Debian Codegraph @

openpgp/x25519/x25519.go

raw
1 package x25519
2
3 import (
4 "crypto/sha256"
5 "crypto/subtle"
6 "io"
7
8 "github.com/ProtonMail/go-crypto/openpgp/aes/keywrap"
9 "github.com/ProtonMail/go-crypto/openpgp/errors"
10 x25519lib "github.com/cloudflare/circl/dh/x25519"
11 "golang.org/x/crypto/hkdf"
12 )
13
14 const (
15 hkdfInfo = "OpenPGP X25519"
16 aes128KeySize = 16
17 // The size of a public or private key in bytes.
18 KeySize = x25519lib.Size
19 )
20
21 type PublicKey struct {
22 // Point represents the encoded elliptic curve point of the public key.
23 Point []byte
24 }
25
26 type PrivateKey struct {
27 PublicKey
28 // Secret represents the secret of the private key.
29 Secret []byte
30 }
31
32 // NewPrivateKey creates a new empty private key including the public key.
33 func NewPrivateKey(key PublicKey) *PrivateKey {
34 return &PrivateKey{
35 PublicKey: key,
36 }
37 }
38
39 // Validate validates that the provided public key matches the private key.
40 func Validate(pk *PrivateKey) (err error) {
41 var expectedPublicKey, privateKey x25519lib.Key
42 subtle.ConstantTimeCopy(1, privateKey[:], pk.Secret)
43 x25519lib.KeyGen(&expectedPublicKey, &privateKey)
44 if subtle.ConstantTimeCompare(expectedPublicKey[:], pk.PublicKey.Point) == 0 {
45 return errors.KeyInvalidError("x25519: invalid key")
46 }
47 return nil
48 }
49
50 // GenerateKey generates a new x25519 key pair.
51 func GenerateKey(rand io.Reader) (*PrivateKey, error) {
52 var privateKey, publicKey x25519lib.Key
53 privateKeyOut := new(PrivateKey)
54 err := generateKey(rand, &privateKey, &publicKey)
55 if err != nil {
56 return nil, err
57 }
58 privateKeyOut.PublicKey.Point = publicKey[:]
59 privateKeyOut.Secret = privateKey[:]
60 return privateKeyOut, nil
61 }
62
63 func generateKey(rand io.Reader, privateKey *x25519lib.Key, publicKey *x25519lib.Key) error {
64 maxRounds := 10
65 isZero := true
66 for round := 0; isZero; round++ {
67 if round == maxRounds {
68 return errors.InvalidArgumentError("x25519: zero keys only, randomness source might be corrupt")
69 }
70 _, err := io.ReadFull(rand, privateKey[:])
71 if err != nil {
72 return err
73 }
74 isZero = constantTimeIsZero(privateKey[:])
75 }
76 x25519lib.KeyGen(publicKey, privateKey)
77 return nil
78 }
79
80 // Encrypt encrypts a sessionKey with x25519 according to
81 // the OpenPGP crypto refresh specification section 5.1.6. The function assumes that the
82 // sessionKey has the correct format and padding according to the specification.
83 func Encrypt(rand io.Reader, publicKey *PublicKey, sessionKey []byte) (ephemeralPublicKey, encryptedSessionKey []byte, err error) {
84 var ephemeralPrivate, ephemeralPublic, staticPublic, shared x25519lib.Key
85 // Check that the input static public key has 32 bytes
86 if len(publicKey.Point) != KeySize {
87 err = errors.KeyInvalidError("x25519: the public key has the wrong size")
88 return
89 }
90 copy(staticPublic[:], publicKey.Point)
91 // Generate ephemeral keyPair
92 err = generateKey(rand, &ephemeralPrivate, &ephemeralPublic)
93 if err != nil {
94 return
95 }
96 // Compute shared key
97 ok := x25519lib.Shared(&shared, &ephemeralPrivate, &staticPublic)
98 if !ok {
99 err = errors.KeyInvalidError("x25519: the public key is a low order point")
100 return
101 }
102 ephemeralPublicKey = ephemeralPublic[:]
103 // Derive the encryption key from the shared secret
104 encryptionKey := applyHKDF(ephemeralPublicKey, publicKey.Point[:], shared[:])
105 // Encrypt the sessionKey with aes key wrapping
106 encryptedSessionKey, err = keywrap.Wrap(encryptionKey, sessionKey)
107 return
108 }
109
110 // Decrypt decrypts a session key stored in ciphertext with the provided x25519
111 // private key and ephemeral public key.
112 func Decrypt(privateKey *PrivateKey, ephemeralPublicKey, ciphertext []byte) (encodedSessionKey []byte, err error) {
113 var ephemeralPublic, staticPrivate, shared x25519lib.Key
114 // Check that the input ephemeral public key has 32 bytes
115 if len(ephemeralPublicKey) != KeySize {
116 err = errors.KeyInvalidError("x25519: the public key has the wrong size")
117 return
118 }
119 copy(ephemeralPublic[:], ephemeralPublicKey)
120 subtle.ConstantTimeCopy(1, staticPrivate[:], privateKey.Secret)
121 // Compute shared key
122 ok := x25519lib.Shared(&shared, &staticPrivate, &ephemeralPublic)
123 if !ok {
124 err = errors.KeyInvalidError("x25519: the ephemeral public key is a low order point")
125 return
126 }
127 // Derive the encryption key from the shared secret
128 encryptionKey := applyHKDF(ephemeralPublicKey, privateKey.PublicKey.Point[:], shared[:])
129 // Decrypt the session key with aes key wrapping
130 encodedSessionKey, err = keywrap.Unwrap(encryptionKey, ciphertext)
131 return
132 }
133
134 func applyHKDF(ephemeralPublicKey []byte, publicKey []byte, sharedSecret []byte) []byte {
135 inputKey := make([]byte, 3*KeySize)
136 // ephemeral public key | recipient public key | shared secret
137 subtle.ConstantTimeCopy(1, inputKey[:KeySize], ephemeralPublicKey)
138 subtle.ConstantTimeCopy(1, inputKey[KeySize:2*KeySize], publicKey)
139 subtle.ConstantTimeCopy(1, inputKey[2*KeySize:], sharedSecret)
140 hkdfReader := hkdf.New(sha256.New, inputKey, []byte{}, []byte(hkdfInfo))
141 encryptionKey := make([]byte, aes128KeySize)
142 _, _ = io.ReadFull(hkdfReader, encryptionKey)
143 return encryptionKey
144 }
145
146 func constantTimeIsZero(bytes []byte) bool {
147 isZero := byte(0)
148 for _, b := range bytes {
149 isZero |= b
150 }
151 return isZero == 0
152 }
153
154 // ENCODING/DECODING ciphertexts:
155
156 // EncodeFieldsLength returns the length of the ciphertext encoding
157 // given the encrypted session key.
158 func EncodedFieldsLength(encryptedSessionKey []byte, v6 bool) int {
159 lenCipherFunction := 0
160 if !v6 {
161 lenCipherFunction = 1
162 }
163 return KeySize + 1 + len(encryptedSessionKey) + lenCipherFunction
164 }
165
166 // EncodeField encodes x25519 session key encryption fields as
167 // ephemeral x25519 public key | follow byte length | cipherFunction (v3 only) | encryptedSessionKey
168 // and writes it to writer.
169 func EncodeFields(writer io.Writer, ephemeralPublicKey, encryptedSessionKey []byte, cipherFunction byte, v6 bool) (err error) {
170 lenAlgorithm := 0
171 if !v6 {
172 lenAlgorithm = 1
173 }
174 if _, err = writer.Write(ephemeralPublicKey); err != nil {
175 return err
176 }
177 if _, err = writer.Write([]byte{byte(len(encryptedSessionKey) + lenAlgorithm)}); err != nil {
178 return err
179 }
180 if !v6 {
181 if _, err = writer.Write([]byte{cipherFunction}); err != nil {
182 return err
183 }
184 }
185 _, err = writer.Write(encryptedSessionKey)
186 return err
187 }
188
189 // DecodeField decodes a x25519 session key encryption as
190 // ephemeral x25519 public key | follow byte length | cipherFunction (v3 only) | encryptedSessionKey.
191 func DecodeFields(reader io.Reader, v6 bool) (ephemeralPublicKey, encryptedSessionKey []byte, cipherFunction byte, err error) {
192 var buf [1]byte
193 ephemeralPublicKey = make([]byte, KeySize)
194 // 32 octets representing an ephemeral x25519 public key.
195 if _, err = io.ReadFull(reader, ephemeralPublicKey); err != nil {
196 return nil, nil, 0, err
197 }
198 // A one-octet size of the following fields.
199 if _, err = io.ReadFull(reader, buf[:]); err != nil {
200 return nil, nil, 0, err
201 }
202 followingLen := buf[0]
203 // The one-octet algorithm identifier, if it was passed (in the case of a v3 PKESK packet).
204 if !v6 {
205 if _, err = io.ReadFull(reader, buf[:]); err != nil {
206 return nil, nil, 0, err
207 }
208 cipherFunction = buf[0]
209 followingLen -= 1
210 }
211 // The encrypted session key.
212 encryptedSessionKey = make([]byte, followingLen)
213 if _, err = io.ReadFull(reader, encryptedSessionKey); err != nil {
214 return nil, nil, 0, err
215 }
216 return ephemeralPublicKey, encryptedSessionKey, cipherFunction, nil
217 }