SHA1 in Java and PHP with different results

試著忘記壹切 提交于 2019-12-03 16:24:21

Edit

you are using the toHash variable twice in the encodeToString method making your second line of code redundant.

this code

String toHash = "qwerty";
String hash = sha1(toHash); //Prints: b1b3773a05c0ed0176787a4f1574ff0075f7521e

toHash = Base64.encodeToString(toHash.getBytes("ASCII"), Base64.DEFAULT);
hash = sha1(toHash); //Prints: 88bfb2d77c3b42823bab820c1737f03c97d87c1b

is equivalent to this code

String toHash = "qwerty";
toHash = Base64.encodeToString(toHash.getBytes("ASCII"), Base64.DEFAULT);
hash = sha1(toHash); //Prints: 88bfb2d77c3b42823bab820c1737f03c97d87c1b

So essentially in java you are

  • getting Base64 for "qwerty"
  • getting the sha1 on that result

While using PHP your are

  • getting the sha1 for "qwerty"
  • getting the Base64 on that result

I assume you've mistyped

Over 3 years later I ran into the same issue, but this time I figured out the problem. Here is the solution to anyone that stumbles upon this question:

I was using:

sha1("qwerty") == sha1("qwerty")
Base64.encodeToString("qwerty".getBytes(), Base64.DEFAULT) == base64_encode("qwerty")
sha1(Base64.encodeToString("qwerty".getBytes(), Base64.DEFAULT)) != sha1(base64_encode("qwerty"))

The problem with this is the Base64.DEFAULT, the default behavior of Base64 wraps the string (adds \n to string). In order to get the same result as the PHP method you should use Base64.NO_WRAP:

sha1("qwerty") == sha1("qwerty")
Base64.encodeToString("qwerty".getBytes(), Base64.NO_WRAP) == base64_encode("qwerty")
sha1(Base64.encodeToString("qwerty".getBytes(), Base64.NO_WRAP)) == sha1(base64_encode("qwerty"))

After I made this change it started to work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!