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