【发布时间】:2021-09-28 04:31:50
【问题描述】:
我需要生成一些数据的 SHA256。我发现this example 是一个非常好的。现在我的问题是我可以使用自己的密钥生成 sha256。
编辑:
首先,很抱歉问错了问题。我并不是说要更改用于生成 SHA256 的密钥。我真正需要的是,将以下java代码转换为c++
public static String calculateHMAC(String data, String key) throws Exception {
String result;
try {
// get an hmac_sha2 key from the raw key bytes
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA2_ALGORITHM);
// get an hmac_sha1 Mac instance and initialize with the signing key
Mac sha256_HMAC = Mac.getInstance(HMAC_SHA2_ALGORITHM);
sha256_HMAC.init(signingKey);
// compute the hmac on input data bytes
byte[] rawHmac = sha256_HMAC.doFinal(data.getBytes());
// base64-encode the hmac
StringBuilder sb = new StringBuilder();
char[] charArray = Base64.encode(rawHmac);
for ( char a : charArray){
sb.append(a);
}
result = sb.toString();
}
catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
return result;
}
【问题讨论】:
-
sha 是一个哈希函数而不是一个加密方案
-
谢谢。标记已删除。
-
那你的“自己的钥匙”是什么意思?
-
您是否将盐与加密密钥混合在一起?
-
你为什么要改变它? SHA256 的全部意义在于,任何人都可以在一段数据上运行它,并将结果与已知的良好值进行比较,以确认数据的完整性。