IOS 上图像的加密/解密

2024-05-14

我们正在使用加密/解密和 UIIMAGE。如果我们加密和解密 UIIMAge 而不保存到 iphone 画廊中,它工作正常,但如果我们加密,保存到画廊中,将(加密的图像)加载到应用程序中,然后解密它效果不好。

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

//加密

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;
}

有人知道是什么问题吗?

Thxs!


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

UIImage* pngImage = [UIImage imageWithData:UIImagePNGRepresentation(rawImage)];
UIImageWriteToSavedPhotosAlbum(pngImage, nil, nil, NULL);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

IOS 上图像的加密/解密 的相关文章

随机推荐

  • 如何在同一设备上运行的 Android 应用程序之间传输文件?

    我正在编写一个与 RESTful 服务交互的 Android 应用程序 该 Web 服务本质上是一个文件系统 并提供元数据以及对文件的 CRUD 访问 我的应用程序检索元数据 并通过ContentProvider 我需要添加与我的应用程序在
  • TableView 中图像的大小不正确

    我正在使用来自 URL 的图像创建一个表视图 但图像不会调整到所有视图的大小 直到我将其按入行中 知道为什么会发生这种情况吗 这是一个自定义的表格视图 我的代码是 UITableViewCell tableView UITableView
  • 测试 jQuery UI 工具提示是否打开

    我正在尝试控制自动打开和关闭jQuery 工具提示 http api jqueryui com tooltip 如何测试工具提示的当前状态是否为打开 我正在使用所有内容的最新版本 Thanks 您可以尝试检查是否有任何课程ui toolti
  • 将 OpenXML 文档嵌入到另一个 OpenXml 文档中

    我需要在一个文件夹中收集多个 docx 文件 并将它们 链接 到一个将显示给用户的文档中 现在我已经读过了布莱恩 琼斯的文章 http blogs msdn com brian jones archive 2009 06 30 embedd
  • 获取数组变量的地址是什么意思?

    今天我读到了一段让我很困惑的 C 代码片段 include
  • 在java程序中使用c++ Dll

    我正在尝试使用System LoadLibrary 使用我用 C 编写的一个简单的 dll UseDllInJava java import com sun jna Library import com sun jna Native imp
  • django 中的身份验证方法返回 None

    你好 我在 django 中做了一个简单的注册和登录页面 当想要登录时 登录视图中的身份验证方法不返回任何内容 我的身份验证应用程序 模型 py from django db import models from django contri
  • 如何在Android模拟器中隐藏应用程序图标?

    我有一个应用程序在启动完成后自动启动 但应用程序图标显示在android模拟器中 现在我想向用户隐藏该图标 这样用户就无法知道应用程序已启动 并且他们无法启动该应用程序手动申请 在您的 AndroidManifest xml 文件中 您可能
  • Unicode NFC 规范化可以增加字符串的长度吗?

    如果我将 Unicode 规范化形式 C 应用于字符串 字符串中的代码点数量是否会增加 是的 应用 NFC 标准化后 有些代码点会扩展为多个代码点 内基础多语种飞机 http en wikipedia org wiki Basic Mult
  • 如何让 Streamlit 每 5 秒重新加载一次?

    我必须每 5 秒重新加载 Streamlit 图表 以便在 XLSX 报告中可视化新数据 如何实现这一目标 import streamlit as st import pandas as pd import os mainDir os pa
  • ViewModel 的列表在操作中为 null

    我正在开发我的第一个 ASP NET MVC 3 应用程序 我有一个如下所示的视图 model IceCream ViewModels Note NotesViewModel using Html BeginForm Html Valida
  • CakePHP - 获取上次运行的查询

    我想获取 CakePHP 运行的最后一个查询 我无法在 core php 中打开调试 也无法在本地运行代码 我需要一种方法来获取最后一个 sql 查询并将其记录到错误日志中而不影响实时站点 该查询失败但正在运行 像这样的事情会很棒 this
  • 将事件添加到 Google Maps API InfoWindow 内的元素

    我想在 Google Maps API v3 InfoWindow 内放置一个带有输入字段和提交按钮的表单 提交后 我想调用一个函数 该函数使用输入字段中输入的地址启动方向服务 这是我的代码 我目前只测试方向事件是否被触发 我已经编写了完整
  • 我在 android studio 中使用 kotlin 时出现错误

    为什么会出现这个错误 09 12 16 36 31 502 1886 1886 com getloction nourmedhat smartgate getlocation E AndroidRuntime 致命异常 main 进程 co
  • jQuery 选择器定位具有 id AND class 的元素不起作用

    我有以下事件处理函数 jQuery document on click button submitb function e alert jQuery 包含在 html 文档中 但是 如果我点击 div class submitb Go di
  • WPF 中的屏幕分辨率问题?

    我将在 WPF 中使用以下代码检测分辨率 double height System Windows SystemParameters PrimaryScreenHeight double width System Windows Syste
  • Windows 10 Mobile (10.0.14393) 地理围栏后台任务 (LocationTrigger)

    自从10 0 14393 周年纪念更新 LocationTrigger似乎不起作用 我有 Windows Phone 8 1 应用程序 也适用于 UWP 应用程序 输出到的便携式库Windows Runtime Component图书馆 w
  • wix 3 安装程序:未解析的绑定时变量!(bind.fileVersion.Name.exe)

    我正在尝试使用 Wix3 中的绑定 bind fileVersion 即 3 11 1 由于某些原因 我收到以下错误消息 未解析的绑定时变量 bind fileVersion TestWix3 exe 我的目标是填写 产品 ID 行 特别是
  • 三.js环境光意想不到的效果

    在下面的代码中 我渲染了一些立方体并使用点光源和环境光照亮它们 然而 当设置为 0xffffff 时 AmbientLight 会将侧面的颜色更改为白色 无论其指定的颜色如何 奇怪的是 点光源按预期工作 我怎样才能使环境光表现得像点光 因为
  • IOS 上图像的加密/解密

    我们正在使用加密 解密和 UIIMAGE 如果我们加密和解密 UIIMAge 而不保存到 iphone 画廊中 它工作正常 但如果我们加密 保存到画廊中 将 加密的图像 加载到应用程序中 然后解密它效果不好 我们使用这个函数来加密 解密 保