Skip to content

Instantly share code, notes, and snippets.

@Alevsk Alevsk/main.go

Created Jul 12, 2020
What would you like to do?
This part of my post "Just enough cryptography for better securing your apps"
package main
import (
func encryptAES_GCM(key []byte, message []byte) string {
block, _ := aes.NewCipher(key)
nonce := make([]byte, 12)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
aesgcm, err := cipher.NewGCM(block)
if err != nil {
ciphertext := aesgcm.Seal(nil, 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)
return base64.StdEncoding.EncodeToString(h.Sum(nil))
func main() {
message := []byte("hello world")
key := []byte("super secret key")
messageHmac := computeHmac256(message, key)
fmt.Println(string(message), messageHmac)
fmt.Println(string(key), deriveKey(key, message))
fmt.Println(string(message), encryptAES_GCM(key, message))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.