Objective-c AES加密看起来不像java AES加密

Jon*_*LOo 3 java iphone encryption aes objective-c

我试图用这种方法加密目标c中扩展NSData的字符串:


 @implementation NSData (AES128)

  • (NSData *)AES128Encrypt { char keyPtr[kCCKeySizeAES128] = {'\xe1','\xaa','\x9c','\x61','\x46','\x74','\x44','\x56','\xf0','\xe5','\x47','\x46','\x86','\xdc','\x95','\x77'};

    NSUInteger dataLength = [self length];

    size_t bufferSize = dataLength + kCCBlockSizeAES128; void *buffer = malloc(bufferSize);

    size_t numBytesEncrypted = 0; CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,kCCAlgorithmAES128,kCCOptionPKCS7Padding,keyPtr,kCCKeySizeAES128,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 *)AES128Decrypt { char keyPtr[kCCKeySizeAES128] = {'\xe1','\xaa','\x9c','\x61','\x46','\x74','\x44','\x56','\xf0','\xe5','\x47','\x46','\x86','\xdc','\x95','\x77'};

    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, kCCKeySizeAES128,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; }

@end

然后我在这里称呼它:


NSString *strData = @"My string";

NSData *objNSData = [NSData dataWithData:[strData dataUsingEncoding: NSUTF8StringEncoding]];

NSLog(@"encrypted: %@",[objNSData description]);

如果我只是在目标c中使用它,它工作正常.但是当我尝试将它发送到java服务器时,它不起作用.

我的密码数据看起来像这样:

86fcf0fa9e3dff93dc8918ffd02ee203 12de0bf8c8ba300456293c4240296c0d

如果我尝试使用相同的密钥使用AES密码在java中,我得到这个:

86fcf0fa9e3dff93dc8918ffd02ee203 8388f173da143c6aeeb90e554259c83c

它很奇怪,因为它的上半部分是一样的.

有人知道为什么会这样吗?谢谢.

Jef*_*ser 9

我从来没有做过任何Objective-C编程,但我几乎肯定你在代码中使用不同模式的 AES .您需要确保这些是一致的.默认值可能是密码块链接(CBC)模式.确保在Java代码中设置此选项.

顺便说一句,CBC模式应该有一个随机的初始化向量(IV)而不是NULL(我假设使用全零).这也需要在两者之间保持一致.

我不得不给出加密的标准免责声明,使用更高级别的协议来处理这些东西通常会更安全,例如传输中的数据的SSL/TLS以及类似于Keyczar的数据.使密码正确是非常困难的,一个小错误(如选择一个错误的模式)可以完全破坏系统的安全性.

  • 男人我爱你:)实际问题是我只是将kCCOptionPKCS7Padding选项传递给CCCrypt函数,我必须通过kCCOptionPKCS7Padding | 无论如何kCCOptionECBMode选项谢谢,你的答案保存了我的一天:) (2认同)