php js 通用加密算法,一个 aes-js 库 里加密算法用 PHP 怎么写?

下面是官方文档 demo 代码

const aesjs = require('aes-js');

// An example 128-bit key

var key = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ];

// The initialization vector (must be 16 bytes)

var iv = [ 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,35, 36 ];

// Convert text to bytes (must be a multiple of the segment size you choose below)

var text = 'TextMustBeAMultipleOfSegmentSize';

var textBytes = aesjs.utils.utf8.toBytes(text);

// The segment size is optional, and defaults to 1

var segmentSize = 8;

// console.log(iv);

//

var aesCfb = new aesjs.ModeOfOperation.cfb(key, iv, segmentSize);

// var encryptedBytes = aesCfb.encrypt(textBytes);

// To print or store the binary data, you may convert it to hex

var encryptedHex = aesjs.utils.hex.fromBytes(encryptedBytes);

console.log(encryptedHex);

// "55e3af2638c560b4fdb9d26a630733ea60197ec23deb85b1f60f71f10409ce27"

// When ready to decrypt the hex string, convert it back to bytes

var encryptedBytes = aesjs.utils.hex.toBytes(encryptedHex);

// The cipher feedback mode of operation maintains internal state,

// so to decrypt a new instance must be instantiated.

var aesCfb = new aesjs.ModeOfOperation.cfb(key, iv, 8);

var decryptedBytes = aesCfb.decrypt(encryptedBytes);

// Convert our bytes back into text

var decryptedText = aesjs.utils.utf8.fromBytes(decryptedBytes);

console.log(decryptedText);

// "TextMustBeAMultipleOfSegmentSize"

怎么改造下用 php 来写?

// 加密算法

$encryptMethod = 'aes-128-cfb';

// 明文数据

$data = 'TextMustBeAMultipleOfSegmentSize';

$secret = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];

// 生成 IV

$ivLength = openssl_cipher_iv_length($encryptMethod);

$iv = openssl_random_pseudo_bytes($ivLength, $isStrong);

if (false === $iv && false === $isStrong) {

die('IV generate failed');

}

// 加密

$encrypted = openssl_encrypt($data, $encryptMethod, $secret, 8, $iv);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值