box.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package main
  2. import (
  3. "crypto/rand"
  4. "fmt"
  5. "golang.org/x/crypto/nacl/box"
  6. )
  7. func maina() {
  8. senderPublicKey, senderPrivateKey, err := box.GenerateKey(rand.Reader)
  9. if err != nil {
  10. panic(err)
  11. }
  12. recipientPublicKey, recipientPrivateKey, err := box.GenerateKey(rand.Reader)
  13. if err != nil {
  14. panic(err)
  15. }
  16. // You must use a different nonce for each message you encrypt with the
  17. // same key. Since the nonce here is 192 bits long, a random value
  18. // provides a sufficiently small probability of repeats.
  19. var nonce [24]byte
  20. _, err = rand.Read(nonce[:])
  21. if err != nil {
  22. panic(err)
  23. }
  24. msg := []byte("Fucking finally")
  25. // This encrypts msg and appends the result to the nonce.
  26. encrypted := box.Seal(nonce[:], msg, &nonce, recipientPublicKey, senderPrivateKey)
  27. // The recipient can decrypt the message using their private key and the
  28. // sender's public key. When you decrypt, you must use the same nonce you
  29. // used to encrypt the message. One way to achieve this is to store the
  30. // nonce alongside the encrypted message. Above, we stored the nonce in the
  31. // first 24 bytes of the encrypted text.
  32. var decryptNonce [24]byte
  33. copy(decryptNonce[:], encrypted[:24])
  34. decrypted, ok := box.Open(nil, encrypted[24:], &decryptNonce, senderPublicKey, recipientPrivateKey)
  35. if !ok {
  36. panic("decryption error")
  37. }
  38. fmt.Println(string(decrypted))
  39. }