1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| package util import ( "bytes" basicAES "crypto/aes" "crypto/cipher" "encoding/base64" ) type Aes struct { securityKey []byte iv []byte }
func AesTool() *Aes { return &Aes{[]byte("123"), []byte("123")} }
func (a Aes) Encrypt(plainText string) (string, error) { block, err := basicAES.NewCipher(a.securityKey) if err != nil { return "", err } plainTextByte := []byte(plainText) blockSize := block.BlockSize() plainTextByte = AddPKCS7Padding(plainTextByte, blockSize) cipherText := make([]byte, len(plainTextByte)) mode := cipher.NewCBCEncrypter(block, a.iv) mode.CryptBlocks(cipherText, plainTextByte) return base64.StdEncoding.EncodeToString(cipherText), nil }
func (a Aes) Decrypt(cipherText string) (string, error) { block, err := basicAES.NewCipher(a.securityKey) if err != nil { return "", err } cipherDecodeText, decodeErr := base64.StdEncoding.DecodeString(cipherText) if decodeErr != nil { return "", decodeErr } mode := cipher.NewCBCDecrypter(block, a.iv) originCipherText := make([]byte, len(cipherDecodeText)) mode.CryptBlocks(originCipherText, cipherDecodeText) originCipherText = StripPKSC7Padding(originCipherText) return string(originCipherText), nil }
func AddPKCS7Padding(ciphertext []byte, blockSize int) []byte { padding := blockSize - len(ciphertext)%blockSize paddingText := bytes.Repeat([]byte{byte(padding)}, padding) return append(ciphertext, paddingText...) }
func StripPKSC7Padding(cipherText []byte) []byte { length := len(cipherText) unpadding := int(cipherText[length-1]) return cipherText[:(length - unpadding)] }
|