Skip to content

Instantly share code, notes, and snippets.

@dedeexe
Created September 18, 2018 11:31
Show Gist options
  • Save dedeexe/41d208f4a5857bb08acdd75c58c55dbb to your computer and use it in GitHub Desktop.
Save dedeexe/41d208f4a5857bb08acdd75c58c55dbb to your computer and use it in GitHub Desktop.
Hash using Swift + Common Crypto
//
// Data+hash.swift
// HashTools
//
// Created by dede.exe on 17/09/18.
// Copyright © 2018 dede.exe. All rights reserved.
//
import Foundation
extension Data {
struct Hash {
private var value : Data
init(value:Data) {
self.value = value
}
var md5 : Data {
var value = self.value
var digestData = Data(count: Int(CC_MD5_DIGEST_LENGTH))
_ = digestData.withUnsafeMutableBytes { bytes in
value.withUnsafeBytes{ valueBytes in
CC_MD5(valueBytes, CC_LONG(value.count), bytes)
}
}
return digestData
}
var sha1 : Data {
var value = self.value
var digestData = Data(count: Int(CC_SHA1_DIGEST_LENGTH))
_ = digestData.withUnsafeMutableBytes { bytes in
value.withUnsafeBytes{ valueBytes in
CC_SHA1(valueBytes, CC_LONG(value.count), bytes)
}
}
return digestData
}
var sha256 : Data {
var value = self.value
var digestData = Data(count: Int(CC_SHA256_DIGEST_LENGTH))
_ = digestData.withUnsafeMutableBytes { bytes in
value.withUnsafeBytes{ valueBytes in
CC_SHA256(valueBytes, CC_LONG(value.count), bytes)
}
}
return digestData
}
}
var hash : Hash {
return Hash(value: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment