example_test.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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.
  4. package secretbox_test
  5. import (
  6. "crypto/rand"
  7. "encoding/hex"
  8. "fmt"
  9. "io"
  10. "golang.org/x/crypto/nacl/secretbox"
  11. )
  12. func Example() {
  13. // Load your secret key from a safe place and reuse it across multiple
  14. // Seal calls. (Obviously don't use this example key for anything
  15. // real.) If you want to convert a passphrase to a key, use a suitable
  16. // package like bcrypt or scrypt.
  17. secretKeyBytes, err := hex.DecodeString("6368616e676520746869732070617373776f726420746f206120736563726574")
  18. if err != nil {
  19. panic(err)
  20. }
  21. var secretKey [32]byte
  22. copy(secretKey[:], secretKeyBytes)
  23. // You must use a different nonce for each message you encrypt with the
  24. // same key. Since the nonce here is 192 bits long, a random value
  25. // provides a sufficiently small probability of repeats.
  26. var nonce [24]byte
  27. if _, err := io.ReadFull(rand.Reader, nonce[:]); err != nil {
  28. panic(err)
  29. }
  30. // This encrypts "hello world" and appends the result to the nonce.
  31. encrypted := secretbox.Seal(nonce[:], []byte("hello world"), &nonce, &secretKey)
  32. // When you decrypt, you must use the same nonce and key you used to
  33. // encrypt the message. One way to achieve this is to store the nonce
  34. // alongside the encrypted message. Above, we stored the nonce in the first
  35. // 24 bytes of the encrypted text.
  36. var decryptNonce [24]byte
  37. copy(decryptNonce[:], encrypted[:24])
  38. decrypted, ok := secretbox.Open([]byte{}, encrypted[24:], &decryptNonce, &secretKey)
  39. if !ok {
  40. panic("decryption error")
  41. }
  42. fmt.Println(string(decrypted))
  43. // Output: hello world
  44. }