知识的搬运者

Unity项目之AES加密

2020-04-07  本文已影响0人  会奔跑的蘑菇
using System.Text;

using System.Security.Cryptography;

using System;

public class EncryptDecipherTool

{

    //加密和解密采用相同的key,可以任意数字,但是必须为32位

    private static string key = "12345678123456781234567812345678";

    public static string Encrypt(string content)

    {

        return Encrypt(content, key);

    }

    //AES加密

    public static string Encrypt(string content, string k)

    {

        byte[] keyBytes = UTF8Encoding.UTF8.GetBytes(k);

        RijndaelManaged rm = new RijndaelManaged();

        rm.Key = keyBytes;

        rm.Mode = CipherMode.ECB;

        rm.Padding = PaddingMode.PKCS7;

        ICryptoTransform ict = rm.CreateEncryptor();

        byte[] contentBytes = UTF8Encoding.UTF8.GetBytes(content);

        byte[] resultBytes = ict.TransformFinalBlock(contentBytes, 0, contentBytes.Length);

        return Convert.ToBase64String(resultBytes, 0, resultBytes.Length);

    }

    public static string Decipher(string content)

    {

        return Decipher(content, key);

    }

    //AES解密

    public static string Decipher(string content, string k)

    {

        byte[] keyBytes = UTF8Encoding.UTF8.GetBytes(k);

        RijndaelManaged rm = new RijndaelManaged();

        rm.Key = keyBytes;

        rm.Mode = CipherMode.ECB;

        rm.Padding = PaddingMode.PKCS7;

        ICryptoTransform ict = rm.CreateDecryptor();

        byte[] contentBytes = Convert.FromBase64String(content);

        byte[] resultBytes = ict.TransformFinalBlock(contentBytes, 0, contentBytes.Length);

        return UTF8Encoding.UTF8.GetString(resultBytes);

    }

}

上一篇 下一篇

猜你喜欢

热点阅读