C# AES加密算法转Python3

C# AES encryption algorithm to Python3

你好,我需要将 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

您正在为您的 C# 代码使用 Encoding.Unicode.GetBytes(clearText) which returns UTF-16LE while Python (more sensibly) defaults to UTF-8 for raw.encode(). I'd use Encoding.UTF8

评论里已经提到了,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# 代码生成的密文未受完整性保护或验证。此外,如果接收方存在填充预言机攻击,它很容易受到攻击。填充 oracle 攻击非常有效,如果它们适用,您将失去消息的完全机密性。

此外,如果盐是非随机的,那么密钥和 IV 也是非随机的。这反过来意味着密文与明文一样随机。换句话说,如果遇到相同的明文块,它就会泄漏数据。所以我希望非随机盐只是为了测试目的。

最后,按预期进行加密 运行 并不意味着您的解决方案是安全的。