我正在做一个项目,我必须与.net团队协调。我需要目标 -C 中下面提到的 AES 加密算法(用 C# 编写)的等效代码。我试过使用AESCrypt和CommonCrypt,但它并没有很好地醒来。在两种语言中获取不同的加密值。
private string Encrypt(string clearText)
{
string EncryptionKey = "MAKV2SPBNI99212";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
请帮忙..感谢在爱德瓦斯
在回答使用 CCKeyDerivationPBKDF 代替 Rfc2898DeriveBytes 时:
使用Common Crypto的PBKDF2的简单C示例。
将C++字符串转换为字节数组时应小心,通常在转换中使用 UTF-8。
const char passwordData[] = "password";
size_t passwordLength = strlen(passwordData);
uint8_t salt[] = {0x01, 0x02, 0x03, 0x04};
size_t saltLength = sizeof(salt);
uint rounds = 1000;
const int derivedKeySize = 16;
uint8_t derivedKey[derivedKeySize];
CCKeyDerivationPBKDF(kCCPBKDF2,
passwordData, passwordLength,
salt, saltLength,
kCCPRFHmacAlgSHA1,
rounds,
derivedKey, derivedKeySize);
for (int i=0; i<derivedKeySize; i++) {
printf("%2x ", derivedKey[i]);
}
printf("%s", "n");
输出
31 96 42 56 3F 7F B3 91 3E 85 FA 43 39 5E 69 93