Swift sha256 – iOS 10 Minute Quick Hack

by Applied Informatics

Here is a quick hack for generating sha256 encoded string in iOS.

Generating a SHA256 string in iOS is simple, first thing to do is to add the CommonCrypto library to your bridging header. If you don’t have a bridging header read on how to create one HERE.

You need to include
#import <CommonCrypto/CommonDigest.h>

Next add the following function to your project somewhere, typically we have a file called “Common.swift” that we dump utilities such as this into, though you can choose whatever name you want.

func sha256(data : NSData) -> String {

let res = NSMutableData(length: Int(CC_SHA256_DIGEST_LENGTH))

CC_SHA256(data.bytes, CC_LONG(data.length), UnsafeMutablePointer(res!.mutableBytes))

// There is a better way to do this .... but this is a quick hack

return "\(res!)".stringByReplacingOccurrencesOfString("", withString: "").stringByReplacingOccurrencesOfString(" ", withString: "")


Now using this function is as easy as follows :

let sha256String = sha256("somestringtoencode".dataUsingEncoding(NSUTF8Encoding)!)

The variable sha256String now contains your sha256 encoding!

This blog is part of our iOS 10 Minute Quick Hack series.

One thought on “Swift sha256 – iOS 10 Minute Quick Hack”

  1. Hello,
    a Berlin based hospital has asked us to look for ResearchKit for Android as they want to provide their study app to both platforms (iOS and Android).

    How could we get access to the Android ResearchKit? Is it already final or is there a dev version for testing purposes available?


Leave a Reply

Your email address will not be published. Required fields are marked *

Mobile Research Apps

We have deep expertise in design and development of mobile research apps that work on both iOS and Android securely.

Contact us now

Popular Posts