AES加解密

using System;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;

public class Test : MonoBehaviour
{
    void Start()
    {
        string key = GetRandomString(32);
        string str = "哦豁,哦豁,哦豁,哦豁哦豁哦豁哦豁哦豁哦豁~";
        string result = AesEncrypt(str, key);
        XMDebug.Log(key);
        XMDebug.Log(result);
        XMDebug.Log(AesDecrypt(result, key));
    }

    /// 
    ///  AES 加密
    /// 
    /// 明文(待加密)
    /// 密文
    /// 
    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);
    }

    /// 
    ///  AES 解密
    /// 
    /// 明文(待解密)
    /// 密文
    /// 
    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);
    }

    /// 
    /// 获取随机字符串
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    public static string GetRandomString(int length, string custom = "", bool useNum = true, bool useLow = true, bool useUpp = true, bool useSpe = true)
    {
        byte[] b = new byte[4];
        new RNGCryptoServiceProvider().GetBytes(b);
        System.Random r = new System.Random(BitConverter.ToInt32(b, 0));
        string s = null, str = custom;
        if (useNum == true) { str += "0123456789"; }
        if (useLow == true) { str += "abcdefghijklmnopqrstuvwxyz"; }
        if (useUpp == true) { str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
        if (useSpe == true) { str += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; }
        for (int i = 0; i < length; i++)
        {
            s += str.Substring(r.Next(0, str.Length - 1), 1);
        }
        return s;
    }
}

 

你可能感兴趣的:(CSharp,AES加解密)