URL加解密

背景介绍

加密方式

  • 加密:首先对字符串记性AES128加密,然后进行base64加密(主要是为了去除特殊字符)
  • 解密:先base64解密,然后在AES128解密即可还原数据
  • 其中base64加解密使用 GTMBase64添加两个方法
+ (NSString*)encodeBase64Data:(NSData *)data {
data = [GTMBase64 encodeData:data];
NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return base64String;
} + (NSData*)decodeBase64String:(NSString * )input {
NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
data = [GTMBase64 decodeData:data];
return data;
}

AES128使用系统CommonCrypto/CommonCryptor.h实现 //用于AES

添加NSData分类,增加两个方法

#pragma mark - AES128位加解密
- (NSData *)AES128EncryptWithKey:(NSString *)key { char keyPtr[kCCKeySizeAES128 + 1];
memset(keyPtr, 0, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]; NSUInteger dataLength = [self length]; size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize); size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmAES,
kCCOptionPKCS7Padding|kCCOptionECBMode,
keyPtr,
kCCBlockSizeAES128,
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 *)AES128DecryptWithKey:(NSString *)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES128+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|kCCOptionECBMode,
keyPtr,
kCCBlockSizeAES128,
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;
}

直奔主题

  • AFNetworking 的post请求如下
- (AFHTTPRequestOperation *)POST:(NSString *)URLString
parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
  • 其中URLString可以作为最基础的,不需要加密

    parameters 就是我们需要加密的地方,这是一个字典,因为AFN会对这个parameters进行解析,所以对这个参数集合进行一次包装,拼接成一个字符串。然后对字符串进行加密。

原来的代码是这样请求数据的

NSMutableDictionary *para = [NSMutableDictionary dictionary];
para[@"method"] = @"securityAdd";
para[@"userId"] = userId;
para[@"userPsw"] = userPsw;
para[@"content"] = @"ddddd123891237"; NSString *url = [NSString stringWithFormat:@"https://%@:82/frame/webInteface.do?", NHBaseURL];
AFHTTPRequestOperation *operation = [NetWorkInst POST:url parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
} success:^(AFHTTPRequestOperation *operation, id responseObject) { }];

加密后代码是这样的

NSMutableDictionary *para = [NSMutableDictionary dictionary];
para[@"method"] = @"securityAdd";
para[@"userId"] = userId;
para[@"userPsw"] = userPsw;
para[@"content"] = @"ddddd123891237"; // 开始加密,格式化数据****************************
NSString *str = [NSString stringWithFormat:@"'method':'securityAdd','userId':'%@','userPsw':'%@','content':'%@'",userId,userPsw,content];
NSLog(@"原始数据:%@",str);
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSData *aaa = [data AES128EncryptWithKey:@"song.com"]; // aes加密
NSLog(@"加密AES128后:%@",aaa);
NSString *bbb = [PublicMethod encodeBase64Data:aaa];//base64加密
NSLog(@"base64加密后:%@",bbb); NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[@"info"] = bbb; // 开始解密****************************
NSData *da = [PublicMethod decodeBase64String:bbb]; //base64解密
NSString *ccc = [[NSString alloc] initWithData:da encoding:NSUTF8StringEncoding];
NSLog(@"base64解密后:%@",ccc);
NSData *ddd = [da AES128DecryptWithKey:@"song.com"];// aes解密
NSString *eee = [[NSString alloc] initWithData:ddd encoding:NSUTF8StringEncoding];
NSLog(@"解密AES128后:%@",eee); NSString *url = [NSString stringWithFormat:@"https://%@:82/frame/webInteface.do?", NHBaseURL];
AFHTTPRequestOperation *operation = [NetWorkInst POST:url parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
} success:^(AFHTTPRequestOperation *operation, id responseObject) { }];

欢迎关注公众号

