| 1 | // Copyright 2019 The age Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package age |
| 6 | |
| 7 | import ( |
| 8 | "crypto/hmac" |
| 9 | "crypto/sha256" |
| 10 | "errors" |
| 11 | "io" |
| 12 | |
| 13 | "filippo.io/age/internal/format" |
| 14 | "golang.org/x/crypto/chacha20poly1305" |
| 15 | "golang.org/x/crypto/hkdf" |
| 16 | ) |
| 17 | |
| 18 | // aeadEncrypt encrypts a message with a one-time key. |
| 19 | func aeadEncrypt(key, plaintext []byte) ([]byte, error) { |
| 20 | aead, err := chacha20poly1305.New(key) |
| 21 | if err != nil { |
| 22 | return nil, err |
| 23 | } |
| 24 | // The nonce is fixed because this function is only used in places where the |
| 25 | // spec guarantees each key is only used once (by deriving it from values |
| 26 | // that include fresh randomness), allowing us to save the overhead. |
| 27 | // For the code that encrypts the actual payload, look at the |
| 28 | // filippo.io/age/internal/stream package. |
| 29 | nonce := make([]byte, chacha20poly1305.NonceSize) |
| 30 | return aead.Seal(nil, nonce, plaintext, nil), nil |
| 31 | } |
| 32 | |
| 33 | var errIncorrectCiphertextSize = errors.New("encrypted value has unexpected length") |
| 34 | |
| 35 | // aeadDecrypt decrypts a message of an expected fixed size. |
| 36 | // |
| 37 | // The message size is limited to mitigate multi-key attacks, where a ciphertext |
| 38 | // can be crafted that decrypts successfully under multiple keys. Short |
| 39 | // ciphertexts can only target two keys, which has limited impact. |
| 40 | func aeadDecrypt(key []byte, size int, ciphertext []byte) ([]byte, error) { |
| 41 | aead, err := chacha20poly1305.New(key) |
| 42 | if err != nil { |
| 43 | return nil, err |
| 44 | } |
| 45 | if len(ciphertext) != size+aead.Overhead() { |
| 46 | return nil, errIncorrectCiphertextSize |
| 47 | } |
| 48 | nonce := make([]byte, chacha20poly1305.NonceSize) |
| 49 | return aead.Open(nil, nonce, ciphertext, nil) |
| 50 | } |
| 51 | |
| 52 | func headerMAC(fileKey []byte, hdr *format.Header) ([]byte, error) { |
| 53 | h := hkdf.New(sha256.New, fileKey, nil, []byte("header")) |
| 54 | hmacKey := make([]byte, 32) |
| 55 | if _, err := io.ReadFull(h, hmacKey); err != nil { |
| 56 | return nil, err |
| 57 | } |
| 58 | hh := hmac.New(sha256.New, hmacKey) |
| 59 | if err := hdr.MarshalWithoutMAC(hh); err != nil { |
| 60 | return nil, err |
| 61 | } |
| 62 | return hh.Sum(nil), nil |
| 63 | } |
| 64 | |
| 65 | func streamKey(fileKey, nonce []byte) []byte { |
| 66 | h := hkdf.New(sha256.New, fileKey, nonce, []byte("payload")) |
| 67 | streamKey := make([]byte, chacha20poly1305.KeySize) |
| 68 | if _, err := io.ReadFull(h, streamKey); err != nil { |
| 69 | panic("age: internal error: failed to read from HKDF: " + err.Error()) |
| 70 | } |
| 71 | return streamKey |
| 72 | } |