12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- package main
- import (
- "crypto/rand"
- "fmt"
- "golang.org/x/crypto/nacl/box"
- )
- func maina() {
- senderPublicKey, senderPrivateKey, err := box.GenerateKey(rand.Reader)
- if err != nil {
- panic(err)
- }
- recipientPublicKey, recipientPrivateKey, err := box.GenerateKey(rand.Reader)
- if err != nil {
- panic(err)
- }
- // 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
- _, err = rand.Read(nonce[:])
- if err != nil {
- panic(err)
- }
- msg := []byte("Fucking finally")
- // This encrypts msg and appends the result to the nonce.
- encrypted := box.Seal(nonce[:], msg, &nonce, recipientPublicKey, senderPrivateKey)
- // The recipient can decrypt the message using their private key and the
- // sender's public key. When you decrypt, you must use the same nonce 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 := box.Open(nil, encrypted[24:], &decryptNonce, senderPublicKey, recipientPrivateKey)
- if !ok {
- panic("decryption error")
- }
- fmt.Println(string(decrypted))
- }
|