1 // Copyright 2016 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
13 "golang.org/x/crypto/nacl/secretbox"
17 // Load your secret key from a safe place and reuse it across multiple
18 // Seal calls. (Obviously don't use this example key for anything
19 // real.) If you want to convert a passphrase to a key, use a suitable
20 // package like bcrypt or scrypt.
21 secretKeyBytes, err := hex.DecodeString("6368616e676520746869732070617373776f726420746f206120736563726574")
26 var secretKey [32]byte
27 copy(secretKey[:], secretKeyBytes)
29 // You must use a different nonce for each message you encrypt with the
30 // same key. Since the nonce here is 192 bits long, a random value
31 // provides a sufficiently small probability of repeats.
33 if _, err := io.ReadFull(rand.Reader, nonce[:]); err != nil {
37 // This encrypts "hello world" and appends the result to the nonce.
38 encrypted := secretbox.Seal(nonce[:], []byte("hello world"), &nonce, &secretKey)
40 // When you decrypt, you must use the same nonce and key you used to
41 // encrypt the message. One way to achieve this is to store the nonce
42 // alongside the encrypted message. Above, we stored the nonce in the first
43 // 24 bytes of the encrypted text.
44 var decryptNonce [24]byte
45 copy(decryptNonce[:], encrypted[:24])
46 decrypted, ok := secretbox.Open(nil, encrypted[24:], &decryptNonce, &secretKey)
48 panic("decryption error")
51 fmt.Println(string(decrypted))
52 // Output: hello world