我尝试使用objective-c运行AES128加密。但是,我没有得到正确的输出。 这也可能是一个愚蠢的目标-c错误,因为我只是从这种语言开始; - )
我的测试用例如下:
CryptoUtils* crypt = [[CryptoUtils alloc] init];
NSData* plaintext = [@"6bc1bee22e409f96e93d7e117393172a" dataUsingEncoding:NSUTF8StringEncoding];
NSData* key = [@"2b7e151628aed2a6abf7158809cf4f3c" dataUsingEncoding:NSUTF8StringEncoding];
NSData* iv = [@"000102030405060708090A0B0C0D0E0F" dataUsingEncoding:NSUTF8StringEncoding];
NSString* encrypted = [crypt encryptData:plaintext withKey:key andIV:iv];
XCTAssertEqualObjects(@"7649abac8119b246cee98e9b12e9197d", encrypted , @"AES testcase1 not equal");
encryptData方法如下所示:
(NSString *)encryptData:(NSData*)clearText withKey:(NSData*) currentKey andIV:(NSData*) currentIV{
// Buffer for Ciphertext
NSMutableData *cipherData = [NSMutableData dataWithLength:clearText.length + kCCBlockSizeAES128];
size_t cipherLength;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
currentKey.bytes,
currentKey.length,
currentIV.bytes,
clearText.bytes,
clearText.length,
cipherData.mutableBytes,
cipherData.length,
&cipherLength);
if(cryptStatus){
NSLog(@"Something terrible during encryption happened!");
} else {
NSLog(@"Ciphertext length: %i", [cipherData length]);
NSString *output=[cipherData description];
output = [output stringByReplacingOccurrencesOfString:@" " withString:@""];
output = [output stringByReplacingOccurrencesOfString:@"<" withString:@""];
output = [output stringByReplacingOccurrencesOfString:@">" withString:@""];
return output;
}
return nil;
}
现在,我回到了一个错误的'加密'字符串。特别是,它很长很长,我怀疑问题是我传递给方法的NSData。有没有人知道我在这里做错了什么?
谢谢
答案 0 :(得分:3)
你的意思是AES128在你的标题中,但在你的第一段中提到AES256。
您还可以使用不想使用的输入数据,键值和IV值。
现在,您想要做的事情可能是:
char bytes[] = {0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a};
NSData *clearText = [NSData dataWithBytes:&bytes length:16];
char keyBytes[] = {0x2b,0x7e,0x15,0x16,0x28,0xae,0xd2,0xa6,0xab,0xf7,0x15,0x88,0x09,0xcf,0x4f,0x3c};
NSData* currentKey = [NSData dataWithBytes:&keyBytes length:16];
char ivBytes[16] = char ivBytes[16] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F};
NSData* currentIV = [NSData dataWithBytes:&ivBytes length:16];
这些更改将为您提供128位长度的输入,键和IV值。
进行这些更改后,输出将为:
7649abac8119b246cee98e9b12e9197d8964e0b149c10b7b682e6e39aaeb731c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
前32个字符与您提供的字符相匹配。这表明您的参考值不完整,代码按预期工作。