This is a creation in Article, where the information may have evolved or changed.
Recent work related to HmacSHA256 encryption, PHP colleague Consulting I said can not encrypt, in fact, the problem is very simple, recorded, convenient for those who are not careful code friends ^_^.
How to encrypt HmacSHA256 in Java:
public static String SignUp(String secretKey, String plain) {
byte[] keyBytes = secretKey.getBytes();
byte[] plainBytes = plain.getBytes();
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(keyBytes, "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] hashs = sha256_HMAC.doFinal(plainBytes);
StringBuilder sb = new StringBuilder();
for (byte x : hashs) {
String b = Integer.toHexString(x & 0XFF);
if (b.length() == 1) {
b = '0' + b;
}
// sb.append(String.format("{0:x2}", x));
sb.append(b);
}
return sb.toString();
// String hash =
// Base64.encodeToString(sha256_HMAC.doFinal(plainBytes),
// Base64.DEFAULT);
// return hash;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
It is broadly divided into these sections to analyze:
1. Get SHA256 Instances
2. Generate an encryption key
3. Initialize the SHA256 instance with this encryption key
4. Use this instance to encrypt the generated hash based on the provided string
4. Finally, the whole thing is to switch to 16 and then output the string.
The PHP section is simple
The best language in the world, right!!
function ($plain,$secretKey){
return bin2hex(hash_hmac("sha256",utf8_encode($plain) , utf8_encode($secretKey), true));
}
For ease of comparison, I declare the function arguments to be the same name.
Note the Hash_hmac declaration in the PHP Documentation:
string hash_hmac (string $ algo, string $ data, string $ key [, bool $ raw_output = FALSE])
algo
The name of the hash algorithm to use, for example: "md5", "sha256", "haval160,4", etc. For a list of supported algorithms, see hash_algos ().
data
The message to be hashed.
key
The key used when generating the message digest using HMAC.
raw_output is set to TRUE to output raw binary data and FALSE to output lowercase hexadecimal strings.
Just because Java engineers pass parameters to PHP's parameters, which leads to PHP engineers? Monte b!
Golang Partial post-update