【问题标题】:Encrypt/decrypt for Image on IOSIOS上的图像加密/解密
【发布时间】:2014-04-24 13:06:29
【问题描述】:

我们正在使用加密/解密和 UIIMAGE。如果我们在不保存到 iphone 库中的情况下加密和解密和 UIIMAge,它可以正常工作,但如果我们加密、保存到库中、加载(加密的图像)到应用程序中并解密它就不好了。

我们正在使用这个函数来加密/解密/保存/加载

//加密

UIImage *image = self.imageView.image;
CGContextRef ctx;
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
int valor =(height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                                             bitsPerComponent, bytesPerRow, colorSpace,
                                             kCGImageAlphaPremultipliedLast |    kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);


    NSData *data = [NSData dataWithBytes:(const void *)rawData length:sizeof(unsigned char)*valor];
   NSData *encryptedData  = [data AES256EncryptWithKey:@"\"thisIsASecre"];


rawData = [encryptedData bytes];


NSData *dataData2 = [NSData dataWithBytes:rawData length:sizeof(rawData)];

ctx = CGBitmapContextCreate(rawData,
                            CGImageGetWidth( imageRef ),
                            CGImageGetHeight( imageRef ),
                            8,
                            CGImageGetBytesPerRow( imageRef ),
                            CGImageGetColorSpace( imageRef ),
                            kCGImageAlphaPremultipliedLast );

imageRef = CGBitmapContextCreateImage (ctx);
UIImage *rawImage = [UIImage imageWithCGImage:imageRef];

self.imageView.image = rawImage;

UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

CGContextRelease(ctx);

//解密

UIImage *image = self.imageView.image;
CGContextRef ctx;
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
int valor =(height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                                             bitsPerComponent, bytesPerRow, colorSpace,
                                             kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);


   NSData *data = [NSData dataWithBytes:(const void *)rawData length:sizeof(unsigned char)*valor];
   NSData *encryptedData  = [data AES256DecryptWithKey:@"\"thisIsASecre"];


rawData = [encryptedData bytes];




ctx = CGBitmapContextCreate(rawData,
                            CGImageGetWidth( imageRef ),
                            CGImageGetHeight( imageRef ),
                            8,
                            CGImageGetBytesPerRow( imageRef ),
                            CGImageGetColorSpace( imageRef ),
                            kCGImageAlphaPremultipliedLast );

imageRef = CGBitmapContextCreateImage (ctx);
UIImage *rawImage = [UIImage imageWithCGImage:imageRef];

self.imageView.image = rawImage;
image = rawImage;

    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

CGContextRelease(ctx);

// 加载图片

UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;

picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;


[self presentViewController:picker animated:YES completion:NULL];


- (void)imagePickerController:(UIImagePickerController *)picker   didFinishPickingMediaWithInfo:(NSDictionary *)info {

self.imageView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"]; 

[picker dismissViewControllerAnimated:YES completion:NULL];


}

//还有我用来加密/解密的类

- (NSData *)AES256EncryptWithKey:(NSString *)key
{
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)

// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

NSUInteger dataLength = [self length];

//See the doc: For block ciphers, the output size will always be less than or 
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);

size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                      keyPtr, kCCKeySizeAES256,
                                      NULL /* initialization vector (optional) */,
                                      [self bytes], dataLength, /* input */
                                      buffer, bufferSize, /* output */
                                      &numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
    //the returned NSData takes ownership of the buffer and will free it on deallocation
    return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}

free(buffer); //free the buffer;
return nil;
}

- (NSData *)AES256DecryptWithKey:(NSString *)key
{
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)

// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

NSUInteger dataLength = [self length];

//See the doc: For block ciphers, the output size will always be less than or 
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);

size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                      keyPtr, kCCKeySizeAES256,
                                      NULL /* initialization vector (optional) */,
                                      [self bytes], dataLength, /* input */
                                      buffer, bufferSize, /* output */
                                      &numBytesDecrypted);

if (cryptStatus == kCCSuccess) {
    //the returned NSData takes ownership of the buffer and will free it on deallocation
    return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}

free(buffer); //free the buffer;
return nil;
}

有人知道是什么问题吗?

谢谢!

【问题讨论】:

  • @rmaddy 在我看来,好像他正在保存一个有效的图像。他正在加密图像像素,然后使用基本上随机的像素创建图像并将其存储在照片库中。 (并不是说他不应该检查错误返回:)
  • 图片库中存储的图片不是一直转换成jpg的吗?在这种情况下,您将进行有损压缩,并且无法期望您的加密/解密周期能够继续存在。
  • @rmaddy 他没有加密 png 或 jpg。他正在加密像素数据本身。本质上,他只是随机化位图中各个像素的颜色。然后他将随机化的像素转换成一个 CGImage 和一个 UIImage,所以他得到的是一个有效的图像(虽然不是特别有用)
  • @David Oops - 我完全误读了这个。谢谢。
  • 您是否验证过您可以在没有中间照片库的情况下通过加密/解密循环并恢复您的原始照片?您将位图图像存储到库中,它可能存储为 JPG。您是否尝试过通过 UIImagePNGRepresentation 强制循环图像并返回?

标签: ios encryption uiimage aes


【解决方案1】:

如果您将位图图像保存到照片库,它会以 JPG 格式存储。 JPG 的有损格式将完全覆盖您的加密过程。尝试将您的位图图像转换为 PNG 图像,然后保存:

UIImage* pngImage = [UIImage imageWithData:UIImagePNGRepresentation(rawImage)];
UIImageWriteToSavedPhotosAlbum(pngImage, nil, nil, NULL);

【讨论】:

  • 首先,感谢您抽出宝贵时间@David 和 rmaddy。我之前(现在)尝试过这样做,但没有成功。使用您的示例,我可以加密(并像 png 一样保存),但是如果我从库中加密照片或 UIImage 中的图像不起作用。
  • 您是否确认可以通过加密/解密进行往返并取回原始文件?
  • - 首先,我从相机或图库中拍摄照片并加密。我可以看到在 UIImage 中加密的照片并保存了它,它工作正常。如果去画廊,我可以看到加密的照片。 - 其次,使用加密图像(来自没有访问权限的 UIImage 库),我正确解密(我看到图像'原始')并像原始图像一样保存到库中。但是如果我做第二步,从画廊中取出加密的照片,那么我就不再工作了。我知道当您保存到图库时可能会压缩照片时一定有问题。
  • @cserrano 你有没有发现这个问题?
猜你喜欢
  • 1970-01-01
  • 2011-10-12
  • 1970-01-01
  • 2014-10-20
  • 2017-08-12
  • 2013-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多