相同的字符串但完全不一样
我用 JAVA 和 PHP 进行编程。我在字符串比较方面遇到了一个问题。实际上,根据 JAVA,两个相同的字符串(在我看来)并不相同。
问题背景:
我使用 $userid_hash = sha1($row["profileId"].'helloworld');
设置了 cookie 以及 $userid = $row["profileId"]
。这样做是为了防止用户访问另一个帐户。
现在的问题是我有一些用 JAVA 编写的服务器代码,它对 userid
进行哈希处理并将其与 userid_hash
进行比较。我在控制台中将它们打印出来。两个字符串是相同的。
但问题是我已经将代码的其余部分包裹在 if 语句中,以防出现任何欺诈企图。根据我在 Eclipse 中的控制台,java 将字符串解释为不一样,尽管它们是一样的。这个问题的根源是什么?
我使用它作为我的 SHA1 哈希我的 SHA1 代码语法错误。我使用 "somestring".getBytes("UTF-8");
来调用它。我的 MySQL 数据库是 UTF-8 编码的,我在 Eclipse 中输入的任何字符串也是 UTF-8 编码的。我做错了什么?如何定位问题?
编辑:
这是比较之前java中的println语句:
ab968f939a4869339b5cdb611674bdf4954f2f6a ab968f939a4869339b5cdb611674bdf4954f2f6a
编辑:
If 语句:
if(packageName.toSHA1((profileId+"secret").getBytes("UTF-8")) == profileId_ver)
I'm programming both in JAVA and PHP. I got one problem with string comparison. Actually two strings that are the same (in my perspective) is not the same according to JAVA.
Background to problem:
I set a cookie using $userid_hash = sha1($row["profileId"].'helloworld');
along with $userid = $row["profileId"]
. This is done to prevent a user from accessing another account.
The problem now is that I have some server code written in JAVA that is hashing the userid
and comparing it with userid_hash
. I print them out in the console. Both string is identical.
But the thing is I have wrapped the rest of the code around an if statement in case of any fraud attempts. And java is interpreting the strings as not the same, even though they is, according to my console in Eclipse. What can be the source of this problem?
I'm using this as my SHA1 hash Syntax wrong with my SHA1 code. I call it using "somestring".getBytes("UTF-8");
. And my MySQL database is UTF-8 encoded also any strings I enter in Eclipse is also UTF-8 encoded. What have I done wrong? How can I locate the problem?
EDIT:
This is the println statement in java before comparison:
ab968f939a4869339b5cdb611674bdf4954f2f6a
ab968f939a4869339b5cdb611674bdf4954f2f6a
EDIT:
If statement:
if(packageName.toSHA1((profileId+"secret").getBytes("UTF-8")) == profileId_ver)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您使用 .equals() 而不是 == 吗? == 对于字符串测试它们是否位于内存中的同一位置,而 .equals() 检查它们是否由相同的字符序列组成(这就是您想要的)。
好:
坏:
Are you using .equals() instead of ==? == for strings tests that they're at the same location in memory, whereas .equals() checks that they're made of the same sequence of characters (which is what you'd want here).
Good:
Bad: