package utils import ( "bytes" "crypto/cipher" "encoding/base64" "encoding/hex" "strings" ) const ( KEY_LENGTH = 8 ) func encrypt(block cipher.Block, src, key, iv []byte) []byte { blockSize := block.BlockSize() src = pkcs5Padding(src, blockSize) mode := cipher.NewCBCEncrypter(block, genBytes(iv, blockSize)) crypted := make([]byte, len(src)) mode.CryptBlocks(crypted, src) return crypted } func decrypt(block cipher.Block, encrypted, key, iv []byte) []byte { mode := cipher.NewCBCDecrypter(block, genBytes(iv, block.BlockSize())) src := make([]byte, len(encrypted)) mode.CryptBlocks(src, encrypted) return pkcs5UnPadding(src) } func pkcs5Padding(data []byte, blockSize int) []byte { padding := blockSize - len(data)%blockSize padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(data, padtext...) } func pkcs5UnPadding(data []byte) []byte { length := len(data) // 去掉最后一个字节 unpadding 次 unpadding := int(data[length-1]) return data[:(length - unpadding)] } func genBytes(originalBytes []byte, length int) []byte { tmp := make([]byte, length) if len(originalBytes) < length { for i := 0; i < length; i++ { tmp[i] = originalBytes[i%len(originalBytes)] } } else { for i := 0; i < length; i++ { tmp[i] = originalBytes[i] } } return tmp } func bytes2String(data []byte, base64Encoding bool) string { if base64Encoding { return base64.StdEncoding.EncodeToString(data) } else { return strings.ToUpper(hex.EncodeToString(data)) } } func string2Bytes(data string, base64Encoding bool) ([]byte, error) { var tmp []byte var err error if base64Encoding { tmp, err = base64.StdEncoding.DecodeString(data) } else { tmp, err = hex.DecodeString(data) } return tmp, err }