我正在尝试在 golang 中实现 AES-256-CBC 加密。我有一个已经使用多年的有效 PHP 代码。我在 Golang 中获取加密值,但是对于相同的有效负载/密钥/iv 组合,这些值与 PHP 的输出不匹配。
为简化起见,我在下面的代码中对有效负载/密钥/iv 进行了硬编码。我还从我的 go 代码中删除了详细的错误消息。
这是我的 GO 代码
func encryption() {
plaintext := []byte("12345678912345678912345678900000")
key, _ := base64.StdEncoding.DecodeString("cidRgzwfcgztwae/mccalIeedOAmA/CbU3HEqWz1Ejk=")
iv, _ := hex.DecodeString("162578ddce177a4a7cb2f7c738fa052d")
/*php seem to use PKCS7 padding to make the source string match the blocksize
requirement for AES-256-CBC.
From what I understand, I need to do padding manually in Golang.
Correct me if wrong */
plaintext, _ = Pkcs7Pad(plaintext, aes.BlockSize)
block, _ := aes.NewCipher(key)
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
fmt.Printf("EncryptedText %v\n", string(ciphertext))
fmt.Printf("EncryptedText as hex %v\n", hex.EncodeToString(ciphertext))
}
func Pkcs7Pad(b []byte, blocksize int) ([]byte, error) {
if blocksize <= 0 {
return nil, errors.New("Invalid block size")
}
if b == nil || len(b) == 0 {
return nil, errors.New("Invalid block size")
}
n := blocksize - (len(b) % blocksize)
pb := make([]byte, len(b)+n)
copy(pb, b)
copy(pb[len(b):], bytes.Repeat([]byte{byte(n)}, n))
return pb, nil
}
我的 Go 输出是
EncryptedText |8??X?z??F ?0ĺe?,??G?V?
Gce??dM????z?,*ȁҼ
EncryptedText as hex 7c38bad658907a81d14620c930c4ba658c1f022cdb1392479856cc0a471d6365dfc5644db6b28cef7ac02c2ac881d2bc
我有一个 PHP 代码来执行相同的任务,这给了我不同的输出。
function encryption() {
$plaintext = "12345678912345678912345678900000";
$key = base64_decode("cidRgzwfcgztwae/mccalIeedOAmA/CbU3HEqWz1Ejk=");
$iv = hex2bin("162578ddce177a4a7cb2f7c738fa052d");
//php openssl_encrypt function seem to use pkcs7pad to make the source string match the blocksize requirement for AES-256-CBC
$ciphertext = openssl_encrypt($plaintext, 'AES-256-CBC', $key, 0, $iv );
print $ciphertext;
}
PHP输出是
fDi61liQeoHRRiDJMMS6ZYwfAizbE5JHmFbMCkcdY2XfxWRNtrKM73rALCrIgdK8
显然,我想让我的 Golang 实现获得与 PHP 相同的输出。由于我需要与我的 Golang 代码和现有的 PHP 代码进行通信,因此我希望在 PHP 和 Golang 中进行相同的加密和解密工作。
有任何想法吗?