标签:tee tor oba als byte ascii mes sum start
using System.IO;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;
namespace Web.Networking
{
/// <summary>
/// AES + Base64 双重加密。
/// </summary>
public class AesBase64Encrypt
{
static bool enable = false;
/// <summary>
/// AES加密所使用的密钥,需要与服务端一致。
/// </summary>
private static string private_key = "S46ZT_UHY*U3HVLC";
/// <summary>
/// 使用特定的配置创建AES加密实例,需要保持Mode、Padding、IV与服务端一致。
/// </summary>
/// <returns>The aes.</returns>
static Aes CreateAes()
{
byte[] key = Encoding.ASCII.GetBytes(private_key);
Aes aes = Aes.Create();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.Zeros;
aes.Key = key;
aes.IV = key;
return aes;
}
/// <summary>
/// 加密字符串
/// </summary>
/// <param name="toEncrypt">待加密的字符串</param>
public static string Encrypt(string toEncrypt)
{
if (!enable)
{
return toEncrypt;
}
Aes aes = CreateAes();
ICryptoTransform cTransform = aes.CreateEncryptor();
byte[] sourceData = Encoding.UTF8.GetBytes(toEncrypt);
byte[] cryptData = cTransform.TransformFinalBlock(sourceData, 0, sourceData.Length);
string cryptString = System.Convert.ToBase64String(cryptData);
return cryptString;
}
/// <summary>
/// 移除开头与结尾的双引号
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static string RemoveInvalidQuotes(string str)
{
str = str.TrimStart(‘"‘).TrimEnd(‘"‘);
return str;
}
/// <summary>
/// 移除末尾的 NULL 字符
/// </summary>
/// <returns></returns>
/// <param name="str"></param>
static string RemoveInvalidNulls(string str)
{
str = str.TrimEnd(‘\0‘);
return str;
}
/// <summary>
/// 解密字符串
/// </summary>
/// <param name="toDecrypt">待解密的字符串</param>
public static string Decrypt(string toDecrypt)
{
if (!enable)
{
return toDecrypt;
}
// 服务端返回格式需要预处理
// 移除多余的双引号
toDecrypt = RemoveInvalidQuotes(toDecrypt);
Aes aes = CreateAes();
ICryptoTransform cTransform = aes.CreateDecryptor();
byte[] encryptedData = System.Convert.FromBase64String(toDecrypt);
byte[] originalSourceData = cTransform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
string originalString = Encoding.UTF8.GetString(originalSourceData);
// 解密后会有多余的NULL字符在末尾,需要移除
originalString = RemoveInvalidNulls(originalString);
return originalString;
}
}
}
标签:tee tor oba als byte ascii mes sum start
原文地址:http://www.cnblogs.com/0315cz/p/7993295.html