Fork me on GitHub

C# AES加解密

/// <summary>
    /// AES加密
    /// </summary>
    /// <param name="key"></param>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string AesEncrypt(string Keystring, string str)
    {
        var EncryptedString = "";
        if (string.IsNullOrEmpty(str)) return null;
        Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);

        RijndaelManaged rm = new RijndaelManaged();
        rm.Key = Encoding.UTF8.GetBytes(Keystring);
        rm.Mode = CipherMode.ECB;                   // 运算方式
        rm.Padding = PaddingMode.PKCS7;             // 填充方式

        try
        {
            ICryptoTransform cTransform = rm.CreateEncryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            EncryptedString = Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }
        catch (Exception e)
        {
            
        }

        return EncryptedString;
    }

    /// <summary>
    /// AES解密
    /// </summary>
    /// <param name="Keystring"></param>
    /// <param name="EncryptedString"></param>
    /// <returns></returns>
    public static string AesDecrypt(string Keystring, string EncryptedString)
    {
        var DecryptedString = "";
        try
        {
            if (string.IsNullOrEmpty(EncryptedString))
            {
                return "";
            }
            Byte[] encryptData = Convert.FromBase64String(EncryptedString);
            RijndaelManaged rm = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(Keystring),
                Mode = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };

            ICryptoTransform ct = rm.CreateDecryptor();

            Byte[] decryptedData = ct.TransformFinalBlock(encryptData, 0, encryptData.Length);
            DecryptedString = Encoding.UTF8.GetString(decryptedData);
        }
        catch (Exception ex)
        {
            
        }

        return DecryptedString;
    }

 

posted @ 2022-12-16 10:46  WantRemake  阅读(289)  评论(0编辑  收藏  举报