AES 加密解密 php c#

php7

<?php

$key="1234567890123456";

$encrypt_data = openssl_encrypt('ABCDEFG', 'AES-128-ECB', $key, 0, "");
echo $encrypt_data;
echo '<br/>';

$decrypt_data = openssl_decrypt($encrypt_data, 'AES-128-ECB', $key, 0, "");
echo $decrypt_data;
echo '<br/>';

?>

C#

using System;
using System.Security.Cryptography;
using System.Text;

namespace ConsoleApp18
{
    class Program
    {
        static void Main(string[] args)
        {
            var content = "ABCDEFG";

            var key = "1234567890123456";

            var str1 = Encrypt(content, key);
            Console.WriteLine(str1);

            var str2 = Decrypt(str1, key);
            Console.WriteLine(str2);

            Console.ReadLine();
        }

        public static string Encrypt(string toEncrypt, string key)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

            AesCryptoServiceProvider rDel = new AesCryptoServiceProvider();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;

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

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

        public static string Decrypt(string toDecrypt, string key)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);

            AesCryptoServiceProvider rDel = new AesCryptoServiceProvider();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;

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

            return UTF8Encoding.UTF8.GetString(resultArray);
        }
    }
}

注意 php默认的填充方式是PKCS7 密钥长度不够16字节会自动填充 C#密钥长度不够16字节会报错

运行结果

posted on 2020-03-29 12:38  河蟹黄  阅读(555)  评论(2编辑  收藏  举报

导航