github.com/TeaOSLab/EdgeNode@v1.3.8/internal/encrypt/method_aes_256_cfb.go (about)

     1  package encrypt
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/aes"
     6  	"crypto/cipher"
     7  )
     8  
     9  type AES256CFBMethod struct {
    10  	block cipher.Block
    11  	iv    []byte
    12  }
    13  
    14  func (this *AES256CFBMethod) Init(key, iv []byte) error {
    15  	// 判断key是否为32长度
    16  	l := len(key)
    17  	if l > 32 {
    18  		key = key[:32]
    19  	} else if l < 32 {
    20  		key = append(key, bytes.Repeat([]byte{' '}, 32-l)...)
    21  	}
    22  
    23  	block, err := aes.NewCipher(key)
    24  	if err != nil {
    25  		return err
    26  	}
    27  	this.block = block
    28  
    29  	// 判断iv长度
    30  	l2 := len(iv)
    31  	if l2 > aes.BlockSize {
    32  		iv = iv[:aes.BlockSize]
    33  	} else if l2 < aes.BlockSize {
    34  		iv = append(iv, bytes.Repeat([]byte{' '}, aes.BlockSize-l2)...)
    35  	}
    36  	this.iv = iv
    37  
    38  	return nil
    39  }
    40  
    41  func (this *AES256CFBMethod) Encrypt(src []byte) (dst []byte, err error) {
    42  	if len(src) == 0 {
    43  		return
    44  	}
    45  
    46  	defer func() {
    47  		err = RecoverMethodPanic(recover())
    48  	}()
    49  
    50  	dst = make([]byte, len(src))
    51  
    52  	encrypter := cipher.NewCFBEncrypter(this.block, this.iv)
    53  	encrypter.XORKeyStream(dst, src)
    54  
    55  	return
    56  }
    57  
    58  func (this *AES256CFBMethod) Decrypt(dst []byte) (src []byte, err error) {
    59  	if len(dst) == 0 {
    60  		return
    61  	}
    62  
    63  	defer func() {
    64  		err = RecoverMethodPanic(recover())
    65  	}()
    66  
    67  	src = make([]byte, len(dst))
    68  	decrypter := cipher.NewCFBDecrypter(this.block, this.iv)
    69  	decrypter.XORKeyStream(src, dst)
    70  
    71  	return
    72  }