登录
首页 >  Golang >  Go问答

使用 PHP 对 Golang 数据进行 AES-256-CBC 加密

来源:stackoverflow

时间:2024-02-11 15:03:21 436浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《使用 PHP 对 Golang 数据进行 AES-256-CBC 加密》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

我正在尝试在 php 中实现 aes-256-cbc 加密。我从 golang 代码中得到了数据输出。我尝试在 php 中获取加密值,但总是失败,我尝试解密它。

这是我在 golang 中的加密和解密代码

var key = "abcdabcdabcdabcd"

func main() {
    str := "hello world"
    fmt.printf("origin data : %v\n", str)
    encryptstr := encrypt(str)
    fmt.printf("encrypt data : %v\n", encryptstr)
    decryptstr := decrypt(encryptstr)
    fmt.printf("decrypt data : %v\n", decryptstr)
}

func encrypt(str string) string {

    data := pkcs5padding([]byte(str))
    iv := make([]byte, 16)
    rand.read(iv)

    blockcipher, err := aes.newcipher([]byte(key))
    if err != nil {
        panic(err)
    }

    c := cipher.newcbcencrypter(blockcipher, iv)
    c.cryptblocks(data, data)
    data = append(iv, data...)

    return hex.encodetostring(data)
}

func decrypt(str string) string {

    origin, _ := hex.decodestring(str)

    iv := origin[:16]
    data := origin[16:]

    block, err := aes.newcipher([]byte(key))
    if err != nil {
        panic(err)
    }

    c := cipher.newcbcdecrypter(block, iv)
    c.cryptblocks(data, data)

    return string(data)

}

func pkcs5padding(ciphertext []byte) []byte {
    padding := aes.blocksize - len(ciphertext)%aes.blocksize
    padtext := bytes.repeat([]byte{byte(padding)}, padding)
    return append(ciphertext, padtext...)
}

我可以获得输出:

origin data : hello world
encrypt data : efb5e55e9d2d15e6a61dcfeef322b0da839674e76666962d41f6a00a04d84adf
decrypt data : hello world

在此处运行代码

我的php代码

public function Decode(){

        //encrypt string from golang
        $strFromGolang = "efb5e55e9d2d15e6a61dcfeef322b0da839674e76666962d41f6a00a04d84adf";
        $decode = hex2bin($strFromGolang);

        $key = "abcdabcdabcdabcd";
        //format
        $data = substr($decode, 16);
        $iv = substr($decode, 0, 16);

        $decrypt = openssl_decrypt($data, 'aes-256-cbc', $key, 0, $iv);
        var_dump($decrypt);
    }

和 $decrypt 得到的值

如何修复我的 php 代码以使 $decrypt 解密成功?


正确答案


您有两个问题:

首先,go 加密不使用 aes-256-cbc,而是使用 aes-128-cbc。我不确定如何在 go 端解决此问题,但在 php 端,只需使用 aes-128-cbc 作为密码字符串。

其次,php 解密期望对 base64 编码文本进行操作,而不是对原始二进制字符串进行操作。要解密原始二进制字符串(如您的情况),您需要传递可选的 openssl_raw_data 标志:

$decrypt = openssl_decrypt($data, 'aes-128-cbc', $key, OPENSSL_RAW_DATA, $iv);

以上就是《使用 PHP 对 Golang 数据进行 AES-256-CBC 加密》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>