DEV Community

Cover image for Some notes on symmetric encryption in golang

Posted on

Some notes on symmetric encryption in golang

Working today on passing around secure parameters I came across the post
Instead of LibSodium, you should use the nacl/box library that is part of [1]

here is a simple example using the suggested libraries

the encrypt import suggested [1]

Enter fullscreen mode Exit fullscreen mode
func getRandomNonce() ([]byte, [24]byte) {
    iv := make([]byte, 24)
    if _, err := io.ReadFull(rand.Reader, iv); err != nil {
    return iv, [24]byte(iv)

func encryptSecret(plainText []byte) ([]byte, [24]byte) {
    nonce, np := getRandomNonce()
    symKey := [32]byte(secretKeyBytes)
    encrypted := secretbox.Seal(nonce, plainText, &np, &symKey)
    return encrypted, np

func decryptSecret(cypherText []byte, decryptNonce [24]byte) []byte {
    symKey := [32]byte(secretKeyBytes)
    decrypted, ok := secretbox.Open(nil, cypherText[24:], &decryptNonce, &symKey)
    if !ok {
        panic("decryption error")
    return decrypted

Enter fullscreen mode Exit fullscreen mode

and here is a test

func TestSymmEncrypt(t *testing.T) {
    plainText := "this is pop"
    cypherText, decryptNonce := encryptSecret([]byte(plainText))
    hopePlainText := decryptSecret(cypherText, decryptNonce)
Enter fullscreen mode Exit fullscreen mode


  • [1] is a good example of why we cant just cut and paste crypto code and hope for the best, its humbling to see even good cryptographers make mistakes
  • its amazing how often the crypto random source and its use is a basic repeated error in so much code
  • golangs rand.Reader uses getrandom(2)[2], its worth it to read the man page to see its limitations from [2] "entropy pool has been initialized and the request size is large (buflen > 256), the call either succeeds, returning a partially filled buffer" oops!

philosophical notes

  • is the universe deterministic if yes then we should be able to get a truly random source, however for the believers of science there has always been an argument for a non deterministic universe
  • struggling with crypto? => Zen proverb "Hell, also, is a place to live in."

Top comments (1)

vidyarathna profile image
Vidyarathna Bhat • Edited

This post offers a clear and insightful exploration of symmetric encryption in Go, blending technical guidance with philosophical reflections seamlessly. Great work!