package utils import ( "bytes" "errors" "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "io" ) // 签名字符串生成 // CBC 模式 // 加密 // // 使用PKCS7进行填充,IOS也是7 func PKCS7Padding(ciphertext []byte, blockSize int) []byte { padding := blockSize - len(ciphertext)%blockSize // 需要填充的数目 // 只要少于256就能放到一个byte中,默认的blockSize=16(即采用16*8=128, AES-128长的密钥) // 最少填充1个byte,如果原文刚好是blocksize的整数倍,则再填充一个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)] } // aes加密,填充秘钥key的16位,24,32分别对应AES-128, AES-192, or AES-256. func AesCBCEncrypt(rawData, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } // 填充原文 blockSize := block.BlockSize() rawData = PKCS7Padding(rawData, blockSize) // 初始向量IV必须是唯一,但不需要保密 cipherText := make([]byte, blockSize+len(rawData)) // block大小 16 //iv := cipherText[:blockSize] iv := key[:16] if _, err := io.ReadFull(rand.Reader, iv); err != nil { return nil, err } // block大小和初始向量大小一定要一致 mode := cipher.NewCBCEncrypter(block, iv) mode.CryptBlocks(cipherText[blockSize:], rawData) return cipherText, nil } // 解密 func AesCBCDncrypt(encryptData, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } blockSize := block.BlockSize() if len(encryptData) < blockSize { return nil, errors.New("ciphertext too short") } //iv := encryptData[:blockSize] iv := key[:16] encryptData = encryptData[blockSize:] if len(encryptData)%blockSize != 0 { return nil, errors.New("ciphertext is not a multiple of the block size") } mode := cipher.NewCBCDecrypter(block, iv) mode.CryptBlocks(encryptData, encryptData) // 解填充 encryptData = PKCS7UnPadding(encryptData) return encryptData, nil } func ProvincialEncrypt(rawData, key []byte) (string, error) { data, err := AesCBCEncrypt(rawData, key) if err != nil { return "", err } return base64.StdEncoding.EncodeToString(data), nil } func ProvincialDecrypt(rawData string, key []byte) (string, error) { data, err := base64.StdEncoding.DecodeString(rawData) if err != nil { return "", err } dnData, err := AesCBCDncrypt(data, key) if err != nil { return "", err } return string(dnData), nil }