I\'m trying to compare two UIImages from the file system to see if they are the same. Obviously, I can\'t use NSObject\'s hash method, since this returns a hash of the objec
Swift Code for hashing a UIImage with the SHA256 algorithm in swift 4.2. There are other algorithms you can use, which are may faster or generate less duplicates but this one is good enough for most usecases.
Just drop the code somewhere in your Project and use it like this: yourUIImage.sha256()
extension UIImage{
public func sha256() -> String{
if let imageData = cgImage?.dataProvider?.data as? Data {
return hexStringFromData(input: digest(input: imageData as NSData))
}
return ""
}
private func digest(input : NSData) -> NSData {
let digestLength = Int(CC_SHA256_DIGEST_LENGTH)
var hash = [UInt8](repeating: 0, count: digestLength)
CC_SHA256(input.bytes, UInt32(input.length), &hash)
return NSData(bytes: hash, length: digestLength)
}
private func hexStringFromData(input: NSData) -> String {
var bytes = [UInt8](repeating: 0, count: input.length)
input.getBytes(&bytes, length: input.length)
var hexString = ""
for byte in bytes {
hexString += String(format:"%02x", UInt8(byte))
}
return hexString
}
}
By the way you need a Bridging Header that imports CommonCrypto. If you don't have one follow these steps:
BridgingHeader
ProjectName/BridgingHeader.h
#import
in your Header FileThe duplicate probability is low, but you can upgrade to SHA512 relatively easy if you got huge datasets:
The Duplicate Probability is about:
Source: https://crypto.stackexchange.com/questions/24732/probability-of-sha256-collisions-for-certain-amount-of-hashed-values