aboutsummaryrefslogtreecommitdiff
path: root/nacl
diff options
context:
space:
mode:
authorKevin Burke <kev@inburke.com>2016-08-10 20:25:16 -0700
committerAdam Langley <agl@golang.org>2016-08-16 17:48:58 +0000
commit1ce41b6ca7dccc03377edf55652ffa334b6c06ce (patch)
tree6dc29a1ecff930eea52e6e8e5958f572f513a44f /nacl
parent807ffeae6d033a871e83d8ffa61d51bf75288066 (diff)
downloadgo-x-crypto-1ce41b6ca7dccc03377edf55652ffa334b6c06ce.tar.xz
nacl/secretbox: add Seal, Open example
I read the docs and wasn't sure how to use the package - what is the best way to generate a nonce? Do I need to use the same nonce for encrypting and decrypting the same message? I read through some code that used this package, and the tests, found the answers I was looking for, and used them to generate an example, which hopefully will be helpful to other users of this package. Change-Id: I24f9682fecb6632f34b4d8d13fed6eb002993677 Reviewed-on: https://go-review.googlesource.com/26810 Reviewed-by: Adam Langley <agl@golang.org>
Diffstat (limited to 'nacl')
-rw-r--r--nacl/secretbox/example_test.go47
1 files changed, 47 insertions, 0 deletions
diff --git a/nacl/secretbox/example_test.go b/nacl/secretbox/example_test.go
new file mode 100644
index 0000000..fc7482a
--- /dev/null
+++ b/nacl/secretbox/example_test.go
@@ -0,0 +1,47 @@
+package secretbox
+
+import (
+ "crypto/rand"
+ "encoding/hex"
+ "fmt"
+ "io"
+)
+
+func Example() {
+ // Load your secret key from a safe place and reuse it across multiple
+ // Seal calls. (Obviously don't use this example key for anything
+ // real.) If you want to convert a passphrase to a key, use a suitable
+ // package like bcrypt or scrypt.
+ secretKeyBytes, err := hex.DecodeString("6368616e676520746869732070617373776f726420746f206120736563726574")
+ if err != nil {
+ panic(err)
+ }
+
+ var secretKey [32]byte
+ copy(secretKey[:], secretKeyBytes)
+
+ // You must use a different nonce for each message you encrypt with the
+ // same key. Since the nonce here is 192 bits long, a random value
+ // provides a sufficiently small probability of repeats.
+ var nonce [24]byte
+ if _, err := io.ReadFull(rand.Reader, nonce[:]); err != nil {
+ panic(err)
+ }
+
+ // This encrypts "hello world" and appends the result to the nonce.
+ encrypted := Seal(nonce[:], []byte("hello world"), &nonce, &secretKey)
+
+ // When you decrypt, you must use the same nonce and key you used to
+ // encrypt the message. One way to achieve this is to store the nonce
+ // alongside the encrypted message. Above, we stored the nonce in the first
+ // 24 bytes of the encrypted text.
+ var decryptNonce [24]byte
+ copy(decryptNonce[:], encrypted[:24])
+ decrypted, ok := Open([]byte{}, encrypted[24:], &decryptNonce, &secretKey)
+ if !ok {
+ panic("decryption error")
+ }
+
+ fmt.Println(string(decrypted))
+ // Output: hello world
+}