AES解密

  #region aes解密
    private static readonly Encoding CHARSET = Encoding.UTF8;
    /// <summary>
    /// 解密给定的AES加密文本
    /// </summary>
    /// <param name="text">需要解密的文本</param>
    /// <param name="aesKey">AES密钥</param>
    /// <returns>解密后的文本</returns>
    /// <exception cref="SecurityException">解密失败抛出异常</exception>
    public static string Decrypt(string text, string aesKey)
    {
        byte[] original;
        try
        {
            // 使用Aes类创建AES解密对象
            using Aes aes = Aes.Create();
            aes.Key = Convert.FromBase64String(aesKey);
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.None;
            aes.IV = aes.Key.Take(16).ToArray();

            // 解密过程
            byte[] encrypted = Convert.FromBase64String(text);
            using ICryptoTransform decryptor = aes.CreateDecryptor();
            original = decryptor.TransformFinalBlock(encrypted, 0, encrypted.Length);
        }
        catch (System.Exception e)
        {
            Console.WriteLine(e.StackTrace);
            throw new SecurityException("aes解密失败", e);
        }

        string xmlContent;
        try
        {
            // 对解密后的byte[]数组进行解码
            byte[] bytes = PKCS7Encoder.Decode(original);

            // 获取XML长度并解密XML文本
            byte[] networkOrder = bytes.Skip(16).Take(4).ToArray();
            int xmlLength = RecoverNetworkBytesOrder(networkOrder);
            xmlContent = CHARSET.GetString(bytes.Skip(20).Take(xmlLength).ToArray());
        }
        catch (System.Exception e)
        {
            Console.WriteLine(e.StackTrace);
            throw new SecurityException("解密后得到的buffer非法", e);
        }
        return xmlContent;
    }

    // 恢复网络字节序,将byte数组转为int类型
    private static int RecoverNetworkBytesOrder(byte[] orderBytes)
    {
        int sourceNumber = 0;
        for (int i = 0; i < 4; i++)
        {
            sourceNumber <<= 8;
            sourceNumber |= orderBytes[i] & 0xff;
        }
        return sourceNumber;
    }

    // PKCS7编码类,提供PKCS7编码方式的实现
    private class PKCS7Encoder
    {
        private const int BLOCK_SIZE = 32;

        // PKCS7解码实现
        public static byte[] Decode(byte[] decrypted)
        {
            int pad = (int)decrypted[decrypted.Length - 1];
            if (pad < 1 || pad > BLOCK_SIZE)
            {
                pad = 0;
            }
            return decrypted.Take(decrypted.Length - pad).ToArray();
        }
    }
    #endregion

 

posted @ 2023-05-09 11:09  左耳*  阅读(73)  评论(0编辑  收藏  举报