加密: AES(C#)

Aes: 唯一密钥进行加密解密

using System.Security.Cryptography;
public static string AesEncrypt(string str, string key) 
{
    string result;
    try
    {
        if (string.IsNullOrEmpty(str))
        {
            result = null;
        }
        else
        {
            byte[] bytes = Encoding.UTF8.GetBytes(str);
            RijndaelManaged rijndaelManaged = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };
            ICryptoTransform cryptoTransform = rijndaelManaged.CreateEncryptor();
            byte[] array = cryptoTransform.TransformFinalBlock(bytes, 0, bytes.Length);
            result = Convert.ToBase64String(array, 0, array.Length);

            return result;
        }
    }
    catch (Exception ex)
    {
        result = null;
        System.Console.WriteLine(ex);
    }
    return result;
}

结果保存为String 类型,ToBase64String仅是一种表示方法,对应解密时就用使用 FromBase64String

public static string AesDecrypt(string str, string key)
{
    if (string.IsNullOrEmpty(str))
    {
        return null;
    }
    string result;
    try
    {
        byte[] array = Convert.FromBase64String(str);

        RijndaelManaged rijndaelManaged = new RijndaelManaged
        {
            Key = Encoding.UTF8.GetBytes(key),
            Mode = CipherMode.ECB,
            Padding = PaddingMode.PKCS7
        };
        ICryptoTransform cryptoTransform = rijndaelManaged.CreateDecryptor();
        byte[] bytes = cryptoTransform.TransformFinalBlock(array, 0, array.Length);

        result = Encoding.UTF8.GetString (bytes);
    }
    catch (Exception ex)
    {
        result = null;
        System.Console.WriteLine(ex);
    }
    return result;
}

补充生成密钥的方法

public static string AesGenKey()
{
    RijndaelManaged rijndaelManaged = new RijndaelManaged
    {
        KeySize = 128,
        Mode = CipherMode.ECB,
        Padding = PaddingMode.PKCS7
    };

    rijndaelManaged.GenerateKey();

    return Encoding.UTF8.GetString (rijndaelManaged.Key);
}

获得Key经常不是常见的字符,则可以使用ToBase64String

public static string AesGenKey()
{
    RijndaelManaged rijndaelManaged = new RijndaelManaged
    {
        KeySize = 128,
        Mode = CipherMode.ECB,
        Padding = PaddingMode.PKCS7
    };

    rijndaelManaged.GenerateKey();

    return Convert.ToBase64String(rijndaelManaged.Key);
}

这样,加密解密的地方就需要修改

RijndaelManaged rijndaelManaged = new RijndaelManaged
{
    Key = Convert.FromBase64String(key),
    Mode = CipherMode.ECB,
    Padding = PaddingMode.PKCS7
};

 

你可能感兴趣的:(算法)