|
| 1 | +package crypt |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/rand" |
| 5 | + "fmt" |
| 6 | + |
| 7 | + "golang.org/x/crypto/chacha20poly1305" |
| 8 | +) |
| 9 | + |
| 10 | +// EncryptChacha20poly1305 encrypts and authenticates the given message with |
| 11 | +// ChaCha20-Poly1305 AEAD using the given 256-bit key. |
| 12 | +func EncryptChacha20poly1305(key []byte, text string) (ciphertext []byte, nonce []byte, err error) { |
| 13 | + // create a new ChaCha20-Poly1305 AEAD using the given 256-bit key |
| 14 | + aead, err := chacha20poly1305.New(key) |
| 15 | + if err != nil { |
| 16 | + err = fmt.Errorf("error creating AEAD: %v", err) |
| 17 | + return |
| 18 | + } |
| 19 | + |
| 20 | + // generate a 96-bit random nonce |
| 21 | + nonce = make([]byte, aead.NonceSize()) |
| 22 | + _, err = rand.Read(nonce) |
| 23 | + if err != nil { |
| 24 | + err = fmt.Errorf("error generating nonce: %v", err) |
| 25 | + return |
| 26 | + } |
| 27 | + |
| 28 | + // data to be encrypted |
| 29 | + data := []byte(text) |
| 30 | + |
| 31 | + // encrypt the data |
| 32 | + ciphertext = aead.Seal(nil, nonce, data, nil) |
| 33 | + |
| 34 | + return |
| 35 | +} |
| 36 | + |
| 37 | +// DecryptChacha20poly1305 decrypts and authenticates the given message with |
| 38 | +// ChaCha20-Poly1305 AEAD using the given 256-bit key and 96-bit nonce. |
| 39 | +func DecryptChacha20poly1305(key, nonce, ciphertext []byte) (text string, err error) { |
| 40 | + // create a new ChaCha20-Poly1305 AEAD using the given 256-bit key |
| 41 | + aead, err := chacha20poly1305.New(key) |
| 42 | + if err != nil { |
| 43 | + err = fmt.Errorf("error creating AEAD: %v", err) |
| 44 | + return |
| 45 | + } |
| 46 | + |
| 47 | + // decrypt the data |
| 48 | + plaintext, err := aead.Open(nil, nonce, ciphertext, nil) |
| 49 | + if err != nil { |
| 50 | + err = fmt.Errorf("error decrypting data: %v", err) |
| 51 | + return |
| 52 | + } |
| 53 | + text = string(plaintext) |
| 54 | + |
| 55 | + return |
| 56 | +} |
0 commit comments