Debian Codegraph @

openpgp/x448/x448.go

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