【发布时间】:2021-10-27 09:00:48
【问题描述】:
无法弄清楚 PHP openssl_encrypt 是如何工作的,并且无法在 GoLang 和 NodeJs 中重现其输出,这是 PHP 中的简化代码 - 输出 hvAB:
<?php
$string = 'aaa';
$cipher = "AES-128-CTR";
$options = 0;
$encryption_iv = '1234567890123456';
$encryption_key = 'bc7316929fe1545bf0b98d114ee3ecb8';
$encryption = openssl_encrypt($string, $cipher, $encryption_key, $options, $encryption_iv);
echo $encryption; // hvAB
在 GoLang 中,假设密钥必须经过十六进制解码以获得所需的 16 长度,以便使用 AES 128 - 输出 PQ5k:
package main
import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"encoding/hex"
"fmt"
)
func main() {
plainText := "aaa"
fmt.Println(encryption(plainText)) // PQ5k
}
func encryption(plainText string) string {
bytes := []byte(plainText)
blockCipher := createCipher()
stream := cipher.NewCTR(blockCipher, []byte("1234567890123456"))
stream.XORKeyStream(bytes, bytes)
return base64.StdEncoding.EncodeToString(bytes)
}
func createCipher() cipher.Block {
key, _ := hex.DecodeString("bc7316929fe1545bf0b98d114ee3ecb8")
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
return block
}
在 NodeJs 中 - 输出 PQ5k:
var crypto = require('crypto');
var algorithm = 'aes-128-ctr';
function encrypt(text, password) {
const key = Buffer.from(password, "hex").slice(0, 16);
const ivBuffer = Buffer.from("1234567890123456");
const cipher = crypto.createCipheriv(algorithm, key, ivBuffer);
let encrypted = cipher.update(text,'utf8','base64') + cipher.final('base64')
console.log(encrypted) // PQ5k
}
encrypt('aaa', 'bc7316929fe1545bf0b98d114ee3ecb8');
起初认为这是一个编码问题,但我认为这是正确的 - openssl_encrypt 将返回 base64 值。我需要将 PHP 变体翻译成 GoLang,但(几乎)任何其他语言的示例将不胜感激。
【问题讨论】:
标签: php node.js go encryption openssl