DEV Community

Discussion on: Secret Key Encryption with Go using AES

Collapse
 
rida profile image
Rida F'kih • Edited

You should be programmatically generating the nonce (not nounce) for each encryption. It’s vital that the nonce is cryptographically random generated, and hard-coding it in your example might get the wrong message across.

It’s always best to use well-known solutions unless you are an actual cryptography expert, libsodium is great for a lot of cryptographic utilities including what you’re trying to do in this post and argon2 is great for salting & hashing.

Collapse
 
breda profile image
Bouchaala Reda • Edited

Absolutely. For the sake of keeping the code example simple I opted to just hardcode the nonce, but you're right the nonce is critical for the encryption/decryption and should never be hardcoded. I updated the code example to randomly generate it.

Some libraries don't even give you the ability to pass a nonce when encrypting, they're generated internally.

Thanks for taking the time to write your feedback! Appreciated.

Collapse
 
nigel447 profile image
nigel447

thanks for pointing this out, crypto posts are always problematic as so many people just copy and paste evidenced by so many examples of code in production using insecure random, below is a simple example for a random nonce
iv := make([]byte, aes.BlockSize)
io.ReadFull(rand.Reader, iv)

the above Reader is a cryptographically secure random number generator, on linux it uses getrandom(2)