Files
JJBB/Assets/Project/Script/GameLogic/GameManager/DESEncryption.cs
2024-08-23 15:49:34 +08:00

83 lines
2.7 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;
public sealed class DESEncryption
{
private static readonly string encryptKey = "5e7b18db";
private static readonly string decryptKey = "5e7b18db";
#region**********Method*******************************
private static TripleDESCryptoServiceProvider TripleDes = new TripleDESCryptoServiceProvider();
//---指定密钥的哈希创建指定长度的字节数组
private static byte[] TruncateHash(string key, int length)
{
// byte[] functionReturnValue = 0;
SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
// Hash the key.
byte[] keyBytes = System.Text.Encoding.Unicode.GetBytes(key);
byte[] hash = sha1.ComputeHash(keyBytes);
// Truncate or pad the hash.
Array.Resize(ref hash, length);
return hash;
}
//添加用来初始化 3DES 加密服务提供程序的构造函数。
//key 参数控制 EncryptData 和 DecryptData 方法。
public static void Init(string key)
{
// Initialize the crypto provider.
TripleDes.Key = TruncateHash(key, TripleDes.KeySize / 8);
TripleDes.IV = TruncateHash("", TripleDes.BlockSize / 8);
}
//添加加密字符串的公共方法
public static string EncryptData(string plaintext)
{
Init(encryptKey);
byte[] plaintextBytes = System.Text.Encoding.Unicode.GetBytes(plaintext);
return Convert.ToBase64String(EncryptData(plaintextBytes));
}
public static byte[] EncryptData(byte[] plaintextBytes)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
CryptoStream encStream = new CryptoStream(ms, TripleDes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
encStream.Write(plaintextBytes, 0, plaintextBytes.Length);
encStream.FlushFinalBlock();
return ms.ToArray();
}
//添加解密字符串的公共方法
public static string DecryptData(string encryptedtext)
{
#if !Code_Encryption
return encryptedtext;
#endif
//return encryptedtext;
//Debug.Log("DecryptData:" + encryptedtext);
Init(decryptKey);
byte[] encryptedBytes = Convert.FromBase64String(encryptedtext);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
CryptoStream decStream = new CryptoStream(ms, TripleDes.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
decStream.Write(encryptedBytes, 0, encryptedBytes.Length);
decStream.FlushFinalBlock();
return System.Text.Encoding.Unicode.GetString(ms.ToArray());
}
#endregion
}