1

Why the Java sha256 result different with the Dart sha256 result?

the Dart code

var key = utf8.encode("Message");
var bytes = utf8.encode("secret");


var hmacSha256 = new Hmac(sha256, key); // HMAC-SHA256
var digest = hmacSha256.convert(bytes);

var result = base64Encode(digest.bytes);

the Java code: String secret = "secret"; String message = "Message";

 Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
 SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
  sha256_HMAC.init(secret_key);

  byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
  String result = bytesToBase64String(bytes);
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
肖雄宇
  • 11
  • 1
  • a wild guess - utf8 vs utf16 issue. https://stackoverflow.com/questions/25876632/will-string-getbytesutf-16-return-the-same-result-on-all-platforms – jackycflau Jan 18 '19 at 06:06
  • how about using `secret.getBytes("UTF-8")` and message.getBytes("UTF-8") instead? – jackycflau Jan 18 '19 at 06:10

0 Answers0