Skip to content

Instantly share code, notes, and snippets.

@akashkahalkar
Last active January 26, 2020 05:17
Show Gist options
  • Save akashkahalkar/71da218adb4d2684f0bcdbc03a52e9b5 to your computer and use it in GitHub Desktop.
Save akashkahalkar/71da218adb4d2684f0bcdbc03a52e9b5 to your computer and use it in GitHub Desktop.
String extension to suppport MD5, SHA256 hashing functions.
//
// Extension+String.swift
// Extension for string with hashing support
//
// Created by Akash Kahalkar on 24/01/20.
// Copyright © 2020 Akash Kahalkar. All rights reserved.
//
/**
Description:
Message digests are designed to protect the integrity of a piece of
data to detect changes and alterations to any part of a message. They are a type of cryptography
utilizing hash values that can warn the copyright owner of any modifications applied to their work.
A good hash function can be defined as
a. for f(x) = y where y != x
b. for f(x) != f(y) where x != y
c for f(x) = y, f(y) = z, y != z
Sending sensitive text data over network in plain text has vulnerability of being capture by
MITI (Man In The Middle Attack) where in attaker can get access to or can modify sesitive data,
these include but not limited to passwords, creditcard numbers, security pins etc. A better
approach is to capture sensitive data, create hash and then use this hash for furthur usage such
as storage or sending over network.
The given String extension is usefull for creating message digest for any string value in swift.
this currently support MD5 and SHA256 algorithm.
Usage:
let password = "SecretText"
let hashedMD5Password = password.getHash(type: .md5)
let hashedSHA256Password = password.getHash(type: .md5)
**/
import Foundation
import CommonCrypto
extension String {
enum HashType {
case sha256, md5
}
func getHash(type: HashType) -> String {
let messageData = self.data(using:.utf8)!
var digestData = getDigest(for: type, with: messageData)
_ = digestData.withUnsafeMutableBytes {digestBytes in
messageData.withUnsafeBytes {messageBytes in
hashData(into: type, messageBytes, CC_LONG(messageData.count), digestBytes)
}
}
return digestData.map { String(format: "%02hhx", $0) }.joined()
}
private func getDigest(for type: HashType, with data: Data) -> Data {
switch type {
case .sha256:
return Data(count: Int(CC_SHA256_DIGEST_LENGTH))
case .md5:
return Data(count: Int(CC_MD5_DIGEST_LENGTH))
}
}
private func hashData(into type: HashType,
_ data: UnsafeRawPointer!,
_ len: CC_LONG,
_ md: UnsafeMutablePointer<UInt8>!) -> UnsafeMutablePointer<UInt8>! {
switch type {
case .sha256:
return CC_SHA256(data, len, md)
case .md5:
return CC_MD5(data, len, md)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment