欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS 常用的加密技术-MD5,DES,AES

程序员文章站 2024-03-16 20:24:46
...

网络请求中为了数据的安全性 , 通常会对数据进行加密之后再以JSON形式传输到后台 . 就算请求被拦截 , 也可以有效的保护用户信息的安全性 . 今天就分享一下 常用的一些加密技术 .


MD5 加密

MD5是利用哈希算法来加密的。哈希算法是一种摘要算法,MD5有以下两个最主要的特性 , 常用于用户密码的加密使用。

  • 加密的不可逆性,只能够加密,不能够解密。
  • 任意长度的明文经过加密后长度都是固定的,长度为16进制32位。

使用MD5 加密之前应该先导入框架 #import "CommonCrypto/CommonDigest.h"

// MD5 转码
-(NSString *) md5: (NSString *) inPutText
{
    const char *cStr = [inPutText UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    
    return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] lowercaseString];
}

DES加密

DES 加密是一种对称式加密方法 . 其特点是

  • 加密与解密使用同一套** , 使用方便 .
  • 具有相当高的复杂性, 其安全性仅以加***的保密为基础 .

与MD5 一样也需要导入框架#import "CommonCrypto/CommonDigest.h"
然后还要导入GTMBase64文件

//加密
+(NSString *)decryptWithContent:(NSString *)content
{
    //** "abc123"
    char * keyChar =(char*)[@"abc123" UTF8String];
    
    if (content == nil) {
        content = @"";
    }
    
    NSString *jm = [NSString stringWithCString:encryptWithKeyAndType([content UTF8String], kCCEncrypt, keyChar) encoding:NSUTF8StringEncoding];
    
    return jm;
    
}
//解密
+ (NSData *)encryptWithContent:(NSData *)content
{
    NSString *contentStr = [[NSString alloc] initWithData:content encoding:NSUTF8StringEncoding];
    
    if (contentStr == nil || [contentStr isEqualToString:@""]) {
        return nil;
    }
    
    const char * contentChar =[contentStr UTF8String];
    //** "abc123"
    char * keyChar =(char*)[@"abc123" UTF8String];
    const char *miChar;
    miChar = encryptWithKeyAndType(contentChar, kCCDecrypt, keyChar);
    if (miChar == nil) {
        miChar = "";
    }
    
    NSString *zmStr = [NSString stringWithCString:miChar encoding:NSUTF8StringEncoding];
    if (zmStr == nil) {
        zmStr [email protected]"";
    }
    return [zmStr dataUsingEncoding:NSUTF8StringEncoding];
}
//核心代码
static const char* encryptWithKeyAndType(const char *text,CCOperation encryptOperation,char *key)
{
    NSString *textString=[[NSString alloc]initWithCString:text encoding:NSUTF8StringEncoding];
    //      NSLog(@"[[item.url description] UTF8String=%@",textString);
    const void *dataIn;
    size_t dataInLength;
    
    if (encryptOperation == kCCDecrypt)//传递过来的是decrypt 解码
    {
        //解码 base64
        NSData *decryptData = [GTMBase64 decodeData:[textString dataUsingEncoding:NSUTF8StringEncoding]];//转成utf-8并decode
        dataInLength = [decryptData length];
        dataIn = [decryptData bytes];
    }
    else  //encrypt
    {
        NSData* encryptData = [textString dataUsingEncoding:NSUTF8StringEncoding];
        dataInLength = [encryptData length];
        dataIn = (const void *)[encryptData bytes];
    }
    
    
    CCCryptorStatus ccStatus;
    uint8_t *dataOut = NULL; //可以理解位type/typedef 的缩写(有效的维护了代码,比如:一个人用int,一个人用long。最好用typedef来定义)
    size_t dataOutAvailable = 0; //size_t  是操作符sizeof返回的结果类型
    size_t dataOutMoved = 0;
    
    dataOutAvailable = (dataInLength + kCCBlockSizeDES) & ~(kCCBlockSizeDES - 1);
    dataOut = malloc( dataOutAvailable * sizeof(uint8_t));
    memset((void *)dataOut, 00, dataOutAvailable);//将已开辟内存空间buffer的首 1 个字节的值设为值 0
    
    //NSString *initIv = @"12345678";
    const void *vkey = key;
    const void *iv = (const void *) key; //[initIv UTF8String];
    
    //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 = [[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)dataOut length:(NSUInteger)dataOutMoved] encoding:NSUTF8StringEncoding];
    }
    else //encryptOperation==0  (加密过程中,把加好密的数据转成base64的)
    {
        //编码 base64
        NSData *data = [NSData dataWithBytes:(const void *)dataOut length:(NSUInteger)dataOutMoved];
        result = [GTMBase64 stringByEncodingData:data];
    }
    
    return [result UTF8String];
    
}

AES加密

AES加密是一种更高级的对称加密算法 . 其特点是

  • **为128位(也有192-256的变体) , 相比DES(56位)更安全.
  • 隐藏了明文模式 , 分组密码转化为流模式

先导入框架 #import <CommonCrypto/CommonCryptor.h>
代码下载地址

//加密
- (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;
}

如果感觉还不错 , 点击喜欢鼓励一下哦 ????????????????