我正在尝试在Python中翻译这行代码:
signature = hmac.new("1234abcd", b64, hashlib.sha384).hexdigest()
我正在尝试使用SHA-384获取带有密钥的字符串的哈希值。但是,我正在尝试使用Java,有人知道该怎么做吗?
另外,我被要求提供一个nonce。有什么要求?
答案 0 :(得分:3)
您可以使用MessageDigest
方法将字节转换为十六进制:
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA384";
private static String bytesToHex(final byte[] hash) {
final StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
final String hex = Integer.toHexString(0xff & hash[i]);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
public static void main(final String... args) throws NoSuchAlgorithmException, InvalidKeyException {
final String nonce = "nonce";
final String message = "test string";
SecretKeySpec signingKey = new SecretKeySpec(nonce.getBytes(), HMAC_SHA1_ALGORITHM);
final Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
System.out.println(bytesToHex(mac.doFinal(message.getBytes())));
}