[.Net] 使用 AES 演算法為字串加密解密

參考 【C#.Net】使用 AES 演算法為字串加密解密

只是將程式碼合併

private delegate ICryptoTransform CreateTransform(AesCryptoServiceProvider aes);

/// <summary>
/// 字串加密(非對稱式)
/// </summary>
/// <param name="Source">加密前字串</param>
/// <param name="CryptoKey">加密金鑰</param>
/// <returns>加密後字串</returns>
public static string Encrypt(string SourceStr, string CryptoKey)
{
    byte[] dataByteArray = Encoding.UTF8.GetBytes(SourceStr);
    return Convert.ToBase64String(Crypto(dataByteArray, CryptoKey, (aes) => aes.CreateEncryptor()));
}

/// <summary>
/// 字串解密(非對稱式)
/// </summary>
/// <param name="Source">解密前字串</param>
/// <param name="CryptoKey">解密金鑰</param>
/// <returns>解密後字串</returns>
public static string Decrypt(string SourceStr, string CryptoKey)
{
    byte[] dataByteArray = Convert.FromBase64String(SourceStr);
    return Encoding.UTF8.GetString(Crypto(dataByteArray, CryptoKey, (aes) => aes.CreateDecryptor()));
}

/// <summary>
/// 加解密
/// </summary>
/// <param name="dataByteArray">加解密前資料</param>
/// <param name="CryptoKey">加解密金鑰</param>
/// <param name="trans">產生加解密的委派</param>
/// <returns>加解密後資料</returns>
private static byte[] Crypto(byte[] dataByteArray, string CryptoKey, CreateTransform trans)
{
    try
    {
        byte[] ck = Encoding.UTF8.GetBytes(CryptoKey);
        AesCryptoServiceProvider aes = new AesCryptoServiceProvider()
        {
            Key = new SHA256CryptoServiceProvider().ComputeHash(ck),
            IV = new MD5CryptoServiceProvider().ComputeHash(ck)
        };
        using (MemoryStream ms = new MemoryStream())
        using (CryptoStream cs = new CryptoStream(ms, trans(aes), CryptoStreamMode.Write))
        {
            cs.Write(dataByteArray, 0, dataByteArray.Length);
            cs.FlushFinalBlock();
            return ms.ToArray();
        }
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message);
    }
    return null;
}

Taiwan is a country. 臺灣是我的國家