0

我有一个用 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一无所知。你认为我能完成这件事吗?谢谢你。

4

1 回答 1

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 个字节。

于 2013-05-13T13:45:19.087 回答