How can I compute a SHA-2 (ideally SHA 256 or SHA 512) hash in iOS?

This is what I’m using for SHA1: #import <CommonCrypto/CommonDigest.h> + (NSData *)sha1:(NSData *)data { unsigned char hash[CC_SHA1_DIGEST_LENGTH]; if ( CC_SHA1([data bytes], [data length], hash) ) { NSData *sha1 = [NSData dataWithBytes:hash length:CC_SHA1_DIGEST_LENGTH]; return sha1; } return nil; } Replace CC_SHA1 with CC_SHA256 (or whichever you need), as well as CC_SHA1_DIGEST_LENGTH with CC_SHA256_DIGEST_LENGTH.

How to use OpenSSL’s SHA256 functions

You make a very common beginners mistake… Putting the libraries you link with in the wrong place on the command line when you build. Dependencies are reversed on the command line, so something that depends on something else should actually be put before what it depends on on the command line. In your example, you … Read more

Obtain SHA-256 string of a string

The implementation could be like that public static String sha256_hash(String value) { StringBuilder Sb = new StringBuilder(); using (SHA256 hash = SHA256Managed.Create()) { Encoding enc = Encoding.UTF8; Byte[] result = hash.ComputeHash(enc.GetBytes(value)); foreach (Byte b in result) Sb.Append(b.ToString(“x2”)); } return Sb.ToString(); } Edit: Linq implementation is more concise, but, probably, less readable: public static String sha256_hash(String … Read more

Generate sha256 with OpenSSL and C++

Here’s how I did it: void sha256_hash_string (unsigned char hash[SHA256_DIGEST_LENGTH], char outputBuffer[65]) { int i = 0; for(i = 0; i < SHA256_DIGEST_LENGTH; i++) { sprintf(outputBuffer + (i * 2), “%02x”, hash[i]); } outputBuffer[64] = 0; } void sha256_string(char *string, char outputBuffer[65]) { unsigned char hash[SHA256_DIGEST_LENGTH]; SHA256_CTX sha256; SHA256_Init(&sha256); SHA256_Update(&sha256, string, strlen(string)); SHA256_Final(hash, &sha256); int … Read more

Hashing passwords with MD5 or sha-256 C#

Don’t use a simple hash, or even a salted hash. Use some sort of key-strengthening technique like bcrypt (with a .NET implementation here) or PBKDF2 (with a built-in implementation). Here’s an example using PBKDF2. To generate a key from your password… string password = GetPasswordFromUserInput(); // specify that we want to randomly generate a 20-byte … Read more