Skip to content

Instantly share code, notes, and snippets.

@goliatone
Forked from mickelsonm/main.go
Created October 16, 2021 04:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goliatone/0cf03fa9220f9313a90ba8412b51a29c to your computer and use it in GitHub Desktop.
Save goliatone/0cf03fa9220f9313a90ba8412b51a29c to your computer and use it in GitHub Desktop.
Golang AES Encryption/Decryption example. See running example: http://play.golang.org/p/5G-IUlYqQV
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"io"
"log"
)
func main() {
CIPHER_KEY := []byte("0123456789012345")
msg := "A quick brown fox jumped over the lazy dog."
if encrypted, err := encrypt(CIPHER_KEY, msg); err != nil {
log.Println(err)
} else {
log.Printf("CIPHER KEY: %s\n", string(CIPHER_KEY))
log.Printf("ENCRYPTED: %s\n", encrypted)
if decrypted, err := decrypt(CIPHER_KEY, encrypted); err != nil {
log.Println(err)
} else {
log.Printf("DECRYPTED: %s\n", decrypted)
}
}
}
func encrypt(key []byte, message string) (encmess string, err error) {
plainText := []byte(message)
block, err := aes.NewCipher(key)
if err != nil {
return
}
//IV needs to be unique, but doesn't have to be secure.
//It's common to put it at the beginning of the ciphertext.
cipherText := make([]byte, aes.BlockSize+len(plainText))
iv := cipherText[:aes.BlockSize]
if _, err = io.ReadFull(rand.Reader, iv); err != nil {
return
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(cipherText[aes.BlockSize:], plainText)
//returns to base64 encoded string
encmess = base64.URLEncoding.EncodeToString(cipherText)
return
}
func decrypt(key []byte, securemess string) (decodedmess string, err error) {
cipherText, err := base64.URLEncoding.DecodeString(securemess)
if err != nil {
return
}
block, err := aes.NewCipher(key)
if err != nil {
return
}
if len(cipherText) < aes.BlockSize {
err = errors.New("Ciphertext block size is too short!")
return
}
//IV needs to be unique, but doesn't have to be secure.
//It's common to put it at the beginning of the ciphertext.
iv := cipherText[:aes.BlockSize]
cipherText = cipherText[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
// XORKeyStream can work in-place if the two arguments are the same.
stream.XORKeyStream(cipherText, cipherText)
decodedmess = string(cipherText)
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment