Created
December 21, 2018 08:54
-
-
Save huanghantao/d62eef979af78dfd9f399ab1130098c2 to your computer and use it in GitHub Desktop.
AESUtil
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package AESUtil | |
import ( | |
"bytes" | |
"crypto/aes" | |
"crypto/cipher" | |
"fmt" | |
) | |
func PKCS5Padding(ciphertext []byte, blockSize int) []byte { | |
padding := blockSize - len(ciphertext)%blockSize | |
padtext := bytes.Repeat([]byte{byte(padding)}, padding) | |
return append(ciphertext, padtext...) | |
} | |
func PKCS5Trimming(encrypt []byte) []byte { | |
padding := encrypt[len(encrypt)-1] | |
return encrypt[:len(encrypt)-int(padding)] | |
} | |
func Encrypt(key []byte, text []byte) ([]byte, error) { | |
block, err := aes.NewCipher(key) | |
if err != nil { | |
return nil, err | |
} | |
text = PKCS5Padding(text, aes.BlockSize) | |
ciphertext := make([]byte, len(text)) | |
cbc := cipher.NewCBCEncrypter(block, key) | |
cbc.CryptBlocks(ciphertext, text) | |
return ciphertext, nil | |
} | |
func Decrypt(key []byte, crypt []byte) []byte { | |
block, err := aes.NewCipher(key) | |
if err != nil { | |
fmt.Println("key error1", err) | |
} | |
if len(crypt) == 0 { | |
fmt.Println("plain content empty") | |
} | |
ecb := cipher.NewCBCDecrypter(block, key) | |
decrypted := make([]byte, len(crypt)) | |
ecb.CryptBlocks(decrypted, crypt) | |
return PKCS5Trimming(decrypted) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment