12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- package encrypt
- import (
- "bytes"
- "crypto/aes"
- "crypto/cipher"
- "encoding/hex"
- )
- func pkcs7Padding(ciphertext []byte, blockSize int) []byte {
- padding := blockSize - len(ciphertext)%blockSize
- padtext := bytes.Repeat([]byte{byte(0)}, padding)
- return append(ciphertext, padtext...)
- }
- func pkcs7UnPadding(ciphertext []byte, blockSize int) []byte {
- padding := blockSize - len(ciphertext)%blockSize
- padtext := bytes.Repeat([]byte{0}, padding)
- return append(ciphertext, padtext...)
- }
- func AesCBCEncrypt(rawData, key []byte) ([]byte, error) {
- block, err := aes.NewCipher(key)
- if err != nil {
- panic(err)
- }
-
- blockSize := block.BlockSize()
- rawData = pkcs7Padding(rawData, blockSize)
- cipherText := make([]byte, len(rawData))
-
- mode := cipher.NewCBCEncrypter(block, key)
- mode.CryptBlocks(cipherText, rawData)
- return cipherText, nil
- }
- func AesCBCDecrypt(encryptData, key []byte) ([]byte, error) {
- block, err := aes.NewCipher(key)
- if err != nil {
- panic(err)
- }
- blockSize := block.BlockSize()
- if len(encryptData) < blockSize {
- panic("ciphertext too short")
- }
-
- if len(encryptData)%blockSize != 0 {
- panic("ciphertext is not a multiple of the block size")
- }
- mode := cipher.NewCBCDecrypter(block, key)
-
- mode.CryptBlocks(encryptData, encryptData)
-
- encryptData = pkcs7UnPadding(encryptData, blockSize)
- return encryptData, nil
- }
- func Encrypt(rawData, key []byte) (string, error) {
- data, err := AesCBCEncrypt(rawData, key)
- if err != nil {
- return "", err
- }
- encryptData := hex.EncodeToString(data)
- return encryptData, nil
- }
- func Decrypt(rawData string, key []byte) (string, error) {
- data, err := hex.DecodeString(rawData)
- if err != nil {
- return "", err
- }
- dnData, err := AesCBCDecrypt(data, key)
- if err != nil {
- return "", err
- }
- return string(dnData), nil
- }
|