AES在iOS(Obj-C)和Android(Java)中获得不同的结果 [英] AES gets different results in iOS (Obj-C) and Android (Java)
问题描述
我是这种加密的完全新手,但我有一个Java应用程序和一个iOS,我希望他们都能够将文本转换成相同的结果。我用AES。
我发现这些代码,当然稍作修改,但它们会返回不同的结果
I'm a complete newbie to this kind of encryption things but I have a Java app and an iOS, and I want them to both be able to ecrypt a text to a same result. I use AES. I found these codes, with a little modification of course, but they return different result
iOS代码:
- (NSData *)AESEncryptionWithKey:(NSString *)key {
unsigned char keyPtr[kCCKeySizeAES128] = { 'T', 'h', 'e', 'B', 'e', 's', 't', 'S', 'e', 'c', 'r','e', 't', 'K', 'e', 'y' };
size_t bufferSize = 16;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
const char iv2[16] = { 65, 1, 2, 23, 4, 5, 6, 7, 32, 21, 10, 11, 12, 13, 84, 45 };
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionECBMode | kCCOptionPKCS7Padding,,
keyPtr,
kCCKeySizeAES128,
iv2,
@"kayvan",
6,
dataInLength,
buffer,
bufferSize,
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer);
return nil;
}
,Java代码是:
public static void main(String[] args) throws Exception {
String password = "kayvan";
String key = "TheBestSecretKey";
String newPasswordEnc = AESencrp.newEncrypt(password, key);
System.out.println("Encrypted Text : " + newPasswordEnc);
}
和另一个java类( AESencrp.class
)我有:
and in another java class (AESencrp.class
) I have:
public static final byte[] IV = { 65, 1, 2, 23, 4, 5, 6, 7, 32, 21, 10, 11, 12, 13, 84, 45 };
public static String newEncrypt(String text, String key) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] keyBytes= new byte[16];
byte[] b= key.getBytes("UTF-8");
int len = 16;
System.arraycopy(b, 0, keyBytes, 0, len);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(IV);
System.out.println(ivSpec);
cipher.init(Cipher.ENCRYPT_MODE,keySpec,ivSpec);
byte[] results = cipher.doFinal(text.getBytes("UTF-8"));
String result = DatatypeConverter.printBase64Binary(results);
return result;
}
我想要加密的字符串是 kayvan
,密钥为 TheBestSecretKey
。 Base64编码后的结果为:
The string I wanted to encrypt is kayvan
with the key TheBestSecretKey
. and the results after Base64 encoding are:
for iOS: 9wXUiV + ChoLHmF6KraVtDQ ==
for Java: / s5YyKb3tDlUXt7pqA5OFA ==
for Java: /s5YyKb3tDlUXt7pqA5OFA==
我现在该怎么办?
推荐答案
我用iOS / Android / Node.js AES256相同的结果编码, https://gist.github.com/m1entus/f70d4d1465b90d9ee024
I made a gist with iOS/Android/Node.js AES256 same result encoding, https://gist.github.com/m1entus/f70d4d1465b90d9ee024
这篇关于AES在iOS(Obj-C)和Android(Java)中获得不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!