Skip to content

Instantly share code, notes, and snippets.

@awadhwana
Last active April 19, 2024 07:31
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save awadhwana/9c95377beba61293390c5fd23a3bb1df to your computer and use it in GitHub Desktop.
Save awadhwana/9c95377beba61293390c5fd23a3bb1df to your computer and use it in GitHub Desktop.
Golang: aes-256-cbc ecrypt/decrypt examples (with iv, blockSize)
package main
// Working example: https://goplay.space/#Sa7qCLm6w65
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/hex"
"fmt"
)
func main() {
key := "12345678901234567890123456789012"
iv := "1234567890123456"
plaintext := "abcdefghijklmnopqrstuvwxyzABCDEF"
fmt.Println("Data to encode: ", plaintext)
cipherText := fmt.Sprintf("%v", Ase256Encode(plaintext, key, iv, aes.BlockSize))
fmt.Println("Encode Result:\t", cipherText)
fmt.Println("Decode Result:\t", Ase256Decode(cipherText, key, iv))
}
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...)
}
@NotYusta
Copy link

hey, i want to tell u somethin, i tested and messed around, encrypting a text will give u the result with a trailing spaces, so you should use strings.TrimSpace func,

you can see the result here, i've modified and adjusted some func for my project.
https://goplay.space/#lBRpljKVjiY

@NotYusta
Copy link

or maybe you can use this func, it will automatically remove trailing white spaces
https://goplay.space/#ExdbpOHVp-0

@NotYusta
Copy link

@bojcheski
Copy link

bojcheski commented Feb 23, 2022

Hey, I'm kinda new to golang and I also had some trouble with those trailing spaces.... I came with this function thats also a good implementation:

func PKCS5UnPadding(src []byte) []byte {
	length := len(src)
	unpadding := int(src[length-1])
	return src[:(length - unpadding)]
}

Just pass cipherTextDecoded to PKCS5UnPadding

@awadhwana
Copy link
Author

Thanks a lot @bojcheski and @NotYusta for highlighting this.

@NotYusta This https://goplay.space/#F_vCnIbq8wY works as expected.

@vuduongtp
Copy link

vuduongtp commented Jun 15, 2022

Use this function if you gonna encrypt plaintext without padding. It will resolve issue trailing spaces.

func AES256Encode(plaintext string, key string, iv string) string {
	bKey := []byte(key)
	bIV := []byte(iv)
	block, err := aes.NewCipher(bKey)
	if err != nil {
		panic(err)
	}
	ciphertext := make([]byte, len(plaintext))
	mode := cipher.NewCBCEncrypter(block, bIV)
	mode.CryptBlocks(ciphertext, []byte(plaintext))
	return hex.EncodeToString(ciphertext)
}

@daamanshah
Copy link

Do not forget to use PKCS5UnPadding() while decoding the string !!!!!!!!!!!!!!!!

func Ase256(plaintext string, key string, iv string, blockSize int) (string, error) {
    bKey := []byte(key)
    bIV := []byte(iv)
    bPlaintext := PKCS5Padding([]byte(plaintext), blockSize, len(plaintext))
    block, err := aes.NewCipher(bKey)
    if err != nil {
        return "", err
    }
    ciphertext := make([]byte, len(bPlaintext))
    mode := cipher.NewCBCEncrypter(block, bIV)
    mode.CryptBlocks(ciphertext, bPlaintext)
    return hex.EncodeToString(ciphertext), nil
}
func PKCS5UnPadding(src []byte) []byte {
    length := len(src)
    unpadding := int(src[length-1])
    return src[:(length - unpadding)]
}
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...)
}
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(PKCS5UnPadding(cipherTextDecoded))
}

@KC6745
Copy link

KC6745 commented Sep 23, 2022

Hi all
I wanted to encrypt and decrypt using a key of length 43 which I am getting from hashicorp vault

https://goplay.space/#C3TFPoaDmeb

how can I make this work? can you pls suggest

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment