Cifrado y descifrado AES texto cifrado de vector aleatorio un cambio a la vez Interoperabilidad de cifrado y descifrado de programas C# y PHP

1. Parte C#

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

/// <summary>
/// AES加密解密
/// </summary>
public class AES
{
    
    

    public string AESKey {
    
     get; set; }
    public AES()
    {
    
    
        AESKey = "ABCD0123abcd!@#$"; 
    }


    public  string Encrypt(string plainText)
    {
    
    
        RijndaelManaged rijndaelCipher = new RijndaelManaged();
        byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字节数组 
        rijndaelCipher.Key = Encoding.UTF8.GetBytes(AESKey);//加解密双方约定好密钥:AESKey
        rijndaelCipher.GenerateIV();
        byte[] keyIv = rijndaelCipher.IV;
        byte[] cipherBytes = null;
        using (MemoryStream ms = new MemoryStream())
        {
    
    
            using (CryptoStream cs = new CryptoStream(ms, rijndaelCipher.CreateEncryptor(), CryptoStreamMode.Write))
            {
    
    
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                cipherBytes = ms.ToArray();//得到加密后的字节数组
                cs.Close();
                ms.Close();
            }
        }
        var allEncrypt = new byte[keyIv.Length + cipherBytes.Length];
        Buffer.BlockCopy(keyIv, 0, allEncrypt, 0, keyIv.Length);
        Buffer.BlockCopy(cipherBytes, 0, allEncrypt, keyIv.Length * sizeof(byte), cipherBytes.Length);
        return Convert.ToBase64String(allEncrypt);
    }

    public  string Decrypt(string showText)
    {
    
    
        string result = string.Empty;
        try
        {
    
    
            byte[] cipherText = Convert.FromBase64String(showText);
            int length = cipherText.Length;
            SymmetricAlgorithm rijndaelCipher = Rijndael.Create();
            rijndaelCipher.Key = Encoding.UTF8.GetBytes(AESKey);//加解密双方约定好的密钥
            byte[] iv = new byte[16];
            Buffer.BlockCopy(cipherText, 0, iv, 0, 16);
            rijndaelCipher.IV = iv;
            byte[] decryptBytes = new byte[length - 16];
            byte[] passwdText = new byte[length - 16];
            Buffer.BlockCopy(cipherText, 16, passwdText, 0, length - 16);
            using (MemoryStream ms = new MemoryStream(passwdText))
            {
    
    
                using (CryptoStream cs = new CryptoStream(ms, rijndaelCipher.CreateDecryptor(), CryptoStreamMode.Read))
                {
    
    
                    cs.Read(decryptBytes, 0, decryptBytes.Length);
                    cs.Close();
                    ms.Close();
                }
            }
            result = Encoding.UTF8.GetString(decryptBytes).Replace("\0", "");   ///将字符串后尾的'\0'去掉
        }
        catch (Exception ex)
        {
    
    
            return ex.Message;
        }
      
        return result;
    }



}

2. Parte PHP

<?php

class Aes
{
    
    
    //构造函数  
    public function __construct($config)
    {
    
    
        //加载配置
        foreach($config as $k => $v)
        {
    
    
            $this->$k = $v;
        }
    }
    //加密
    public function aesEn($data){
    
    
        return  base64_encode(
            $this->iv. //将 iv data 拼接在一起
            openssl_encrypt(
                $data, 
                $this->method,
                $this->key, 
                OPENSSL_RAW_DATA , 
                $this->iv
            )
        ); 
    }
    
    //解密
    public function aesDe($data){
    
    
        $data_0=base64_decode($data);
        $this->iv=substr($data_0, 0, 16); //拆分出iv,定长16
        $data=substr($data_0, 16, strlen($data_0)-16); //余下为数据
        return openssl_decrypt(
            $data,  
            $this->method, 
            $this->key, 
            OPENSSL_RAW_DATA, 
            $this->iv
        );
    }
}

//加密配置项
$config = [
    'key'=>'ABCD0123abcd!@#$', //加密key 长度16
    'iv'=>md5(time().uniqid(),true), //随机产生且保证偏移量为16位
    'method'=> 'AES-128-CBC' //加密方式  # AES-256-CBC等
];
  
$obj = new Aes($config); //创建一个对象,加载配置
var_dump($obj->aesEn('2022'));//加密数据
var_dump($obj->aesDe('smsWfpVuFek4d5UHjEsiRAc0C2KE/3JpRQtil+HTY5g='));//解密数据


3. Prueba de captura de pantalla

inserte la descripción de la imagen aquí
inserte la descripción de la imagen aquí

Supongo que te gusta

Origin blog.csdn.net/lzl640/article/details/127447055
Recomendado
Clasificación