寻找等效的windows phone c#代码进行python AES MODE_CBC加密

时间:2016-03-15 15:28:36

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

我在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手机开发的新手,在我的应用程序中,我必须通过传递加密数据来查询数据。

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

谢谢!

1 个答案:

答案 0 :(得分: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;
        }
    }
}

请注意,此处存在一个小问题:我使用UTF8passwordstrPlainText进行编码,但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密码模式也被视为“坏”"。