Created
June 26, 2022 18:04
-
-
Save shollingsworth/8bbcbd6088973acef9ada3063e1f8b47 to your computer and use it in GitHub Desktop.
example of using golang box to encrypt / decrypt
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 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