3

我正在尝试实现生成 HttpSession 密钥

我正在生成一个介于 1,000,000 到 9,999,999 之间的随机数,并将其作为 cookie 发送给用户。

是否有可能使这个过程安全?任何人都可以制作一个这样的随机数并尝试访问我的服务器......也许我需要更大的范围?

另一个问题是,如何生成我以前没有生成的数字?现在我每次使用该号码时都会重新生成,是否有可能以更好的方式做到这一点?

4

3 回答 3

3

使用UUID。具体来说,UUID.randomUUID()这是关于碰撞可能性的讨论。

于 2010-08-08T00:22:48.380 回答
2

It sounds a lot like you're trying to implement some basic authentication. Something to try (in pseudo-code; I'm not great with Java on the web):

random_number = rand(1000000, 9999999);
secret = "Some random text here";
timestamp = unix_timestamp(); // Get a UNIX timestamp
user_ip = users_ip(); // Get the user's IP
setcookie("random_number", random_number); // Save the random number
setcookie("timestamp", timestamp);
setcookie("token", sha256(random_number + secret + timestamp + ip)); // Concat and hash everything to form a token

When you want to check if the random number is valid, just pull all the pieces back together and compare it to the token:

random_number = getcookie("random_number");
secret = "Some random text here";
timestamp = int(getcookie("timestamp"));
user_ip = users_ip(); // Get the user's IP
token = sha256(random_number + secret + timestamp + ip);

if(unix_timestamp() - timestamp < 0 || unix_timestamp() - timestamp > timeout) {
    // The token is more than an hour old; it might have been stolen.
}
if(token == getcookie("token")) {
    // The user is valid
} else {
    // The user is invalid
}

This code will block someone from spoofing the random number by making sure it comes from the same IP. You can also use the timestamp stuff to make sure that the user's session expires over time. This'll keep hackers from simply generating a good number and using it forever.

As for the secret, that's a random text chunk. It should be completely random and never be shared. It basically makes your tokens virtually impossible to reverse engineer (otherwise, it's a matter of trying combinations like "number timestamp ip", "ip number timestamp", etc.).

It should also be noted that something like this could be better accomplished with HMAC, but that could be somewhat overkill for what you're looking to do. This solution will do a damn good job as-is.

Hope this helps.

EDIT

It should be noted that your secrets need to be the same for the verification to work.

于 2010-08-08T00:59:59.130 回答
1

我问过自己同样的问题,并在这里找到了一个很好的答案: 在 JavaScript 中创建 GUID / UUID?

您最好阅读有关 RFC 4122 的更多信息,看看这是否是您的意思。我正在将此伪代码用于 NodeJS 项目,它可以完成这项工作。

顺便说一句:为了安全起见,您需要超过 7 位数字。

于 2010-08-08T21:36:45.970 回答