phpのhmac-SHA1と同等のjava
-
05-07-2019 - |
質問
このphp呼び出しに相当するJavaを探しています:
hash_hmac('sha1', "test", "secret")
java.crypto.Macを使用してこれを試しました、ただし2つは同意しません:
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 Doggenが既に指摘したように、raw出力パラメーターをtrueに設定しない限り、PHPは16進表記を使用してメッセージダイジェストを出力します。
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)-しかし、式全体をチェックしませんでした。
this のメソッドを介してバイト配列を実行するとどうなりますかページ?
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);
Havenはテストしていませんが、これを試してください:
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