Skip to content

Instantly share code, notes, and snippets.

@pocoz
Forked from hothero/aes_cbc_pkcs5.go
Created April 10, 2019 11:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pocoz/33187561a73e9cb0e5ec768577ef05ef to your computer and use it in GitHub Desktop.
Save pocoz/33187561a73e9cb0e5ec768577ef05ef to your computer and use it in GitHub Desktop.
AES/CBC/PKCS5Padding implementation by Golang (can work with JAVA, C#, etc.)
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"fmt"
)
var (
initialVector = "1234567890123456"
passphrase = "Impassphrasegood"
)
func main() {
var plainText = "hello world"
encryptedData := AESEncrypt(plainText, []byte(passphrase))
encryptedString := base64.StdEncoding.EncodeToString(encryptedData)
fmt.Println(encryptedString)
encryptedData, _ = base64.StdEncoding.DecodeString(encryptedString)
decryptedText := AESDecrypt(encryptedData, []byte(passphrase))
fmt.Println(string(decryptedText))
}
func AESEncrypt(src string, key []byte) []byte {
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(initialVector))
content := []byte(src)
content = PKCS5Padding(content, block.BlockSize())
crypted := make([]byte, len(content))
ecb.CryptBlocks(crypted, content)
return crypted
}
func AESDecrypt(crypt []byte, key []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, []byte(initialVector))
decrypted := make([]byte, len(crypt))
ecb.CryptBlocks(decrypted, crypt)
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)]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment