微信AES-128-CBC加密解密
Posted 花间岛
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了微信AES-128-CBC加密解密相关的知识,希望对你有一定的参考价值。
[TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { var key = "cheayeon"; var iv = "encoding"; var text = "sb sb ha ha ha"; //对text,key iv 进行base64加密 var enKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(key)); var enIv = Convert.ToBase64String(Encoding.UTF8.GetBytes(iv)); var enText = Convert.ToBase64String(Encoding.UTF8.GetBytes(text)); //加密 var encryp = AesEncryp(enText, enKey,enIv); //解密 var decryp = AesDecryp(encryp, enKey, enIv); } /// <summary> /// 加密密text /// 王剑锋 2018年7月7日09:58:34 /// </summary> /// <param name="text">明文</param> /// <param name="key">秘钥,Base64串</param> /// <param name="iv">向量,Base64串</param> /// <returns></returns> public string AesEncryp(string text,string key,string iv) { var aes = Aes.Create(); //AES-128-CBC PKCS#7 aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.KeySize = 128; aes.BlockSize = 128; //Base64解密text,KEY,IV,不够16位填充0 aes.Key = Padding16(Convert.FromBase64String(key),0); aes.IV = Padding16(Convert.FromBase64String(iv),0); //获取该算法规则下的加密器 var encryp = aes.CreateEncryptor(); //加密之前加一个Base64解密 ,要加密的数据 var dataBytes = Convert.FromBase64String(text); //获取AES-128-CBC PKCS#7 密文 var enData = encryp.TransformFinalBlock(dataBytes,0, dataBytes.Length); return Convert.ToBase64String(enData); } /// <summary> /// 解密text /// 王剑锋 2018年7月7日09:58:16 /// </summary> /// <param name="text">密文</param> /// <param name="key">秘钥,Base64串</param> /// <param name="iv">向量,Base64串</param> /// <returns></returns> public string AesDecryp(string text, string key, string iv) { var aes = Aes.Create(); //AES-128-CBC PKCS#7 aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.KeySize = 128; aes.BlockSize = 128; //Base64解密text,KEY,IV aes.Key = Padding16(Convert.FromBase64String(key),0); aes.IV = Padding16(Convert.FromBase64String(iv),0); //获取该算法规则下的解密器 var encryp = aes.CreateDecryptor(); //加密之前加一个Base64解密 ,要加密的数据 var dataBytes = Convert.FromBase64String(text); //获取AES-128-CBC PKCS#7 明文 var enData = encryp.TransformFinalBlock(dataBytes, 0, dataBytes.Length); return Encoding.UTF8.GetString(enData); } /// <summary> /// 不够16位的整数倍,已指定字符填充 /// </summary> /// <param name="array"></param> /// <param name="padding"></param> /// <returns></returns> public byte[] Padding16(byte [] array,byte padding) { int group = (array.Length + 15) / 16; var newArray = new byte[group*16]; for (int i = 0; i < newArray.Length; i++) { newArray[i] = (i < array.Length ? array[i] : padding); } return newArray; }
以上是关于微信AES-128-CBC加密解密的主要内容,如果未能解决你的问题,请参考以下文章
AES (aes-cbc-128, aes-cbc-192, aes-cbc-256) 使用 openssl C 加密/解密
无法使用来自 AES-256-CBC 的 pgcrypto 解密,但 AES-128-CBC 可以