php和golang 使用aes CBC模式加解密
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2024-01-31 17:15:07
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章
php加解密
$key = 'yKFdBXEBQSK6wvB4pvnyGgqbPKrCw6Wr'; $iv = '93mVGaEOAUB22dLb'; $data = '123456'; $encrypted = openssl_encrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv); echo base64_encode($encrypted), PHP_EOL; $decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv); echo $decrypted;
golang加解密
import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/md5" "encoding/base64" "encoding/json" "fmt" ) func PKCS7Padding(ciphertext []byte, blockSize int) []byte { padding := blockSize - len(ciphertext)%blockSize padText := bytes.Repeat([]byte{byte(padding)}, padding) return append(ciphertext, padText...) } func PKCS7UnPadding(origData []byte) []byte { length := len(origData) unpadding := int(origData[length-1]) return origData[:(length - unpadding)] } func AesEncryptCBC(orig string, key, iv string) string { origData := []byte(orig) k := []byte(key) block, _ := aes.NewCipher(k) blockSize := block.BlockSize() origData = PKCS7Padding(origData, blockSize) ivCopy := []byte(iv) blockMode := cipher.NewCBCEncrypter(block, ivCopy[:blockSize]) cryted := make([]byte, len(origData)) blockMode.CryptBlocks(cryted, origData) return base64.StdEncoding.EncodeToString(cryted) } func AesDecryptCBC(cryted string, key, iv string) string { crytedByte, _ := base64.StdEncoding.DecodeString(cryted) k := []byte(key) block, _ := aes.NewCipher(k) blockSize := block.BlockSize() ivCopy := []byte(iv) blockMode := cipher.NewCBCDecrypter(block, ivCopy[:blockSize]) orig := make([]byte, len(crytedByte)) blockMode.CryptBlocks(orig, crytedByte) orig = PKCS7UnPadding(orig) return string(orig) } func main() { key := "yKFdBXEBQSK6wvB4pvnyGgqbPKrCw6Wr" iv := "93mVGaEOAUB22dLb" data := "123456" encrypted := AesEncryptCBC(data, key, iv) fmt.Println(encrypted) decrypted := AesDecryptCBC(encrypted, key, iv) fmt.Println(decrypted) }