base64:
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"fmt"
)
func AESEncrypt(src string, key []byte, iv string) string {
block, err := aes.NewCipher(key)
if err != nil {
fmt.Println("key error1", err)
}
if src == "" {
fmt.Println("plain content empty")
}
ecb := cipher.NewCBCEncrypter(block, []byte(iv))
content := []byte(src)
content = PKCS5Padding(content, block.BlockSize())
crypted := make([]byte, len(content))
ecb.CryptBlocks(crypted, content)
return base64.StdEncoding.EncodeToString(crypted)
}
func AESDecrypt(cryptedStr string, key []byte, iv string) []byte {
encryptedData, _ := base64.StdEncoding.DecodeString(cryptedStr)
block, err := aes.NewCipher(key)
if err != nil {
fmt.Println("key error1", err)
}
if len(encryptedData) == 0 {
fmt.Println("plain content empty")
}
ecb := cipher.NewCBCDecrypter(block, []byte(iv))
decrypted := make([]byte, len(encryptedData))
ecb.CryptBlocks(decrypted, encryptedData)
return PKCS5Trimming(decrypted)
}
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)]
}
hex:
func Ase256Encode(plaintext string, key string, iv string, blockSize int) string {
bKey := []byte(key)
bIV := []byte(iv)
bPlaintext := PKCS5Padding([]byte(plaintext), blockSize, len(plaintext))
block, err := aes.NewCipher(bKey)
if err != nil {
panic(err)
}
ciphertext := make([]byte, len(bPlaintext))
mode := cipher.NewCBCEncrypter(block, bIV)
mode.CryptBlocks(ciphertext, bPlaintext)
return hex.EncodeToString(ciphertext)
}
func Ase256Decode(cipherText string, encKey string, iv string) (decryptedString string) {
bKey := []byte(encKey)
bIV := []byte(iv)
cipherTextDecoded, err := hex.DecodeString(cipherText)
if err != nil {
panic(err)
}
block, err := aes.NewCipher(bKey)
if err != nil {
panic(err)
}
mode := cipher.NewCBCDecrypter(block, bIV)
mode.CryptBlocks([]byte(cipherTextDecoded), []byte(cipherTextDecoded))
return string(cipherTextDecoded)
}
func PKCS5Padding(ciphertext []byte, blockSize int, after int) []byte {
padding := (blockSize - len(ciphertext)%blockSize)
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}