我正试图在Android上实现AES128加密。我有一个解决方案,使用Objective C工作在iPhone上,但无法将其移植到Android。我已经搜索了一个解决方案的stackoverflow,但我似乎做错了什么。我对Java相当陌生,所以我想我错过了一些与数据,字符串转换有关的事情。Android AES 128加密
这里是我的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
你的编码是明文不同。 Android使用UTF8,iPhone使用ASCII。 – vcsjones 2013-03-13 16:08:21
作为一个方面说明,我会劝阻你的密码模式使用ECB(除非你试图保持与已经使用它的系统的兼容性)。它使得识别加密数据中的模式变得相当容易。 – vcsjones 2013-03-13 16:10:49
感谢vcsjones,我已将代码更新为plainText.getBytes(“ASCII”),但结果仍然不同 – Pabs 2013-03-13 16:37:58