example_test.go 1.4 KB

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