/// <summary> /// 根据加密类型加密 /// </summary> /// <param name="inputBytes"> 需要加密的正文 </param> /// <param name="randomBytes">随机填充</param> /// <param name="aesKeyStatic">静态密钥</param> /// <param name="aesKeyDynamic">动态密钥</param> /// <param name="type">加密类型</param> /// <param name="ms">内存流</param> private static void InternalWriteEncryptDataByType(byte[] inputBytes, byte[] randomBytes, string aesKeyStatic, string aesKeyDynamic, EncryptType type, MemoryStream ms) { byte[] encBytes = inputBytes; int intType = (int)type; //客户端密钥更新强制优先检查 if ((intType & ((int)EncryptType.ResetKey)) != 0) { InternalWriteKeyUpdate(aesKeyStatic, randomBytes, ms); } int maxType = 16; int child; EncryptType childType; int encryptCount = 0; while (maxType > 0) { maxType = maxType >> 1; child = maxType & intType; if (child == 0) { continue; } encryptCount++; childType = (EncryptType)child; switch (childType) { case EncryptType.ResetKey: break; case EncryptType.AES: encBytes = Cipher_Aes.EncryptToBytes(encBytes, aesKeyDynamic); break; case EncryptType.Gzip: encBytes = Cipher_Gzip.Compress(encBytes); break; case EncryptType.PT: break; default: throw new Exception("未受支持的加密类型"); } } if (encryptCount < 0) { throw new Exception("未识别的加密类型"); } if (encBytes != null) { ms.Write(encBytes, 0, encBytes.Length); } }
/// <summary> /// 解密正文并返回 /// </summary> /// <param name="intType">int32的 加密类型</param> /// <param name="aesKeyDynamic">动态加密</param> /// <param name="ms">内存协议流</param> /// <returns></returns> private static byte[] InternalDecryptReturnContent(int intType, string aesKeyDynamic, MemoryStream ms) { //当前位置 int currPos = (int)ms.Position; int encTextCount = (int)ms.Length - currPos; byte[] retBytes = new byte[encTextCount]; ms.Read(retBytes, 0, retBytes.Length); int currType = 1; EncryptType state; //这里的8是因为当前最大类别就是8 while (currType <= 8) { if ((currType & intType) != 0) { state = (EncryptType)currType; switch (state) { case EncryptType.AES: retBytes = Cipher_Aes.DecryptToBytes(retBytes, aesKeyDynamic); break; case EncryptType.Gzip: retBytes = Cipher_Gzip.Decompress(retBytes); break; //纯文本,不需要解密 case EncryptType.PT: break; //最早判断,已经读取过了 case EncryptType.ResetKey: break; } } currType = currType << 1; } return(retBytes); }
public static string DeGzip(this string input) => Encoding.UTF8.GetString(Cipher_Gzip.Decompress(Convert.FromBase64String(input)));
public static string ToGzip(this string input) => Convert.ToBase64String(Cipher_Gzip.Compress(Encoding.UTF8.GetBytes(input)));