84 lines
2.9 KiB
C#
Raw Normal View History

2025-06-07 17:43:34 +08:00
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class EncryptUtils
{
#if UNITY_EDITOR
[UnityEditor.MenuItem("Framework/加密key生成")]
static private void GenRSAKey()
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
string publickey = rsa.ToXmlString(false);
string privatekey = rsa.ToXmlString(true);
}
#endif
static public byte[] RSAEncrypt(string publickey, byte[] content)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
byte[] cipherbytes;
rsa.FromXmlString(publickey);
cipherbytes = rsa.Encrypt(content, false);
return cipherbytes;
}
static public byte[] RSADecrypt(string privatekey, byte[] content)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
byte[] cipherbytes;
rsa.FromXmlString(privatekey);
cipherbytes = rsa.Decrypt(content, false);
return cipherbytes;
}
public static byte[] DESEncrypt(byte[] data, string desrgbKey, string desrgbIV)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream memoryStream = new MemoryStream();
byte[] desrgbKeyBs = Encoding.UTF8.GetBytes(desrgbKey);
byte[] desrgbIVBs = Encoding.UTF8.GetBytes(desrgbIV);
CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(desrgbKeyBs, desrgbIVBs), CryptoStreamMode.Write);
cryptoStream.Write(data, 0, data.Length);
cryptoStream.FlushFinalBlock();
return memoryStream.ToArray();
}
public static byte[] DESDecrypt(byte[] data, string desrgbKey, string desrgbIV)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream memoryStream = new MemoryStream();
byte[] desrgbKeyBs = Encoding.UTF8.GetBytes(desrgbKey);
byte[] desrgbIVBs = Encoding.UTF8.GetBytes(desrgbIV);
CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(desrgbKeyBs, desrgbIVBs), CryptoStreamMode.Write);
cryptoStream.Write(data, 0, data.Length);
cryptoStream.FlushFinalBlock();
return memoryStream.ToArray();
}
public static byte[] AESEncrypt(byte[] data, string key)
{
RijndaelManaged aes256 = new RijndaelManaged();
aes256.Key = Encoding.UTF8.GetBytes(key);
aes256.Mode = CipherMode.ECB;
aes256.Padding = PaddingMode.PKCS7;
return aes256.CreateEncryptor().TransformFinalBlock(data, 0, data.Length);
}
public static byte[] AESDecrypt(byte[] data, string key)
{
RijndaelManaged aes256 = new RijndaelManaged();
aes256.Key = Encoding.UTF8.GetBytes(key);
aes256.Mode = CipherMode.ECB;
aes256.Padding = PaddingMode.PKCS7;
return aes256.CreateDecryptor().TransformFinalBlock(data, 0, data.Length);
}
}