PHP의 HMAC-SHA1에 해당하는 Java
-
05-07-2019 - |
문제
이 PHP 호출과 동등한 Java를 찾고 있습니다.
hash_hmac('sha1', "test", "secret")
나는 이것을 사용하여 시도했다 java.crypto.mac, 그러나 두 사람은 동의하지 않습니다.
String mykey = "secret";
String test = "test";
try {
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec secret = new SecretKeySpec(mykey.getBytes(),"HmacSHA1");
mac.init(secret);
byte[] digest = mac.doFinal(test.getBytes());
String enc = new String(digest);
System.out.println(enc);
} catch (Exception e) {
System.out.println(e.getMessage());
}
key = "Secret"및 Test = "Test"가있는 출력은 일치하지 않는 것 같습니다.
해결책
실제로 그들은 동의합니다.
Hans Dogggen은 이미 PHP가 출력 한 것처럼, 원시 출력 매개 변수를 true로 설정하지 않는 한 육각형 표기법을 사용하여 메시지 다이제스트를 출력합니다.
Java에서 동일한 표기법을 사용하려면 다음과 같은 것을 사용할 수 있습니다.
for (byte b : digest) {
System.out.format("%02x", b);
}
System.out.println();
그에 따라 출력을 포맷합니다.
다른 팁
Java에서 이것을 시도 할 수 있습니다.
private static String computeSignature(String baseString, String keyString) throws GeneralSecurityException, UnsupportedEncodingException {
SecretKey secretKey = null;
byte[] keyBytes = keyString.getBytes();
secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(secretKey);
byte[] text = baseString.getBytes();
return new String(Base64.encodeBase64(mac.doFinal(text))).trim();
}
이것은 내 구현입니다.
String hmac = "";
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec secret = new SecretKeySpec(llave.getBytes(), "HmacSHA1");
mac.init(secret);
byte[] digest = mac.doFinal(cadena.getBytes());
BigInteger hash = new BigInteger(1, digest);
hmac = hash.toString(16);
if (hmac.length() % 2 != 0) {
hmac = "0" + hmac;
}
return hmac;
PHP는 Java가 생성하는 바이트에 대해 HEX 표기법을 사용하는 것 같습니다 (1A = 26). 그러나 전체 표현식을 확인하지 않았습니다.
메소드를 통해 바이트 배열을 실행하면 어떻게됩니까? 이것 페이지?
HMACMD5에 대한 나의 구현 - HMACSHA1로 알고리즘을 변경합니다.
SecretKeySpec keySpec = new SecretKeySpec("secretkey".getBytes(), "HmacMD5");
Mac mac = Mac.getInstance("HmacMD5");
mac.init(keySpec);
byte[] hashBytes = mac.doFinal("text2crypt".getBytes());
return Hex.encodeHexString(hashBytes);
테스트하지 않았지만 이것을 시도하십시오.
BigInteger hash = new BigInteger(1, digest);
String enc = hash.toString(16);
if ((enc.length() % 2) != 0) {
enc = "0" + enc;
}
이것은 Java의 MD5와 SHA1이 PHP를 일치시키는 내 방법의 스냅 샷입니다.
이런 식으로 나는 php에서 hash_hmac을 사용하는 것과 똑같은 문자열을 얻을 수 있습니다.
String result;
try {
String data = "mydata";
String key = "myKey";
// Get an hmac_sha1 key from the raw key bytes
byte[] keyBytes = key.getBytes();
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
// Get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
// Compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(data.getBytes());
// Convert raw bytes to Hex
byte[] hexBytes = new Hex().encode(rawHmac);
// Covert array of Hex bytes to a String
result = new String(hexBytes, "ISO-8859-1");
out.println("MAC : " + result);
}
catch (Exception e) {
}
제휴하지 않습니다 StackOverflow