AES加解密 随机向量 密文一次一变 C#与PHP 程序加解密互通

1、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、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、测试截图
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值