#pragma mark- DES加密算法
+ (NSString*)encrypt:(NSString*)sText encryptOrDecrypt:(CCOperation)encryptOperation
{
constvoid*dataIn;
size_tdataInLength;
constNSString*key =@"";//和服务器约定的key
if(encryptOperation ==kCCDecrypt)//传递过来的是decrypt解码
{
//解码base64
NSData*decryptData = [GTMBase64decodeData:[sTextdataUsingEncoding:NSUTF8StringEncoding]];//转成utf-8并decode
dataInLength = [decryptDatalength];
dataIn = [decryptDatabytes];
}
else//encrypt
{
NSData* encryptData = [sTextdataUsingEncoding:NSUTF8StringEncoding];
dataInLength = [encryptDatalength];
dataIn = (constvoid*)[encryptDatabytes];
}
CCCryptorStatusccStatus;
uint8_t*dataOut =NULL;//可以理解位type/typedef的缩写(有效的维护了代码,比如:一个人用int,一个人用long。最好用typedef来定义)
size_tdataOutAvailable =0;//size_t是操作符sizeof返回的结果类型
size_tdataOutMoved =0;
dataOutAvailable = (dataInLength +kCCBlockSizeDES) & ~(kCCBlockSizeDES-1);
dataOut =malloc( dataOutAvailable *sizeof(uint8_t));
memset((void*)dataOut,0x0, dataOutAvailable);//将已开辟内存空间buffer的首1个字节的值设为值0
NSString*initIv =@"";//和上面的key一致
constvoid*vkey = (constvoid*) [keyUTF8String];
constvoid*iv = (constvoid*) [initIvUTF8String];
//CCCrypt函数加密/解密
ccStatus =CCCrypt(encryptOperation,//加密/解密
kCCAlgorithmDES,//加密根据哪个标准(des,3des,aes。。。。)
kCCOptionPKCS7Padding,//选项分组密码算法(des:对每块分组加一次密3DES:对每块分组加三个不同的密)
vkey,//密钥加密和解密的密钥必须一致
kCCKeySizeDES,//DES密钥的大小(kCCKeySizeDES=8)
iv,//可选的初始矢量
dataIn,//数据的存储单元
dataInLength,//数据的大小
(void*)dataOut,//用于返回数据
dataOutAvailable,
&dataOutMoved);
NSString*result =nil;
if(encryptOperation ==kCCDecrypt)//encryptOperation==1解码
{
//得到解密出来的data数据,改变为utf-8的字符串
result = [[NSStringalloc]initWithData:[NSDatadataWithBytes:(constvoid*)dataOutlength:(NSUInteger)dataOutMoved]encoding:NSUTF8StringEncoding];
}
else//encryptOperation==0(加密过程中,把加好密的数据转成base64的)
{
//编码base64
NSData*data = [NSDatadataWithBytes:(constvoid*)dataOutlength:(NSUInteger)dataOutMoved];
result = [GTMBase64stringByEncodingData:data];
}
returnresult;
}
GTMBase64文件地址:https://pan.baidu.com/s/1kUTPrqJ