Skip to content

Instantly share code, notes, and snippets.

@Alevsk
Last active December 31, 2021 03:44
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 Alevsk/0c296f230279bd399a244d4f7d1d7b84 to your computer and use it in GitHub Desktop.
Save Alevsk/0c296f230279bd399a244d4f7d1d7b84 to your computer and use it in GitHub Desktop.
This is part of my post "Just enough cryptography for better securing your apps"
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/sha1"
"crypto/sha256"
"encoding/base64"
"fmt"
"io"
"golang.org/x/crypto/pbkdf2"
)
func decryptAESGCM(key []byte, data []byte) string {
block, err := aes.NewCipher(key)
if err != nil {
return err.Error()
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return err.Error()
}
nonceSize := gcm.NonceSize()
nonce, cipherText := data[:nonceSize], data[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, cipherText, nil)
if err != nil {
return err.Error()
}
return string(plaintext)
}
func encryptAESGCM(key []byte, message []byte) string {
block, _ := aes.NewCipher(key)
nonce := make([]byte, 12)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
ciphertext := aesgcm.Seal(nonce, nonce, message, nil)
return base64.StdEncoding.EncodeToString(ciphertext)
}
func deriveKey(key []byte, salt []byte) string {
derivedKey := pbkdf2.Key(key, salt, 4096, 32, sha1.New)
return base64.StdEncoding.EncodeToString(derivedKey)
}
func computeHmac256(message []byte, key []byte) string {
h := hmac.New(sha256.New, key)
h.Write(message)
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
func main() {
message := []byte("hello world")
key := []byte("super secret key")
messageHmac := computeHmac256(message, []byte("cryptographic key"))
fmt.Println(string(message), messageHmac)
fmt.Println(string(key), deriveKey(key, []byte("E1F53135E559C253")))
cipherText := encryptAESGCM(key, message)
fmt.Println(string(message), cipherText)
data, _ := base64.StdEncoding.DecodeString(cipherText)
fmt.Println(cipherText, decryptAESGCM(key, data))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment