This is part of my post "Just enough cryptography for better securing your apps"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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