在 C++ 中生成 SHA256
Generate SHA256 in c++
我需要生成一些数据的 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;
}
编辑(OP 更改了问题):
有很多 C++ 库可用于加密操作:
这是 Generate sha256 with OpenSSL and C++ 的示例。
旧答案:
SHA-256 是 SHA-2 密码哈希函数家族的成员,通常从输入消息中生成 256 位或 32 字节 HASH 代码。
这不是一种“加密”机制,这意味着从 HASH(也称为消息摘要或摘要)您无法重新生成 消息。
因此,我们不需要任何“密钥”来生成 SHA-256
消息摘要。
此外,哈希函数实际上被认为 不可能 反转,即仅从其哈希值(消息摘要)重新创建输入数据。因此,您不能将 HASH message/message 摘要“解密”到其输入消息,从而得出结论,哈希不可能进行逆向。例如,
SHA256(plainText) -> digest
然后有NO机制像inverseSHA256
可以做以下事情,
// we cannot do the following
inverseSHA256(digest) -> plainText
我需要生成一些数据的 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;
}
编辑(OP 更改了问题):
有很多 C++ 库可用于加密操作:
这是 Generate sha256 with OpenSSL and C++ 的示例。
旧答案:
SHA-256 是 SHA-2 密码哈希函数家族的成员,通常从输入消息中生成 256 位或 32 字节 HASH 代码。
这不是一种“加密”机制,这意味着从 HASH(也称为消息摘要或摘要)您无法重新生成 消息。
因此,我们不需要任何“密钥”来生成 SHA-256
消息摘要。
此外,哈希函数实际上被认为 不可能 反转,即仅从其哈希值(消息摘要)重新创建输入数据。因此,您不能将 HASH message/message 摘要“解密”到其输入消息,从而得出结论,哈希不可能进行逆向。例如,
SHA256(plainText) -> digest
然后有NO机制像inverseSHA256
可以做以下事情,
// we cannot do the following
inverseSHA256(digest) -> plainText