golang php aes-256-cbc decrypt example

Golang 和 PHP 均可使用对称加密算法 AES(也称作 Rijndael)进行加密和解密。如果你使用的是 AES-256-CBC 模式,那么你可以使用如下代码在 Golang 中进行解密:

package main
import (
	"crypto/aes"
	"crypto/cipher"
	"fmt"
func main() {
	key := []byte("1234567890abcdef1234567890abcdef")
	ciphertext := []byte("d1b66cc7c1bcc92f8a9f9b9dce7f49b5")
	block, err := aes.NewCipher(key)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	if len(ciphertext) < aes.BlockSize {
		fmt.Println("ciphertext too short")
		os.Exit(1)
	iv := ciphertext[:aes.BlockSize]
	ciphertext = ciphertext[aes.BlockSize:]
	stream := cipher.NewCFBDecrypter(block, iv)
	stream.XORKeyStream(ciphertext, ciphertext)
	fmt.Printf("%s\n", ciphertext)

你可以使用如下代码在 PHP 中进行解密:

$key = "1234567890abcdef1234567890abcdef";
$ciphertext = "d1b66cc7c1bcc92f8a9f9b9dce7f49b5";
$ivsize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = substr($ciphertext, 0, $ivsize);
$ciphertext = substr($ciphertext, $ivsize);
$plaintext = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext, MCRYPT_MODE_CBC, $iv);
echo $plaintext;

注意:这里的代码仅供参考,你需要确保使用了安全的密钥和初始向量,并且应该注意在生产环境中使用的加密算法的安全性。

  •