Pab*_*abs 6 iphone encryption android aes
我正在尝试在Android上实施AES128加密.我有一个使用Objective C在iPhone上工作的解决方案,但无法将其移植到Android.我搜索了stackoverflow的解决方案,但我似乎做错了什么.我对Java很新,所以我觉得我错过了与数据,字符串转换有关的事情.
这是我的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];
Run Code Online (Sandbox Code Playgroud)
这是我的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"));
Run Code Online (Sandbox Code Playgroud)
在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"));
Run Code Online (Sandbox Code Playgroud)
但我在Android和iPhone之间的结果仍然不一样
除了明文编码困难(正如 vcsjones 在评论中指出的那样)之外,还要确保密钥字符串的编码相同(请注意,使用原始字符串(如密码)直接作为加密密钥是个坏消息熊,在密码上使用像 PBKDF2 这样的密钥派生函数来派生密钥)。
另外,Java 的 ASCII 编码字符串是US-ASCII,而不仅仅是ASCII,因此请确保在调用中使用它getBytes。
编辑:发现你的问题:iOS 字符串在末尾使用额外的空字符(0x00)进行加密,而 java 则没有。因此,在 java 中加密“hello world\0”将得到与 iOS 中“hello world”相同的输出
| 归档时间: |
|
| 查看次数: |
1840 次 |
| 最近记录: |