w PHP Mam następującą funkcję:dlaczego hash_hmac PHP („sha256”) daje inny wynik niż Java sha256_HMAC
base64_encode(hash_hmac('sha256', $data, $secret, false));
Próbuję utworzyć funkcję w Javie, które dadzą ten sam wynik dla same parametry "dane" i "tajne".
Próbowałem korzystać z tej funkcji:
public static String base64sha256(String data, String secret) {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] res = sha256_HMAC.doFinal(data.getBytes());
return Base64.encodeToString(res, Base64.NO_WRAP);
}
Ale mam różne wyniki dla tego samego wejścia
UPDATE: Ta funkcja działa. Cieszyć się.
public static String base64sha256(String data, String secret) {
String hash = null;
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] res = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
hash = getHex(res);
hash = Base64.encodeToString(hash.getBytes("UTF-8"), Base64.NO_WRAP);
} catch (Exception e){}
return hash;
}
static final String HEXES = "abcdef";
public static String getHex(byte [] raw) {
if (raw == null) {
return null;
}
final StringBuilder hex = new StringBuilder(2 * raw.length);
for (final byte b : raw) {
hex.append(HEXES.charAt((b & 0xF0) >> 4))
.append(HEXES.charAt((b & 0x0F)));
}
return hex.toString();
}
kodowanie danych może? ANSI vs UTF-8 na przykład? – gtgaxiola
Próbowałem używać getBytes ("UTF-8") na obu parametrach i nadal nie jest to ten sam wynik co wersja PHP –
Zobacz ten Q & A http://stackoverflow.com/q/4680661/ gdzie mówią o 'String.getBytes() 'i ten jeden http://stackoverflow.com/q/23066005/ te zostały znalezione w" Powiązane ". –