Skip to content

Instantly share code, notes, and snippets.

@shamsher31
Last active December 1, 2023 12:22
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save shamsher31/72dcf05c3cc82b146e965e2ff976af45 to your computer and use it in GitHub Desktop.
Save shamsher31/72dcf05c3cc82b146e965e2ff976af45 to your computer and use it in GitHub Desktop.
Golang Encrypt Decrypt
// Refrence http://stackoverflow.com/questions/18817336/golang-encrypting-a-string-with-aes-and-base64
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"io"
"log"
)
func main() {
key := []byte("a very very very very secret key") // 32 bytes
plaintext := []byte("some really really really long plaintext")
fmt.Printf("%s\n", plaintext)
ciphertext, err := encrypt(key, plaintext)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%0x\n", ciphertext)
result, err := decrypt(key, ciphertext)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", result)
}
// See alternate IV creation from ciphertext below
//var iv = []byte{35, 46, 57, 24, 85, 35, 24, 74, 87, 35, 88, 98, 66, 32, 14, 05}
func encrypt(key, text []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
b := base64.StdEncoding.EncodeToString(text)
ciphertext := make([]byte, aes.BlockSize+len(b))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
cfb := cipher.NewCFBEncrypter(block, iv)
cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
return ciphertext, nil
}
func decrypt(key, text []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(text) < aes.BlockSize {
return nil, errors.New("ciphertext too short")
}
iv := text[:aes.BlockSize]
text = text[aes.BlockSize:]
cfb := cipher.NewCFBDecrypter(block, iv)
cfb.XORKeyStream(text, text)
data, err := base64.StdEncoding.DecodeString(string(text))
if err != nil {
return nil, err
}
return data, nil
}
@pastasciutta
Copy link

How can I use this code to decrypt a password previously crypted and stored somewhere?

@xeoncross
Copy link

This has no Authentication (HMAC) so is not safe. It is recommended to use GCM if your whole plaintext fits into memory (as shown above).

@cesarmarinhorj
Copy link

thanks!!! works!!!
each time we call the function, it generates a different cipher text.
great!!!
8)

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