• C# AES加密解密


    using System;
    using System.Security.Cryptography;
    using System.Text;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    
    namespace UnitTest.OtherTest
    {
        [TestClass]
       public class AesClass
        {
            [TestMethod]
            public void TestAES()
            {
                string str = "嘿,你好漂亮";
                string result = AesEncrypt(str, "12345678876543211234567887654abc");
                Console.WriteLine(result);
                Console.WriteLine(AesDecrypt(result, "12345678876543211234567887654abc"));
            }
    
          /// <summary>
            ///  AES 加密
            /// </summary>
            /// <param name="str">明文(待加密)</param>
            /// <param name="key">密文</param>
            /// <returns></returns>
            public static string AesEncrypt(string str, string key)
            {
                if (string.IsNullOrEmpty(str)) return null;
                Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
    
                RijndaelManaged rm = new RijndaelManaged
                {
                    Key = Encoding.UTF8.GetBytes(key),
                    Mode = CipherMode.ECB,
                    Padding = PaddingMode.PKCS7
                };
    
                ICryptoTransform cTransform = rm.CreateEncryptor();
                Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
    
                return Convert.ToBase64String(resultArray, 0, resultArray.Length);
            }
            /// <summary>
            ///  AES 解密
            /// </summary>
            /// <param name="str">明文(待解密)</param>
            /// <param name="key">密文</param>
            /// <returns></returns>
            public static string AesDecrypt(string str, string key)
            {
                if (string.IsNullOrEmpty(str)) return null;
                Byte[] toEncryptArray = Convert.FromBase64String(str);
    
                RijndaelManaged rm = new RijndaelManaged
                {
                    Key = Encoding.UTF8.GetBytes(key),
                    Mode = CipherMode.ECB,
                    Padding = PaddingMode.PKCS7
                };
    
                ICryptoTransform cTransform = rm.CreateDecryptor();
                Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
    
                return Encoding.UTF8.GetString(resultArray);
            }
        }
       
    }
  • 相关阅读:
    高等代数中的名词解析No1
    概率论中的名词解释(个人理解,非官方) No1
    概率论中的公式解释(个人理解,非官方) No1
    CentOS7 网络设置
    神经网络与人工智能No0导言(笔记版)
    centos7 防火墙设置
    神经网络与人工智能No1Rosenblatt感知器(笔记版)
    输入法打不出来的数学符号大全
    php对xml文件的解析
    PHPExcel生成Excel模版
  • 原文地址:https://www.cnblogs.com/zjbky/p/8796765.html
Copyright © 2020-2023  润新知