【问题标题】:Looking for equivalent windows phone c# code for python AES MODE_CBC encryption [closed]寻找python AES MODE_CBC加密的等效windows phone c#代码[关闭]
【发布时间】:2016-03-15 15:28:35
【问题描述】:

我在python中有加密/解密方法写成

import base64
from Crypto.Cipher import AES


def get_encrypted_message(message):
    """Return encrypted message."""
    length = 16 - (len(message) % 16)
    message += chr(length) * length
    cipher = AES.new('abcdefghijklmnopqrstuvwxyz123456',
                     AES.MODE_CBC, 16 * '\x00')
    message = cipher.encrypt(message)
    return base64.b64encode(message)


def get_decrypted_message(message):
    """Return decrypted message."""
    if not message:
        return
    message = base64.b64decode(message)
    cipher = AES.new(
        'abcdefghijklmnopqrstuvwxyz123456', AES.MODE_CBC, 16 * '\x00')
    msg = cipher.decrypt(message)
    return msg.strip()


ENCRYPTED_MSG = get_encrypted_message('123')
print ENCRYPTED_MSG         # 5pRIk9MDE3z9caf/ayilIA==
print get_decrypted_message(ENCRYPTED_MSG)  # 123

我现在正在寻找等效的 Windows phone 8.1 C# AES 算法加密方法。我是 windows phone 开发的新手,在我的应用程序中我必须通过传递加密数据来查询数据。

请指导或帮助编写这个简单的代码。由于我发现很难获得 winphone 8.1 c# 算法,因此我看不到任何 AES 算法可用或不可用,因为它在 8 中可用。

谢谢!

【问题讨论】:

    标签: c# python encryption windows-phone-8 aes


    【解决方案1】:

    WP 8.1 和 WinRT

    public static string Encrypt2(string password, string plainText)
    {
        IBuffer passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
        IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf8);
        IBuffer iv = WindowsRuntimeBuffer.Create(16);
    
        SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
        // create symmetric key from derived password key
        CryptographicKey symmKey = symProvider.CreateSymmetricKey(passwordBuffer);
    
        // encrypt data buffer using symmetric key and derived salt material
        IBuffer encryptedBuffer = CryptographicEngine.Encrypt(symmKey, plainBuffer, iv);
        string encryptedText = CryptographicBuffer.EncodeToBase64String(encryptedBuffer);
        return encryptedText;
    }
    
    public static string Decrypt2(string password, string encryptedText)
    {
        IBuffer passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
        IBuffer encryptedBuffer = CryptographicBuffer.DecodeFromBase64String(encryptedText);
        IBuffer iv = WindowsRuntimeBuffer.Create(16);
    
        SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
        // create symmetric key from derived password material
        CryptographicKey symmKey = symProvider.CreateSymmetricKey(passwordBuffer);
    
        // encrypt data buffer using symmetric key and derived salt material
        IBuffer plainBuffer = CryptographicEngine.Decrypt(symmKey, encryptedBuffer, iv);
        string plainText = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, plainBuffer);
        return plainText;
    }
    

    其他一切

    public static string Encrypt(string password, string plainText)
    {
        using (var aes = new AesManaged())
        {
            aes.Key = Encoding.UTF8.GetBytes(password);
            aes.IV = new byte[16];
            aes.Padding = PaddingMode.PKCS7;
            aes.Mode = CipherMode.CBC;
    
            byte[] plainBuffer = Encoding.UTF8.GetBytes(plainText);
    
            using (MemoryStream input = new MemoryStream(plainBuffer))
            using (MemoryStream output = new MemoryStream())
            using (ICryptoTransform encryptor = aes.CreateEncryptor())
            using (CryptoStream cs = new CryptoStream(output, encryptor, CryptoStreamMode.Write))
            {
                input.CopyTo(cs);
                cs.FlushFinalBlock();
                string encryptedText = Convert.ToBase64String(output.GetBuffer(), 0, (int)output.Length);
                return encryptedText;
            }
        }
    }
    
    public static string Decrypt(string password, string encryptedText)
    {
        using (var aes = new AesManaged())
        {
            aes.Key = Encoding.UTF8.GetBytes(password);
            aes.IV = new byte[16];
            aes.Padding = PaddingMode.PKCS7;
            aes.Mode = CipherMode.CBC;
    
            byte[] encryptedBuffer = Convert.FromBase64String(encryptedText);
    
            using (MemoryStream input = new MemoryStream(encryptedBuffer))
            using (MemoryStream output = new MemoryStream())
            using (ICryptoTransform decryptor = aes.CreateDecryptor())
            using (CryptoStream cs = new CryptoStream(input, decryptor, CryptoStreamMode.Read))
            {
                cs.CopyTo(output);
                string plainText = Encoding.UTF8.GetString(output.GetBuffer(), 0, (int)output.Length);
                return plainText;
            }
        }
    }
    

    请注意这里有一个小问题:我使用UTF8 来编码passwordstrPlainText,但是python 使用bytestring 来编码所有内容,而bytestring 编码不可知(见What is a Python bytestring?)。

    使用示例:

    string result = Encrypt("abcdefghijklmnopqrstuvwxyz123456", "123"); // 5pRIk9MDE3z9caf/ayilIA==
    string decrypted = Decrypt("abcdefghijklmnopqrstuvwxyz123456", result); // 123
    

    该方法返回与您的示例相同的加密结果。

    这段代码的一个小问题是IV(初始化向量)是用一个空的biffer(Python中的new byte[16]16 * '\x00')初始化的。这是一个“坏习惯”。即使使用 CBC 密码模式也被认为是“不好的”。

    【讨论】:

    • 密码是 SALT 对吗?
    • @LoveSharma 密码是abcdefghijklmnopqrstuvwxyz123456,就像你的例子一样。
    • 我正在尝试在通用 Windows Phone 应用程序 8.1 中使用 AesManaged - 我没有看到可用的软件包。如何安装 aesmanaged 包?
    • 感谢xanatos,但是这篇文章是针对windows 8的(这篇文章是为Windows Phone 8开发者准备的。)——看来,AesManaged在windows8.1+中是不存在的
    猜你喜欢
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多