需求
用原生 Java 及 Node.js 实现 SHA256 加密。
准备工作
- 加密 secret:
bbca32faa8f75c67f46f01c7ede3959a
- 加密 key:
123456
- 时间戳:
1239899287986
- 加密数据:
key
+ 时间戳 - 编码规范:
utf-8
- 预期结果:
0d16a0f153940f67c97ef1ab2cdfcba866f476fa6ddd6831b5a017848694aaba
Node.js 实现
const crypto = require('crypto');
const secret = 'bbca32faa8f75c67f46f01c7ede3959a';
const key = '123456';
const timestamp = 1239899287986;
const algorithm = 'sha256';
const expected = '0d16a0f153940f67c97ef1ab2cdfcba866f476fa6ddd6831b5a017848694aaba';
const actual = crypto
.createHmac(algorithm, secret)
.update(key + timestamp)
.digest('hex');
console.log(actual);
console.assert(actual === expected, 'not equal');
// 0d16a0f153940f67c97ef1ab2cdfcba866f476fa6ddd6831b5a017848694aaba
原生 Java 实现
package demo;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class Sha256Demo {
public static void main(String[] args) {
String secret = "bbca32faa8f75c67f46f01c7ede3959a";
String key = "123456";
Long timestamp = 1239899287986L;
String data = key + timestamp;
String actual = encryptSha256(secret, data);
System.out.println("actual: " + actual);
String expected = "0d16a0f153940f67c97ef1ab2cdfcba866f476fa6ddd6831b5a017848694aaba";
System.out.println(expected.equals(actual));
}
private static String encryptSha256(String secret, String data) {
try {
String algorithm = "HmacSHA256"; // supported algorithms: 'HmacSHA1', 'HmacSHA256'
String encode = "utf-8";
Mac sha256_HMAC = Mac.getInstance(algorithm);
SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(encode), algorithm);
sha256_HMAC.init(secretKey);
byte[] hash = sha256_HMAC.doFinal(data.getBytes(encode));
return byte2Hex(hash);
} catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
e.printStackTrace();
return "";
}
}
private static String byte2Hex(byte[] bytes) {
StringBuffer stringBuffer = new StringBuffer();
String temp = null;
for (int i = 0; i < bytes.length; i++) {
temp = Integer.toHexString(bytes[i] & 0xFF);
if (temp.length() == 1) {
stringBuffer.append("0");
}
stringBuffer.append(temp);
}
return stringBuffer.toString();
}
}
执行结果:
actual: 0d16a0f153940f67c97ef1ab2cdfcba866f476fa6ddd6831b5a017848694aaba
true
拓展
由于都是原生实现,加密算法也对 SHA1
有效。只需将 Node.js
实现中的第 6 行改为 sha1
,Java
原生实现中的第 25 行改为 HmacSHA1
即可。