我是这种加密事物的新手,但我有一个 Java 应用程序和一个 iOS,我希望它们都能够将文本加密为相同的结果。我使用 AES。我找到了这些代码,当然稍作修改,但它们返回不同的结果
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
)中,我有:
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
key TheBestSecretKey
。Base64编码后的结果是:
对于 iOS:9wXUiV+ChoLHmF6KraVtDQ==
对于 Java:/s5YyKb3tDlUXt7pqA5OFA==
我现在该怎么办?