Skip to content

Instantly share code, notes, and snippets.

@shollingsworth
Created June 26, 2022 18:04
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 shollingsworth/8bbcbd6088973acef9ada3063e1f8b47 to your computer and use it in GitHub Desktop.
Save shollingsworth/8bbcbd6088973acef9ada3063e1f8b47 to your computer and use it in GitHub Desktop.
example of using golang box to encrypt / decrypt
package crypt
import (
crypto_rand "crypto/rand"
"encoding/hex"
"io"
"golang.org/x/crypto/nacl/box"
)
func GenerateKey() (string, string) {
publicKey, privateKey, err := box.GenerateKey(crypto_rand.Reader)
if err != nil {
panic(err)
}
return hex.EncodeToString(publicKey[:]), hex.EncodeToString(privateKey[:])
}
func Encrypt(publicKey [32]byte, privateKey [32]byte, message []byte) []byte {
var nonce [24]byte
if _, err := io.ReadFull(crypto_rand.Reader, nonce[:]); err != nil {
panic(err)
}
encrypted := box.Seal(nonce[:], message, &nonce, &publicKey, &privateKey)
return encrypted
}
func Decrypt(publicKey [32]byte, privateKey [32]byte, encrypted []byte) []byte {
var nonce [24]byte
copy(nonce[:], encrypted[:24])
decrypted, ok := box.Open(nil, encrypted[24:], &nonce, &publicKey, &privateKey)
if !ok {
panic("decryption failed")
}
return decrypted
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment