前后端(PHP)使用AES对称加密

// 这个是加密用的
function encrypt(text){
    var key = CryptoJS.enc.Utf8.parse('1463587320654321'); //为了避免补位,直接用16位的秘钥
    var iv = CryptoJS.enc.Utf8.parse('1758326540123456'); //16位初始向量
    var encrypted = CryptoJS.AES.encrypt(text, key, {
            iv: iv,
            mode:CryptoJS.mode.CBC,
            padding:CryptoJS.pad.Pkcs7
        });
    return encrypted.toString();
}
encrypt(123); // AMFSKTJa3K092qSi5XC46w==

// 这个是解密用的
function decrypt (text) {
  var key = CryptoJS.enc.Utf8.parse('1463587320654321'); //为了避免补位,直接用16位的秘钥
  var iv = CryptoJS.enc.Utf8.parse('1758326540123456'); //16位初始向量
  var encrypted = CryptoJS.AES.decrypt(text, key, {
      iv: iv,
      mode:CryptoJS.mode.CBC,
      padding:CryptoJS.pad.Pkcs7

  }); 

  return encrypted.toString(CryptoJS.enc.Utf8); 
}

php

/**
 * 传输密码加解密
 */
function encryptWithOpenssl($data = '',$key='1463587320654321',$iv='1758326540123456')
{
    $a = openssl_encrypt($data, 'aes-128-cbc', $key, 1, $iv);
    return base64_encode($a);
}

function dencryptWithOpenssl($data = '',$key='1463587320654321',$iv='1758326540123456')
{
    return openssl_decrypt($data, 'aes-128-cbc', $key, 0, $iv);
}
dd(dencryptWithOpenssl(encryptWithOpenssl(123456)));//123456

你可能感兴趣的:(笔记,php)