在 C++ 中生成 SHA256
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31586701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate SHA256 in c++
提问by Nelson T Joseph
I need to generate SHA256 of some data. I found this exampleis a very good one. Now my question is Can I generate a sha256 by using my own key.
我需要生成一些数据的 SHA256。我发现这个例子是一个很好的例子。现在我的问题是我可以使用我自己的密钥生成一个 sha256。
EDIT:
编辑:
First of all, sorry for wrong question. I don't mean that to change the key used to generate SHA256. I really need is that, to convert the following java code to c++
首先,抱歉问错了问题。我不是说要更改用于生成 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;
}
采纳答案by l33t
回答by rakeb.mazharul
SHA-256 is a member of SHA-2cryptographic hash functions family, which usually generates 256 bits or 32 bytes HASH Codefrom an input message.
SHA-256 是SHA-2加密散列函数家族的成员,通常从输入消息生成 256 位或 32 字节的HASH 代码。
It's not an encryptionmechanism which implies that from the HASH Code, also known as message digestor simply the digest, you can not regenerate the message.
它不是一种加密机制,这意味着您无法从HASH 代码(也称为消息摘要或简称为摘要)中重新生成消息。
Hence there's need no keyto use SHA-256
to generate message digest.
因此不需要使用密钥SHA-256
来生成消息摘要。
Moreover, hash functionsconsidered practically impossibleto invert, that is, to recreate the input data from its hash value (message digest) alone. So You can't "decrypt"a HASH message/message digest to its input message, means reversing is not possible for Hashing. For example,
此外,散列函数被认为实际上不可能反转,即仅从其散列值(消息摘要)重新创建输入数据。因此,您无法将 HASH 消息/消息摘要“解密”为其输入消息,这意味着无法进行哈希处理。例如,
SHA256(plainText) -> digest
then there is NOmechanism like inverseSHA256
which can do the following,
那么就没有inverseSHA256
可以执行以下操作的机制,
inverseSHA256(digest) -> plainText