Skip to content

Instantly share code, notes, and snippets.

@stupidbodo
Last active January 3, 2024 10:29
Show Gist options
  • Star 78 You must be signed in to star a gist
  • Fork 23 You must be signed in to fork a gist
  • Save stupidbodo/601b68bfef3449d1b8d9 to your computer and use it in GitHub Desktop.
Save stupidbodo/601b68bfef3449d1b8d9 to your computer and use it in GitHub Desktop.
AES Encryption Example in Golang
// Playbook - http://play.golang.org/p/3wFl4lacjX
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"io"
"strings"
)
func addBase64Padding(value string) string {
m := len(value) % 4
if m != 0 {
value += strings.Repeat("=", 4-m)
}
return value
}
func removeBase64Padding(value string) string {
return strings.Replace(value, "=", "", -1)
}
func Pad(src []byte) []byte {
padding := aes.BlockSize - len(src)%aes.BlockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(src, padtext...)
}
func Unpad(src []byte) ([]byte, error) {
length := len(src)
unpadding := int(src[length-1])
if unpadding > length {
return nil, errors.New("unpad error. This could happen when incorrect encryption key is used")
}
return src[:(length - unpadding)], nil
}
func encrypt(key []byte, text string) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
msg := Pad([]byte(text))
ciphertext := make([]byte, aes.BlockSize+len(msg))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
cfb := cipher.NewCFBEncrypter(block, iv)
cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(msg))
finalMsg := removeBase64Padding(base64.URLEncoding.EncodeToString(ciphertext))
return finalMsg, nil
}
func decrypt(key []byte, text string) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
decodedMsg, err := base64.URLEncoding.DecodeString(addBase64Padding(text))
if err != nil {
return "", err
}
if (len(decodedMsg) % aes.BlockSize) != 0 {
return "", errors.New("blocksize must be multipe of decoded message length")
}
iv := decodedMsg[:aes.BlockSize]
msg := decodedMsg[aes.BlockSize:]
cfb := cipher.NewCFBDecrypter(block, iv)
cfb.XORKeyStream(msg, msg)
unpadMsg, err := Unpad(msg)
if err != nil {
return "", err
}
return string(unpadMsg), nil
}
func main() {
key := []byte("LKHlhb899Y09olUi")
encryptMsg, _ := encrypt(key, "Hello World")
msg, _ := decrypt(key, encryptMsg)
fmt.Println(msg) // Hello World
}
@thylong
Copy link

thylong commented Feb 23, 2017

https://gist.github.com/stupidbodo/601b68bfef3449d1b8d9#file-aes_encryption-go-L78
typo: multiple

Thanks for the snippet dude, works like a charm 👍

@zyfdegh
Copy link

zyfdegh commented Nov 1, 2017

Good job, solved my problem, thanks

@jordan-patterson
Copy link

Thanks for sharing

@nicholascc
Copy link

Hey, I'm working on a project and want to use this snippet.

Could you add a license to the code, because I don't think I can use it without it.

Thanks, this is great!

@Adrien-Luxey
Copy link

So what's the fuss with adding/removing '=' characters?

Thanks anyway, I really did not want to dive into using the bare Go stl functions...

@luanngominh
Copy link

Thank you so much!

@madushadhanushka
Copy link

Thank you. It work nice for me 👍

@JoveYu
Copy link

JoveYu commented Mar 12, 2019

this is pkcs7 padding

Copy link

ghost commented Apr 6, 2019

nice work bro!

now i m tyring to make some encryption tool use your code,

when i finish this work, i will share my work :)

@davidelena
Copy link

Thank you for sharing and your answer helps me a lot

@MAGANER
Copy link

MAGANER commented Feb 14, 2021

but how to generate a key?

@LangPham
Copy link

Thank you!

@Stef16Robbe
Copy link

Thanks a lot!

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