1

I am using openssl sha256 function with C++. What is the difference between the below two way of calculating sha256 ?

Way1: Just call SHA256 method like below

SHA256((unsigned char*)buffer_to_hash, buffer_size, hashed_payload);

Way2: Use SHA256_CTX, SHA256_Init, SHA256_Update and SHA256_Final. As mentioned here generate sha256 with openssl and C++

Both the programs produce the same result

Example for both methods have been mentioned here

Community
  • 1
  • 1
Nachi
  • 67
  • 6

1 Answers1

2

Modulo bugs and such, the two have basically different intents. The first does batch style processing. That is to say: you give it one complete string, and it produces a hash of that complete string.

The second does hashing incrementally. If you don't have (or want) access to the entire string to be hashed at once, it allows you to read some data, operate on it, read some more, operate on it, and so on until you've read all the data. At the end, you can get the overall hash of the entire data stream.

Just for example, let's assume you're running this on a computer with 4 Gigs of RAM, and you want to hash a 16 gigabyte file. Since the data won't fit in RAM (or even close to it) the second is probably a better choice for this case. Likewise, if you're receiving data over the network, but don't (necessarily) want to store all the raw packets just so you can hash them and (for example) acknowledge receipt.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • I have the entire object in memory, so I can use the way1. But is there a recommended way of doing ? Every tutorial I saw uses way2 and I am not able to find official documentation for way1 – Nachi Aug 30 '13 at 20:54
  • @nachiappan: if you have all the data easily accessible at once, you might as well use the first method. – Jerry Coffin Aug 30 '13 at 20:55
  • I cant find the official documentation for sha256 in http://www.openssl.org/docs/apps/openssl.html – Nachi Aug 30 '13 at 20:58
  • @nachiappan: I'm afraid you're pretty much on your own as far as searching documents goes. If you get really stuck, you might look at: http://codereview.stackexchange.com/q/13288/489 – Jerry Coffin Aug 30 '13 at 21:15
  • @nachiappan While Jerry is correct, you should not use any of the two methods, but the EVP generic interface, see : http://www.openssl.org/docs/crypto/EVP_DigestInit.html – Remi Gacogne Sep 01 '13 at 07:34