我想在iOS中生成相同的加密字符串,在.net中生成android。我可以在 android 和 .net 中生成相同的字符串,但对于 Objective C 则不同。
安卓代码:
public static String encrypt(String key, String value) {
try {
SecretKey secretKey = new SecretKeySpec(key.getBytes(), "AES");
AlgorithmParameterSpec iv = new IvParameterSpec(key.getBytes());
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
return new String(Base64.encode(cipher.doFinal(value.getBytes("UTF-8")), Base64.NO_WRAP));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
后端代码
public Encryption(input: string): any {
return CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(input), this.Cryptokey,
{
keySize: 128 / 8,
iv: this.iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
}
在 Objective C 代码中
- (NSData *)AES256EncryptWithKey:(NSString *)key
{
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer); //free the buffer;
return nil;
}
我关注了这些网址加密 AES/CBC/PKCS7Padding https://stackoverflow.com/questions/39404038/encrypt-aes-cbc-pkcs7padding
如何在 Objective C 中使用 AES 256 CBC 加密 https://stackoverflow.com/questions/45832991/how-to-encrypt-with-aes-256-cbc-in-objective-c
使用 PKCS7Padding 的 AES CBC 加密在 Java 和 Objective-C 中具有不同的结果 https://stackoverflow.com/questions/37477635/aes-cbc-encryption-with-pkcs7padding-has-different-results-in-java-and-objective
根据我对 Objective C 的理解,我首先需要转换 NSData 中的密码,然后将其传递给 AES 加密方法。
此方法将返回给我加密的数据,现在我需要将其转换为 Base 64 字符串编码。
谁能告诉我应该怎么做才能为 iOS、Android 和 .net 生成相同的结果?
例如
如果我想在所有 3 个平台中加密字符串“xceedancce”并且我的密钥是
7061737323313233
那么在 Android 和 .net 中,结果是“uXDlYA4e8Z8HWd9rvNdXaw==”,但在 iOS 中结果相同
它是“l4zDDnwOVJ0dz2fl7HdKIA==”
谁能建议我应该在 Objective C 中做什么?
谢谢。