无法弄清楚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
}
在节点Js中 - 输出: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');
起初认为这是一个编码问题,但我认为这是正确的 - 将返回base64值。我需要将PHP变体翻译成GoLang,但是(几乎)任何其他语言的示例将不胜感激。openssl_encrypt
慕桂英546537
跃然一笑
相关分类