Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate SHA256 in c++

Tags:

c++

sha256

I need to generate SHA256 of some data. I found this example is a very good one. Now my question is Can I generate a sha256 by using my own key.

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++

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;
}
like image 544
Nelson T Joseph Avatar asked Jul 23 '15 11:07

Nelson T Joseph


2 Answers

Edit (as OP changed the question):

There are lots of C++ libraries available for cryptographic operations:

  1. OpenSSL (My personal choice, we use this library in our industry products).
  2. Crypto++.

Here's an example of Generate sha256 with OpenSSL and C++.

OLD ANSWER:

SHA-256 is a member of SHA-2 cryptographic hash functions family, which usually generates 256 bits or 32 bytes HASH code from an input message.

It's not an "encryption" mechanism which means, from the HASH (also known as message digest or digest) you can not regenerate the message.

Therefore, we do not need any "keys" to generate SHA-256 message digest.

Moreover, hash functions are considered practically impossible to 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, which concludes reversing is not possible for Hashing. For example,

SHA256(plainText) -> digest

Then there is NO mechanism like inverseSHA256 which can do the following,

// we cannot do the following
inverseSHA256(digest) -> plainText
like image 92
rakeb.mazharul Avatar answered Nov 14 '22 09:11

rakeb.mazharul


I would recommend the free Crypto++ library. Here's a sample for HMAC.

like image 6
l33t Avatar answered Nov 14 '22 08:11

l33t