我将尝试在Android上实现AES128加密。我已经使用Objective C在iPhone上找到了解决方案,但是在移植到Android上时出现了问题。我在stackoverflow上搜索了解决方案,但貌似我做错了什么。考虑到数据和字符串转换,我的Java水平相对较弱,因此可能会遗漏一些重要内容。
这是我的iPhone加密代码:
这是我的iPhone加密代码:
char keyPtr[kCCKeySizeAES128+1];
[keyString getCString:keyPtr
maxLength:sizeof(keyPtr)
encoding:NSASCIIStringEncoding];
// CString for the plain text
char plainBytes[[plainString length]+1];
[plainString getCString:plainBytes
maxLength:sizeof(plainBytes)
encoding:NSASCIIStringEncoding];
size_t bytesEncrypted = 0;
// Allocate the space for encrypted data
NSUInteger dataLength = [plainString length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void* buffer = malloc(bufferSize);
// Encrypt
CCCryptorStatus ret = CCCrypt(kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding | kCCOptionECBMode,
keyPtr,
kCCKeySizeAES128,
NULL,
plainBytes, sizeof(plainBytes),
buffer, bufferSize,
&bytesEncrypted);
if (ret != kCCSuccess) {
free(buffer);
}
encryptedData = [NSData dataWithBytes:buffer length:bytesEncrypted];
这是我的Java代码:
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(plainText.getBytes("UTF-8"));
在iPhone和Java中使用相同的密钥和明文会得到不同的结果。我的iPhone结果符合我的需求,所以我正在尝试让Java给我iPhone的结果。我确定在Java中缺少某些东西,只是不确定是什么。
编辑
根据下面的建议,我修改了我的Java代码如下:
byte[] keyBytes = plainTextKey.getBytes("US-ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(plainText.getBytes("US-ASCII"));
但我仍然在Android和iPhone之间获取不同的结果。