123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- package aes
- import (
- cryptoAes "crypto/aes"
- "crypto/cipher"
- "encoding/base64"
- )
- var _ Aes = (*aes)(nil)
- type Aes interface {
- i()
- EncryptCBC(encryptStr string, urlEncode bool) (string, error)
- DecryptCBC(decryptStr string, urlEncode bool) (string, error)
- EncryptCFB(plain string, urlEncode bool) (string, error)
- DecryptCFB(encrypted string, urlEncode bool) (string, error)
- }
- type aes struct {
- key string
- iv string
- }
- func New(key, iv string) Aes {
- return &aes{
- key: key,
- iv: iv,
- }
- }
- func (a *aes) i() {}
- func (a *aes) EncryptCBC(encryptStr string, urlEncode bool) (string, error) {
- encoder := base64.StdEncoding
- if urlEncode {
- encoder = base64.URLEncoding
- }
- encryptBytes := []byte(encryptStr)
- block, err := cryptoAes.NewCipher([]byte(a.key))
- if err != nil {
- return "", err
- }
- blockSize := block.BlockSize()
- encryptBytes = pkcsPadding(encryptBytes, blockSize)
- blockMode := cipher.NewCBCEncrypter(block, []byte(a.iv))
- encrypted := make([]byte, len(encryptBytes))
- blockMode.CryptBlocks(encrypted, encryptBytes)
- return encoder.EncodeToString(encrypted), nil
- }
- func (a *aes) DecryptCBC(decryptStr string, urlEncode bool) (string, error) {
- encoder := base64.StdEncoding
- if urlEncode {
- encoder = base64.URLEncoding
- }
- decryptBytes, err := encoder.DecodeString(decryptStr)
- if err != nil {
- return "", err
- }
- block, err := cryptoAes.NewCipher([]byte(a.key))
- if err != nil {
- return "", err
- }
- blockMode := cipher.NewCBCDecrypter(block, []byte(a.iv))
- decrypted := make([]byte, len(decryptBytes))
- blockMode.CryptBlocks(decrypted, decryptBytes)
- decrypted = pkcsUnPadding(decrypted)
- return string(decrypted), nil
- }
- func (a *aes) EncryptCFB(plain string, urlEncode bool) (string, error) {
- encoder := base64.StdEncoding
- if urlEncode {
- encoder = base64.URLEncoding
- }
- block, err := cryptoAes.NewCipher([]byte(a.key))
- if err != nil {
- return "", err
- }
- encrypted := make([]byte, len(plain))
- stream := cipher.NewCFBEncrypter(block, []byte(a.iv))
- stream.XORKeyStream(encrypted, []byte(plain))
- return encoder.EncodeToString(encrypted), nil
- }
- func (a *aes) DecryptCFB(encrypted string, urlEncode bool) (string, error) {
- encoder := base64.StdEncoding
- if urlEncode {
- encoder = base64.URLEncoding
- }
- decryptBytes, err := encoder.DecodeString(encrypted)
- if err != nil {
- return "", err
- }
- block, err := cryptoAes.NewCipher([]byte(a.key))
- if err != nil {
- return "", err
- }
- plain := make([]byte, len(decryptBytes))
- stream := cipher.NewCFBDecrypter(block, []byte(a.iv))
- stream.XORKeyStream(plain, decryptBytes)
- return string(plain), nil
- }
|