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

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