Decrypt decrypts the given ciphertext using the PeerDBEncKey.
(ciphertext []byte)
| 58 | |
| 59 | // Decrypt decrypts the given ciphertext using the PeerDBEncKey. |
| 60 | func (key PeerDBEncKey) Decrypt(ciphertext []byte) ([]byte, error) { |
| 61 | if key.ID == "" { |
| 62 | return ciphertext, nil |
| 63 | } |
| 64 | |
| 65 | decodedKey, err := base64.StdEncoding.DecodeString(key.Value) |
| 66 | if err != nil { |
| 67 | return nil, fmt.Errorf("failed to decode base64 key: %w", err) |
| 68 | } |
| 69 | |
| 70 | if len(decodedKey) != 32 { |
| 71 | return nil, fmt.Errorf("invalid key length, must be 32 bytes") |
| 72 | } |
| 73 | |
| 74 | if len(ciphertext) < nonceSize { |
| 75 | return nil, fmt.Errorf("ciphertext too short") |
| 76 | } |
| 77 | |
| 78 | nonce := ciphertext[:nonceSize] |
| 79 | ciphertext = ciphertext[nonceSize:] |
| 80 | |
| 81 | aead, err := chacha20poly1305.NewX(decodedKey) |
| 82 | if err != nil { |
| 83 | return nil, fmt.Errorf("failed to create ChaCha20-Poly1305: %w", err) |
| 84 | } |
| 85 | |
| 86 | plaintext, err := aead.Open(nil, nonce, ciphertext, nil) |
| 87 | if err != nil { |
| 88 | return nil, fmt.Errorf("failed to decrypt: %w", err) |
| 89 | } |
| 90 | |
| 91 | return plaintext, nil |
| 92 | } |
| 93 | |
| 94 | // Encrypt encrypts the given plaintext using the PeerDBEncKey. |
| 95 | func (key PeerDBEncKey) Encrypt(plaintext []byte) ([]byte, error) { |
no outgoing calls
no test coverage detected