在Objective C、.net和Android中生成相同的加密字符串AES/CBC/PKCS7Padding,可以按照以下步骤进行:
#import <CommonCrypto/CommonCryptor.h>
NSString *encryptString(NSString *plainText, NSString *key, NSString *iv) {
NSData *plainData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
NSData *ivData = [iv dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *encryptedData = [NSMutableData dataWithLength:plainData.length + kCCBlockSizeAES128];
size_t encryptedLength = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmAES,
kCCOptionPKCS7Padding,
keyData.bytes,
keyData.length,
ivData.bytes,
plainData.bytes,
plainData.length,
encryptedData.mutableBytes,
encryptedData.length,
&encryptedLength);
if (cryptStatus == kCCSuccess) {
encryptedData.length = encryptedLength;
return [encryptedData base64EncodedStringWithOptions:0];
}
return nil;
}
using System;
using System.Security.Cryptography;
using System.Text;
string EncryptString(string plainText, string key, string iv) {
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
byte[] ivBytes = Encoding.UTF8.GetBytes(iv);
using (Aes aes = Aes.Create()) {
aes.Key = keyBytes;
aes.IV = ivBytes;
aes.Padding = PaddingMode.PKCS7;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
byte[] encryptedBytes = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
return Convert.ToBase64String(encryptedBytes);
}
}
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;
String encryptString(String plainText, String key, String iv) {
try {
byte[] plainBytes = plainText.getBytes("UTF-8");
byte[] keyBytes = key.getBytes("UTF-8");
byte[] ivBytes = iv.getBytes("UTF-8");
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encryptedBytes = cipher.doFinal(plainBytes);
return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
需要注意的是,以上代码只是生成加密字符串的示例,实际应用中还需要进行错误处理、密钥管理等其他安全措施。
推荐的腾讯云相关产品:腾讯云密钥管理系统(KMS)用于管理密钥,保护数据的安全性。详情请参考:腾讯云密钥管理系统(KMS)
请注意,以上答案仅供参考,具体实现方式可能因平台版本、库的不同而有所差异。在实际应用中,建议根据具体平台和库的文档进行进一步的研究和开发。
领取专属 10元无门槛券
手把手带您无忧上云