Example #1
0
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="content">加密内容</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        public string Encrypt(byte[] content, byte[] key)
        {
            rijndaelManaged.GenerateIV();

            var aesEncrypt  = rijndaelManaged.CreateEncryptor(key, rijndaelManaged.IV);
            var aesBuffer   = aesEncrypt.TransformFinalBlock(content, 0, content.Length);
            var ivAesBuffer = KArray.Merge(rijndaelManaged.IV, aesBuffer);

            return(Encode(Convert.ToBase64String(rijndaelManaged.IV),
                          Convert.ToBase64String(aesBuffer),
                          Convert.ToBase64String(HMac(ivAesBuffer, key))));
        }
Example #2
0
        /// <summary>
        /// 解密被加密的内容
        /// </summary>
        /// <param name="str">需要解密的字符串</param>
        /// <param name="key">密钥</param>
        /// <returns>解密后的值</returns>
        public byte[] Decrypt(string str, byte[] key)
        {
            string iv, value, hmac;

            Decode(str, out iv, out value, out hmac);

            var aesBuffer   = Convert.FromBase64String(value);
            var ivBuffer    = Convert.FromBase64String(iv);
            var ivAesBuffer = KArray.Merge(rijndaelManaged.IV, aesBuffer);

            if (Convert.ToBase64String(HMac(ivAesBuffer, key)) != hmac)
            {
                throw new Exception("HMac validation failed");
            }

            var aesDecrypt = rijndaelManaged.CreateDecryptor(key, ivBuffer);

            aesBuffer = aesDecrypt.TransformFinalBlock(aesBuffer, 0, aesBuffer.Length);

            return(aesBuffer);
        }