123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- package utils
- import (
- "bytes"
- "crypto/cipher"
- "encoding/base64"
- "encoding/hex"
- "strings"
- )
- const (
- KeyLength = 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))
- encrypted := make([]byte, len(src))
- mode.CryptBlocks(encrypted, src)
- return encrypted
- }
- 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
- }
|