iOS URL加解密的更多相关文章

  1. iOS,信息加解密

    1.AES加解密 AES加解密 // //  AESEncryptAndDecrypt.h //  NSData扩展方法,用于处理aes加解密 // //  Created by Vie on 16/ ...

  2. iOS RSA加解密签名和验证

    转自:http://www.jianshu.com/p/81b0b54436b8 Pre:在公司负责了一个项目,需要用到iOS RSA验证签名的功能.后台给我的仅仅是一个公钥的字符串.经过起初的一段时 ...

  3. iOS RC4加解密算法

    -(NSString *)encrypt:(NSString *)string withKey:(NSString *)key{ self.sBox = [[self frameSBox:key] m ...

  4. 加解密、PKI与CA基础

    介绍 这门知识如果以前尝过的各位想必都知道:枯燥无比!因此在文中我会尽量讲的生动些,举一些例子,并试图以一个完整的例子来贯穿整个讲述过程.今年又恰逢莎翁逝世400周年,一方面也为了纪念这位伟大的作家. ...

  5. DES跨(C# Android IOS)三个平台通用的加解密方法

          #region   跨平台加解密(c# 安卓 IOS)       //  public static string sKey = "12345678";       ...

  6. .net 安卓IOS跨平台des加解密双向的(可以互相加解密)

    #region 跨平台加解密(c# 安卓 IOS) // public static string sKey = "12345678"; // /// // /// 解密 // / ...

  7. 【iOS】FMDB/SQLCipher数据库加解密,迁移

    2016-04-19更新:本文代码可能有些问题,请移步 http://zhengbomo.github.io/2016-04-18/sqlcipher-start/ 查看 sqlite应用几乎在所有的 ...

  8. java与IOS之间的RSA加解密

    很简单的一个需求,ipad端给密码RSA加密,传到java后台,解密.RSA加密算法是基于一个密钥对的,分为公钥和私钥,一般情况公钥加密,私钥解密,但也可私钥加密,公钥解密.还可以验签,就是先用私钥对 ...

  9. URL加载系统----iOS工程师必须熟练掌握

    URL加载系统----iOS工程师必须熟练掌握     iOS根本离不开网络——不论是从服务端读写数据.向系统分发计算任务,还是从云端加载图片.音频.视频等.   当应用程序面临处理问题的抉择时,通常 ...

随机推荐

  1. python常见异常及解决方法

    异常1: ValueError: unsupported hash type sha224 ERROR:root:code for hash sha256 was not found. Traceba ...

  2. mysql五种日期函数

    create table timess( id int primary key auto_increment, YEARs ——” DATEs DATE ——” TIMEs TIME ::——::” ...

  3. 使用intellij idea创建JSP和引入Tomecat包

    首先我们需要按照好intellij idea 如果没有安装好,这里有下载按照教程:https://www.cnblogs.com/weibanggang/p/9395702.html 首先我们创建一个 ...

  4. 优雅的QSignleton (五) 优雅地进行GameObject命名

      这段时间空调吹感冒了,休息了好久 ​ 本篇介绍QSingleton最重要的功能,是它让QSingleton称得上优雅.相关内容之前介绍过. 代码如下: MonoSingletonPath.cs n ...

  5. C# sqlhelp

    public class SqlHelp { //数据库连接字符串 public static string connectionString = ConfigurationManager.Conne ...

  6. 在CentOS7系统上安装MySQL数据库

    1.下载安装MySQL官方repo文件 下载MySQL的官方repo文件 [root@centos7 ~]# wget -i -c http://dev.mysql.com/get/mysql57-c ...

  7. Spring知识点小结(一)

    一.Spring的简介 1.spring是一个full-stack轻量级开源框架    2.spring的两大核心        IoC: inverse of control  控制反转:反转是对象 ...

  8. django-基于中间件实现限制ip频繁访问

    ########django-基于中间件写一个限制频繁登陆######## 额额,标题已经很醒目了,通过中间件去实现,其他方法也可以实现 浏览器前端传来的请求,必须通过中间件,才能到后面路由,视图函数 ...

  9. jquery mobile 移动web(4)

    下拉菜单: 设置label 元素的for 属性为 select label 元素的文本内容作为选项的名称 定义div元素并设置data-role 属性值为 fieldcontain. <div ...

  10. c c++面试----c工程开发之链接

    多数c语言的初学者对c工程开发过程各个阶段的作用理解不到位,而这方面的的知识又是实际开发过程中经常用到的技能点,所以就成为面试考察中一个重要的考察方面.例如:头文件的作用.头文件的内容:链接的作用和意 ...