寻找 windows phone c# 代码用于 python AES MODE_CBC 加密

Looking for equivalent windows phone c# code for python AES MODE_CBC encryption

我在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.

中可用

谢谢!

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;
        }
    }
}

请注意,这里有一个小问题:我使用 UTF8passwordstrPlainText 进行编码,但 python 使用 bytestring 用于所有内容,并且 bytestring 与编码无关(参见 What is a Python bytestring?)。

使用示例:

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

方法returns与您的示例相同的加密结果。

这段代码的一个小问题是IV(初始化向量)是用一个空缓冲区初始化的(new byte[16]和Python中的16 * '\x00')。这是一个"bad habit"。即使使用 CBC 密码模式也被认为是 "bad".