最近在弄AES解密,解密方法是 iv取加密文件內(nèi)容的前16位,然后解密之后把內(nèi)容里面的填充字符b"\0"去掉
1.首先是把data轉(zhuǎn)成Byte數(shù)組 然后取前16位
Byte *testByte = (Byte *)[data bytes];
Byte *bytes =malloc(sizeof(*bytes)*data.length);
for(int i=0;i<16;i++){
bytes[i] = testByte[i];
}
2.跟后端同步好補(bǔ)位方法 我這里是不補(bǔ)位填0 其他補(bǔ)位方法自行查找
3.去掉數(shù)據(jù)里面補(bǔ)位的0,我這里是把data轉(zhuǎn)換成字符串 ,我這邊是不足16位,會(huì)補(bǔ)夠0到16位
+(NSString *)AES128Decrypt:(NSData *)data key:(NSString *)key{
char keyPtr[kCCKeySizeAES128 + 1];
memset(keyPtr, 0, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [data length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
//16字節(jié)的偏移量
Byte *testByte = (Byte *)[data bytes];
Byte *bytes =malloc(sizeof(*bytes)*data.length);
for(int i=0;i<16;i++){
bytes[i] = testByte[i];
}
size_t numBytesCrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
kCCAlgorithmAES128,
0,//不補(bǔ)位
keyPtr,
kCCBlockSizeAES128,
bytes,
[data bytes],
dataLength,
buffer,
bufferSize, &numBytesCrypted);
if (cryptStatus == kCCSuccess) {
//原始數(shù)據(jù)
NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
//原始數(shù)據(jù)去掉前面16位的偏移量
NSData *subData = [resultData subdataWithRange:NSMakeRange(16, resultData.length-16)];
//方法:http://www.reibang.com/p/fb9d3a69d3d3
NSString *plaintext = @"";
char termChar[1] = {'\0'};
NSMutableData *data = [NSMutableData dataWithBytes:subData.bytes length:subData.length];
[data appendBytes:termChar length:1];
plaintext = [[NSString alloc] initWithCString:data.bytes encoding:NSUTF8StringEncoding];
return plaintext;
}
free(buffer);
return nil;
}
AES解密使用方法
NSData *testData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"1.txt" ofType:@""]];
NSString *laststr = [QLAESDecrypt AES128Decrypt:testData key:@"keykeykey"];
NSLog(@"laststr::%@",laststr);
下面是Des解密 單純MARK下
//Des解密
+(NSData *)decryptUseDES:(NSString *)plainText key:(NSString *)key{
NSData *plaindata = nil;
NSData *cipherdata = [[NSData alloc] initWithBase64EncodedString:plainText options:NSDataBase64DecodingIgnoreUnknownCharacters];
size_t bufferSize = cipherdata.length;
void * buffer = malloc(bufferSize);
NSData * date = [key dataUsingEncoding:NSUTF8StringEncoding];
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
kCCAlgorithmDES,/* 算法 */
kCCOptionPKCS7Padding,
[key UTF8String],
kCCKeySizeDES,
[date bytes],
[cipherdata bytes],
[cipherdata length],
buffer,
bufferSize,
&numBytesDecrypted);
if(cryptStatus == kCCSuccess)
{
plaindata = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesDecrypted];
return plaindata;
}
return plaindata;
}