I am using the following code for getting SHA 256 of UIImage
(source: https://stackoverflow.com/a/50931949/10451073)
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
}
}
I'm using it as:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let file = info[UIImagePickerControllerOriginalImage]
{
print((file as? UIImage)?.sha256())
}
self.dismiss(animated: true, completion: nil)
}
However I'm getting SHA 256 of any UIImage wrong. For example, upon checking SHA 256 for this image- https://drive.google.com/open?id=1p9n01qOFahr6I1Q7FPzoDCKcjLjYVivl, I am getting value as 1d6a7c377157c4511183706033898c76c090924ecbf9d47ddff7243237dc9243
instead of getting correct value being 360cd85c64b5e672c48ef948df689a17e41b80a84b9d3d2039143e47a9473395
(verified from: https://hash.online-convert.com/sha256-generator )
Please help me understand what's wrong here and how I should change the above code to get the correct SHA 256 value. Help is much appreciated. Thank you.
EDIT: Upon discussion with @Paulw11 in his answer below I got it that I need to get hash of the file instead of the image. However I am not sure how to change this code to get the same. Please help me with the same.