接口传输需要加密敏感信息时,可以使用aes进行对称加密,前后端约定加解密方式。

前端JavaScript,主要是依赖 crypto-js 的 4.1.1 版本。

import CryptoJS from "crypto-js";

const keyStr = '5ad466edc44a2c6567e502d128280a7f';// 和后端约定好

const ivStr = '#2%gaFD4VD7zuxFj';// 和后端约定好


export default {
// 加密
encrypt(data) {
const key = CryptoJS.enc.Latin1.parse(keyStr);
const iv = CryptoJS.enc.Latin1.parse(ivStr);
const encoded = CryptoJS.AES.encrypt(data, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
adding: CryptoJS.pad.ZeroPadding
}).toString()
return encoded;
},
// 解密
decrypt(data) {
const key = CryptoJS.enc.Latin1.parse(keyStr);
const iv = CryptoJS.enc.Latin1.parse(ivStr);
const decoded = CryptoJS.AES.decrypt(data, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
adding: CryptoJS.pad.ZeroPadding
}).toString(CryptoJS.enc.Utf8)
return decoded;
}
};

PHP 后端加解密

<?php

declare (strict_types=1);


namespace App\util;


/**
*
* @ClassName AES
* @Version 1.0
* @Description
* @package App\util
*/
class AES
{
private $method;

private $iv;

private $position = 0;

public function __construct($method = "AES-256-CBC")
{
$this->method = $method;
}

public function getIvLen(): int
{
return openssl_cipher_iv_length($this->method);
}

public function setIv(string $iv): self
{
$this->iv = $iv;
return $this;
}

public function getIv(): string
{
return $this->iv;
}

public function encrypt(string $data, string $key, bool $base64 = true): array
{
if (!$this->iv) {
$ivLen = $this->getIvLen();
try {
$this->iv = random_bytes($ivLen);
} catch (\Throwable $exception) {
throw new \Exception("生成iv失败");
}
}
$base64 && $data = base64_encode($data);
$result = openssl_encrypt($data, $this->method, $key, $this->position, $this->iv);
return [
'result' => $result, 'iv' => $this->iv,
];
}

public function decrypt(string $data, string $iv, string $key, bool $base64 = true): string
{
$result = openssl_decrypt($data, $this->method, $key, $this->position, $iv);
if ($result === false) {
throw new \Exception("解密失败");
}
$base64 && $result = base64_decode($result);
return $result;
}
}