你好,我需要将 C# 加密算法传递给 python,但我无法在最终哈希中得到相同的结果,有人知道我做错了什么吗?
这是 C# AES 密码:
using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;
public class Program
{
public static void Main()
{
string data = "leandro";
string encrypt = Encrypt(data);
Console.WriteLine(encrypt);
}
static readonly char[] padding = { '=' };
private const string EncryptionKey = "teste123";
public static string Encrypt(string clearText)
{
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
Console.WriteLine(clearBytes);
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()).TrimEnd(padding).Replace('+', '-').Replace('/', '_');
}
}
return clearText;
}
}
输出:DTyK3ABF4337NRNHPoTliQ
这是我的 python 版本:
import base64
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
class AESCipher(object):
def __init__(self, key, interactions=1000):
self.bs = AES.block_size
self.key = key
self.interactions = interactions
def encrypt(self, raw):
raw = self._pad(raw)
nbytes = [0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76,
0x65, 0x64, 0x65, 0x76]
salt = bytes(nbytes)
keyiv = PBKDF2(self.key, salt, 48, self.interactions)
key = keyiv[:32]
iv = keyiv[32:48]
cipher = AES.new(key, AES.MODE_CBC, iv)
enc = base64.b64encode(iv + cipher.encrypt(raw.encode('utf-16le')))
return self._base64_url_safe(str(enc, "utf-8"))
def _pad(self, s):
return s + (self.bs - len(s) % self.bs) * \
chr(self.bs - len(s) % self.bs)
def _base64_url_safe(self, s):
return s.replace('+', '-').replace('/', '_').replace('=', '')
@staticmethod
def _unpad(s):
return s[:-ord(s[len(s) - 1:])]
enc = AESCipher("teste123")
dec = enc.encrypt("leandro")
print(dec)
输出: LJTFEn0vmz8IvqFZJ87k8lI8DPh8-oIOSIxmS5NE4D0
最佳答案
您正在使用Encoding.Unicode.GetBytes(clearText)
which returns UTF-16LE而Python(更明智)defaults to UTF-8对于raw.encode()
。我会使用Encoding.UTF8
用于您的 C# 代码。
正如评论中已经提到的,Python 还会在密文前面添加 IV,而 C# 代码只是执行加密并在解密时计算 IV(因此不需要存储)。
这是一个执行相同操作的 Python 程序:
import base64
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
from Crypto.Util.Padding import pad
class AESCipher(object):
def __init__(self, key, interactions=1000):
self.bs = AES.block_size
self.key = key
self.interactions = interactions
def encrypt(self, raw):
nbytes = [0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76,
0x65, 0x64, 0x65, 0x76]
salt = bytes(nbytes)
keyiv = PBKDF2(self.key, salt, 48, self.interactions)
key = keyiv[:32]
iv = keyiv[32:48]
cipher = AES.new(key, AES.MODE_CBC, iv)
encoded = raw.encode('utf-16le')
encodedpad = pad(encoded, self.bs)
ct = cipher.encrypt(encodedpad)
cip = base64.b64encode(ct)
return self._base64_url_safe(str(cip, "utf-8"))
def _base64_url_safe(self, s):
return s.replace('+', '-').replace('/', '_').replace('=', '')
enc = AESCipher("teste123")
dec = enc.encrypt("leandro")
print(dec)
<小时/>
在您大喊 Eureka 之前,请务必了解 C# 代码生成的密文不受完整性保护,也没有经过身份验证。此外,如果接收方存在填充预言机攻击,则它很容易受到填充预言机攻击。填充预言机攻击非常有效,如果应用它们,您将失去消息的完全 secret 性。
此外,如果盐是非随机的,那么 key 和 IV 也是非随机的。这反过来意味着密文与明文一样随机。换句话说,如果遇到相同的明文 block ,它就会泄漏数据。所以我希望非随机盐只是用于测试目的。
最后,按预期运行加密并不意味着您的解决方案是安全的。
关于C# AES 加密算法转Python3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59722526/