C# AES 加密算法转Python3

标签 c# python-3.x python-2.7 encryption aes

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

相关文章:

c# - 已删除 用户在其他浏览器上删除后仍登录

使用 COM 端口/使用 USB 串行 COM 端口与 xbee 模块通信的 C# 程序

c# - C#中通过反射创建匿名对象

python - 如何将一个列表中的单词与列表中的另一个单词进行比较

python-2.7 - 在 python3 中使用 h5py 发现 key

c# - 返回错误并抛出异常

python - 在Python中检查一系列抛硬币的序列是否为3

python - 获取 map 返回所有 T/F 值以进行列表匹配

python : Remove duplicate elements in lists and sublists; and remove full sublist if duplicate

python - 查找 python 中 t 测试用例的除数总数