我正在捎带Encrypt/decrypt for Image on IOS UIImage加密策略,该策略使用Obj-c来实现我在Swift中寻找的东西。现在,忽略那里的“保存到库”问题,因为我在应用程序本身有解密问题。
加密步骤似乎工作正常,我确实将加密图像发送到imageView.image
,但是当我尝试解密时,我得到另一张似乎是加密的图像,从不回到原来的.png图片。
有关我哪里出错的想法? AES加密文件:https://github.com/alexeypro/EncryptDecrypt
加密/解密:
func pixelEncryptDecrypt() {
let image = imageView.image!
var imageRef = image.CGImage
let width = CGImageGetWidth(imageRef)
let height = CGImageGetHeight(imageRef)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bytesPerPixel: UInt = 4
let bytesPerRow: UInt = bytesPerPixel * width
let bitsPerComponent: UInt = 8
let sizeOfRawDataInBytes: Int = Int(height * width * 4)
var rawData = UnsafeMutablePointer<Void>.alloc(sizeOfRawDataInBytes)
let context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue) | CGBitmapInfo.ByteOrder32Big)
CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), imageRef)
var data = NSData(bytes: rawData, length: sizeOfRawDataInBytes)
data = encrypted ? data.AES256DecryptWithKey(key) : data.AES256EncryptWithKey(key)
rawData = data.mutableCopy().mutableBytes
let cryptContext = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue))
imageRef = CGBitmapContextCreateImage(cryptContext);
let encryptedImage = UIImage(CGImage: imageRef)
imageView.image = encryptedImage
encrypted = !encrypted
}
答案 0 :(得分:1)
上述代码的问题在于我假设了图像的alpha通道,经过进一步的研究是一个愚蠢的错误。我将CGImageAlphaInfo.PremultipliedLast
的假定Alpha通道替换为变量let alphaInfo = CGImageGetAlphaInfo(imageRef)
,并将该变量传递给CGBitmapContextCreate
两个调用。
func pixelEncryptDecrypt() {
let image = imageView.image!
var imageRef = image.CGImage
let width = CGImageGetWidth(imageRef)
let height = CGImageGetHeight(imageRef)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bytesPerPixel: UInt = 4
let bytesPerRow: UInt = bytesPerPixel * width
let bitsPerComponent: UInt = 8
let alphaInfo = CGImageGetAlphaInfo(imageRef) // this is what solved the issue.
let sizeOfRawDataInBytes: Int = Int(height * width * 4)
var rawData = UnsafeMutablePointer<Void>.alloc(sizeOfRawDataInBytes)
var context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, CGBitmapInfo(alphaInfo.rawValue) | CGBitmapInfo.ByteOrder32Big)
CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), imageRef)
var data = NSData(bytes: rawData, length: sizeOfRawDataInBytes)
data = encrypted ? data.AES256DecryptWithKey(key) : data.AES256EncryptWithKey(key)
rawData = data.mutableCopy().mutableBytes
context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, CGBitmapInfo(alphaInfo.rawValue))
imageRef = CGBitmapContextCreateImage(context);
let encryptedImage = UIImage(CGImage: imageRef)
imageView.image = encryptedImage
encrypted = !encrypted
}