• 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字节会报错

    运行结果

  • 相关阅读:
    树莓派上使用docker部署aria2,minidlna
    在Ubuntu上部署一个基于webrtc的多人视频聊天服务
    解决.net core3.1使用docker部署在Ubuntu上连接sqlserver报error:35的问题
    .Net Core in Docker
    .Net Core in Docker
    SQL Server in Docker
    使用Docker运行SQL Server
    Spring Boot 2.x(四):整合Mybatis的四种方式
    Spring Boot 2.x (一):HelloWorld
    yarn (npm) 切换设置镜像源
  • 原文地址:https://www.cnblogs.com/foggy2330/p/12591684.html
Copyright © 2020-2023  润新知