AES获取iOS和Java的不同结果 [英] AES gets different results in iOS and Java
问题描述
我是一个完整的新手对这种加密的东西,但我有一个Java应用程序,并在iOS,我希望他们俩能ECRYPT一个文本到相同的结果。我使用AES。 我发现C $ CS这些$,当然是有一点点修改,但他们返回不同的结果。
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 code:
- (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 code是:
and the Java code is:
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
)我有:
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;
}
我想加密的字符串凯万
与键 TheBestSecretKey
。和Base64编码后的结果是:
The string I wanted to encrypt is kayvan
with the key TheBestSecretKey
. and the results after Base64 encoding are:
针对iOS: 9wXUiV + ChoLHmF6KraVtDQ ==
有关Java的: / s5YyKb3tDlUXt7pqA5OFA ==
我应该怎么做呢?
推荐答案
我做了一个要点与iOS /安卓/ Node.js的AES256相同的结果编码,<一个href="https://gist.github.com/m1entus/f70d4d1465b90d9ee024">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和Java的不同结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!