博客> iOS 的 AES-128-CBC 数据加密解密 (nosalt)
iOS 的 AES-128-CBC 数据加密解密 (nosalt)
2018-12-11 11:20 评论:0 阅读:723 凯顺自然
ios OpenSSL AES128 CBC

场景:与路由器进行通讯,路由器、安卓端使用OpenSSL库加密 需求:实现对路由器返回数据的AES解密 AES加密方式:(终端命令)echo -n "badsvboasdf23fas" | openssl enc -aes-128-cbc -pass pass:"abc" -md md5 -e -nosalt -iv 0 -base64 -p -v 问题误区:在加密解密过程中,key是需要进行MD5加密的,而我一直是拿到MD5的字符串然后进行下一步操作,结果进了误区,转了两周才转出来,教训! 下面上代码:

import

import "CommonCrypto/CommonDigest.h"

define gIv @"0" //可以自行修改

-(NSData )AES128EncryptWithKey:(NSString )key {//加密 const char *str = key.UTF8String; unsigned char keyPtr[CC_MD5_DIGEST_LENGTH]; CC_MD5(str, (CC_LONG)strlen(str), keyPtr);

char ivPtr[kCCKeySizeAES128];
memset(ivPtr, 0, sizeof(ivPtr));
[gIv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];

NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                      kCCAlgorithmAES128,
                                      kCCOptionPKCS7Padding | kCCOptionECBMode,//PKCS7和JAVA的PKCS5是相通的,对于kCCOptionECBMode这个,现在还没搞明白,因为看API上有一句“Default is CBC” ;nopadding填写“0x0000”,需要自己进行数据填充(这个填充方式比较自由)
                                      keyPtr,
                                      kCCBlockSizeAES128,
                                      ivPtr,
                                      [self bytes],
                                      dataLength,
                                      buffer,
                                      bufferSize,
                                      &numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
    NSData *data = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    NSData *data64 = [data base64EncodedDataWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];
    return data64;
}
free(buffer);
return nil;

}

  • (NSData )AES128DecryptWithKey:(NSString )key {//解密

    const char *str = key.UTF8String; unsigned char keyPtr[CC_MD5_DIGEST_LENGTH]; CC_MD5(str, (CC_LONG)strlen(str), keyPtr);

    char ivPtr[kCCKeySizeAES128]; memset(ivPtr, 0, sizeof(ivPtr)); [gIv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];

    NSUInteger dataLength = [self length]; size_t bufferSize = dataLength + kCCBlockSizeAES128; void buffer = malloc(bufferSize); size_t numBytesDecrypted = 0; CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding | kCCOptionECBMode, keyPtr, kCCBlockSizeAES128, ivPtr, [self bytes], dataLength, buffer, bufferSize, &numBytesDecrypted); if (cryptStatus == kCCSuccess) { NSData data = [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted]; // NSData *data=[[NSData alloc]initWithBytes:buffer length:numBytesDecrypted]; return data; } free(buffer); return nil; }

收藏
0
sina weixin mail 回到顶部