解密用Obj-C加密的java和AES文件

时间:2013-05-12 23:30:56

标签: java objective-c aes

我有一个用obj-c代码加密的文件:

NSMutableData *fileData = [NSMutableData new];
// Get file data.
[[self encrypt::fileData WithKey:@"SOME_KEY"]]

- (NSMutableData*) encrypt:(NSMutableData*)data WithKey: (NSString *) key
{
    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keyBuffer[kCCKeySizeAES128+1]; // room for terminator (unused)
    bzero( keyBuffer, sizeof(keyBuffer) ); // fill with zeroes (for padding)

    [key getCString: keyBuffer maxLength: sizeof(keyBuffer) encoding: NSUTF8StringEncoding];

    // encrypts in-place, since this is a mutable data object
    size_t numBytesEncrypted = 0;

    size_t returnLength = ([data length] + kCCKeySizeAES256) & ~(kCCKeySizeAES256 - 1);

    char* returnBuffer = malloc(returnLength * sizeof(uint8_t) );

    CCCryptorStatus result = CCCrypt(kCCEncrypt, kCCAlgorithmAES128 , kCCOptionPKCS7Padding | kCCOptionECBMode,
                                 keyBuffer, kCCKeySizeAES128, nil,
                                 [data bytes], [data length],
                                 returnBuffer, returnLength,
                                 &numBytesEncrypted);

    if(result == kCCSuccess)
        return [NSMutableData dataWithBytes:returnBuffer length:numBytesEncrypted];
    else
        return nil;
}

我想用java读取这个文件。我正在尝试

SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
// What is salt ??
KeySpec spec = new PBEKeySpec("SOME_KEY", salt, 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
String plaintext = new String(cipher.doFinal(ciphertext), "UTF-8");
System.out.println(plaintext);

我对obj-c一无所知。你觉得我能做到吗?谢谢。

1 个答案:

答案 0 :(得分:0)

使用Cipher.getInstance("AES/ECB/PKCS5Padding");,因为Objective-C代码使用的是ECB而不是CBC(您应该使用CBC或CTR代替ECB,但在这种情况下,它看起来不像您有选择)

此外,使用SecretKey secret = new SecretKeySpec("SOME_KEY".getBytes("UTF-8"), "AES");,因为Objective-C代码只是使用密码中的原始字节来生成密钥(而不是像您一样使用加密密钥生成器)。 “SOME_KEY”需要与Objective-C代码使用的密码相同。此外,“SOME_KEY”.getBytes(“UTF-8”)需要正好是16个字节,因此如果需要,您需要将其截断为16个字节,或者将其填充为0到16个字节。