@
ca2oh4 我当时也考虑用 golang 写一个脚本,然后 php 通过 http 调用。不过后面解决了就不用了。这是当时写的 golang 案例
```golang
package main
import (
"bytes"
"crypto/cipher"
"encoding/hex"
"fmt"
"
github.com/tjfoc/gmsm/sm4"
)
// PKCS5Padding 使用 PKCS5 填充
func PKCS5Padding(src []byte, blockSize int) []byte {
padding := blockSize - len(src)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(src, padtext...)
}
// PKCS5UnPadding 去除 PKCS5 填充
func PKCS5UnPadding(src []byte) []byte {
length := len(src)
unpadding := int(src[length-1])
return src[:(length - unpadding)]
}
// SM4 CBC 模式加密
func sm4CBCEncrypt(key, plaintext, iv []byte) ([]byte, error) {
block, err := sm4.NewCipher(key)
if err != nil {
return nil, err
}
plaintext = PKCS5Padding(plaintext, block.BlockSize())
ciphertext := make([]byte, len(plaintext))
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext, plaintext)
return ciphertext, nil
}
// SM4 CBC 模式解密
func sm4CBCDecrypt(key, ciphertext, iv []byte) ([]byte, error) {
block, err := sm4.NewCipher(key)
if err != nil {
return nil, err
}
plaintext := make([]byte, len(ciphertext))
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(plaintext, ciphertext)
plaintext = PKCS5UnPadding(plaintext)
return plaintext, nil
}
func main() {
key, _ := hex.DecodeString("key") // 16 字节的十六进制密钥
iv, _ := hex.DecodeString("iv") // 16 字节的 IV
plaintext := []byte("This is a secret message.")
// 加密
ciphertext, err := sm4CBCEncrypt(key, plaintext, iv)
if err != nil {
fmt.Println("Encryption error:", err)
return
}
fmt.Printf("Ciphertext (hex): %s\n", hex.EncodeToString(ciphertext))
// 解密
decrypted, err := sm4CBCDecrypt(key, ciphertext, iv)
if err != nil {
fmt.Println("Decryption error:", err)
return
}
fmt.Printf("Decrypted text: %s\n", decrypted)
}
```