Hi All,
Encryption has always been a key feature in apps developed in any Platform. Used widely in iOS Apps.
So lets today explore the
SHA algorithm for encryption and decryption.
What is it
The algorithm is named as
Secure Hash Algorithm. Highly used for Digital Signatures. This algorithm generates a unique and non-reversible text. Suppose if you are able to get the secret key used for hashing then alone with that you cannot generate the actual data making it secure. Also, two different kinds of data with the same secret hash code cannot generate the same hashed string.
However, with SHA1
two different strings with the
same hash code generated the
same hashed result resulting in a collision which led the users to move to SHA256 for better security. The larger is the bit size of hash the larger is the combination option and higher is the security but definitely, the implementation is important too.
But will longer hash length have any impact on performance? Yes, it may.
It can be broken down as
SHA[Number] [Output Size in Bits]
- SHA0 [160]
- SHA1 [160]
- SHA2 [SHA224, SHA256, SHA384, SHA512]
- SHA3 [SHA224, SHA256, SHA384, SHA512]
Plain Text >> Hash Algorithm >> Hashed Text
Utilize the Encryption logic in iOS App
1. Add Security Framework
2. Import CommonCrypto.h
Objective C
- (NSData *)hmacForKeyAndData:(NSString *)key data:(NSString *)data
{
unsigned char cHMAC[CC_SHA1_DIGEST_LENGTH];
const char *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding];
const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];
CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
return [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];
}
Swift
func hmac(forKeyAndData key: String?, data: String?) -> Data?
{
let cHMAC = [UInt8](repeating: 0, count: CC_SHA1_DIGEST_LENGTH)
let cKey = Int8(key?.cString(using: String.Encoding.ascii.rawValue) ?? 0)
let cData = Int8(data?.cString(using: String.Encoding.ascii.rawValue) ?? 0)
CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC)
return Data(bytes: &cHMAC, length: MemoryLayout<cHMAC>.size)
}