123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157 |
- 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
- }
|