ASP.NET AES-128-CBC加密解密(与php通讯)

最近有个项目需要和php进行接口对接,讨论到了接口加密相关的内容,最后定下来使用AES-128-CBC的加密方式。

but,在和php端进行加密解密验证的时候踩坑无数,特此记录。

php端代码:

    /**
     * AES 加密
     */
    public static function encrypt($input) {
        $key    = key;
        $method = "AES-128-CBC";
        $iv     = iv;
        $output = openssl_encrypt($input, $method, $key, 1, $iv);
        return base64_encode($output);
    }

    /**
     * AES 解密
     *
     */
    public static function secured_decrypt($input) {
        $key    = key;
        $method = "AES-128-CBC";
        $iv     = iv;
        $input  = base64_decode($input);
        $output = openssl_decrypt($input, $method, $key, 1, $iv);
        return $output;
    }

  对应C#端代码:

        //AES加密
        public static string Encrypt(string toEncrypt)
        {
            byte[] keyArray = Encoding.Default.GetBytes(key);
            byte[] ivArray = Encoding.Default.GetBytes(iv);
            byte[] toEncryptArray = Encoding.Default.GetBytes(toEncrypt);

            RijndaelManaged rDel = new RijndaelManaged
            {
                Key = keyArray,
                IV = ivArray,
                Mode = CipherMode.CBC,
                Padding = PaddingMode.PKCS7
            };

            ICryptoTransform cTransform = rDel.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        //AES解密
        public static string Decrypt(string toDecrypt)
        {
            byte[] keyArray = Encoding.Default.GetBytes(key);
            byte[] ivArray = Encoding.Default.GetBytes(iv);
            byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);

            RijndaelManaged rDel = new RijndaelManaged
            {
                Key = keyArray,
                IV = ivArray,
                Mode = CipherMode.CBC,
                Padding = PaddingMode.PKCS7
            };

            ICryptoTransform cTransform = rDel.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return Encoding.Default.GetString(resultArray);
        }

其中:key和iv是双方约定好的密钥和初始化向量。

上一篇:4/24 学习总结


下一篇:C语言程序实验报告IV