podman
427 строк · 12.7 Кб
1package libtrust
2
3import (
4"crypto"
5"crypto/rand"
6"crypto/rsa"
7"crypto/x509"
8"encoding/json"
9"encoding/pem"
10"errors"
11"fmt"
12"io"
13"math/big"
14)
15
16/*
17* RSA DSA PUBLIC KEY
18*/
19
20// rsaPublicKey implements a JWK Public Key using RSA digital signature algorithms.
21type rsaPublicKey struct {
22*rsa.PublicKey
23extended map[string]interface{}
24}
25
26func fromRSAPublicKey(cryptoPublicKey *rsa.PublicKey) *rsaPublicKey {
27return &rsaPublicKey{cryptoPublicKey, map[string]interface{}{}}
28}
29
30// KeyType returns the JWK key type for RSA keys, i.e., "RSA".
31func (k *rsaPublicKey) KeyType() string {
32return "RSA"
33}
34
35// KeyID returns a distinct identifier which is unique to this Public Key.
36func (k *rsaPublicKey) KeyID() string {
37return keyIDFromCryptoKey(k)
38}
39
40func (k *rsaPublicKey) String() string {
41return fmt.Sprintf("RSA Public Key <%s>", k.KeyID())
42}
43
44// Verify verifyies the signature of the data in the io.Reader using this Public Key.
45// The alg parameter should be the name of the JWA digital signature algorithm
46// which was used to produce the signature and should be supported by this
47// public key. Returns a nil error if the signature is valid.
48func (k *rsaPublicKey) Verify(data io.Reader, alg string, signature []byte) error {
49// Verify the signature of the given date, return non-nil error if valid.
50sigAlg, err := rsaSignatureAlgorithmByName(alg)
51if err != nil {
52return fmt.Errorf("unable to verify Signature: %s", err)
53}
54
55hasher := sigAlg.HashID().New()
56_, err = io.Copy(hasher, data)
57if err != nil {
58return fmt.Errorf("error reading data to sign: %s", err)
59}
60hash := hasher.Sum(nil)
61
62err = rsa.VerifyPKCS1v15(k.PublicKey, sigAlg.HashID(), hash, signature)
63if err != nil {
64return fmt.Errorf("invalid %s signature: %s", sigAlg.HeaderParam(), err)
65}
66
67return nil
68}
69
70// CryptoPublicKey returns the internal object which can be used as a
71// crypto.PublicKey for use with other standard library operations. The type
72// is either *rsa.PublicKey or *ecdsa.PublicKey
73func (k *rsaPublicKey) CryptoPublicKey() crypto.PublicKey {
74return k.PublicKey
75}
76
77func (k *rsaPublicKey) toMap() map[string]interface{} {
78jwk := make(map[string]interface{})
79for k, v := range k.extended {
80jwk[k] = v
81}
82jwk["kty"] = k.KeyType()
83jwk["kid"] = k.KeyID()
84jwk["n"] = joseBase64UrlEncode(k.N.Bytes())
85jwk["e"] = joseBase64UrlEncode(serializeRSAPublicExponentParam(k.E))
86
87return jwk
88}
89
90// MarshalJSON serializes this Public Key using the JWK JSON serialization format for
91// RSA keys.
92func (k *rsaPublicKey) MarshalJSON() (data []byte, err error) {
93return json.Marshal(k.toMap())
94}
95
96// PEMBlock serializes this Public Key to DER-encoded PKIX format.
97func (k *rsaPublicKey) PEMBlock() (*pem.Block, error) {
98derBytes, err := x509.MarshalPKIXPublicKey(k.PublicKey)
99if err != nil {
100return nil, fmt.Errorf("unable to serialize RSA PublicKey to DER-encoded PKIX format: %s", err)
101}
102k.extended["kid"] = k.KeyID() // For display purposes.
103return createPemBlock("PUBLIC KEY", derBytes, k.extended)
104}
105
106func (k *rsaPublicKey) AddExtendedField(field string, value interface{}) {
107k.extended[field] = value
108}
109
110func (k *rsaPublicKey) GetExtendedField(field string) interface{} {
111v, ok := k.extended[field]
112if !ok {
113return nil
114}
115return v
116}
117
118func rsaPublicKeyFromMap(jwk map[string]interface{}) (*rsaPublicKey, error) {
119// JWK key type (kty) has already been determined to be "RSA".
120// Need to extract 'n', 'e', and 'kid' and check for
121// consistency.
122
123// Get the modulus parameter N.
124nB64Url, err := stringFromMap(jwk, "n")
125if err != nil {
126return nil, fmt.Errorf("JWK RSA Public Key modulus: %s", err)
127}
128
129n, err := parseRSAModulusParam(nB64Url)
130if err != nil {
131return nil, fmt.Errorf("JWK RSA Public Key modulus: %s", err)
132}
133
134// Get the public exponent E.
135eB64Url, err := stringFromMap(jwk, "e")
136if err != nil {
137return nil, fmt.Errorf("JWK RSA Public Key exponent: %s", err)
138}
139
140e, err := parseRSAPublicExponentParam(eB64Url)
141if err != nil {
142return nil, fmt.Errorf("JWK RSA Public Key exponent: %s", err)
143}
144
145key := &rsaPublicKey{
146PublicKey: &rsa.PublicKey{N: n, E: e},
147}
148
149// Key ID is optional, but if it exists, it should match the key.
150_, ok := jwk["kid"]
151if ok {
152kid, err := stringFromMap(jwk, "kid")
153if err != nil {
154return nil, fmt.Errorf("JWK RSA Public Key ID: %s", err)
155}
156if kid != key.KeyID() {
157return nil, fmt.Errorf("JWK RSA Public Key ID does not match: %s", kid)
158}
159}
160
161if _, ok := jwk["d"]; ok {
162return nil, fmt.Errorf("JWK RSA Public Key cannot contain private exponent")
163}
164
165key.extended = jwk
166
167return key, nil
168}
169
170/*
171* RSA DSA PRIVATE KEY
172*/
173
174// rsaPrivateKey implements a JWK Private Key using RSA digital signature algorithms.
175type rsaPrivateKey struct {
176rsaPublicKey
177*rsa.PrivateKey
178}
179
180func fromRSAPrivateKey(cryptoPrivateKey *rsa.PrivateKey) *rsaPrivateKey {
181return &rsaPrivateKey{
182*fromRSAPublicKey(&cryptoPrivateKey.PublicKey),
183cryptoPrivateKey,
184}
185}
186
187// PublicKey returns the Public Key data associated with this Private Key.
188func (k *rsaPrivateKey) PublicKey() PublicKey {
189return &k.rsaPublicKey
190}
191
192func (k *rsaPrivateKey) String() string {
193return fmt.Sprintf("RSA Private Key <%s>", k.KeyID())
194}
195
196// Sign signs the data read from the io.Reader using a signature algorithm supported
197// by the RSA private key. If the specified hashing algorithm is supported by
198// this key, that hash function is used to generate the signature otherwise the
199// the default hashing algorithm for this key is used. Returns the signature
200// and the name of the JWK signature algorithm used, e.g., "RS256", "RS384",
201// "RS512".
202func (k *rsaPrivateKey) Sign(data io.Reader, hashID crypto.Hash) (signature []byte, alg string, err error) {
203// Generate a signature of the data using the internal alg.
204sigAlg := rsaPKCS1v15SignatureAlgorithmForHashID(hashID)
205hasher := sigAlg.HashID().New()
206
207_, err = io.Copy(hasher, data)
208if err != nil {
209return nil, "", fmt.Errorf("error reading data to sign: %s", err)
210}
211hash := hasher.Sum(nil)
212
213signature, err = rsa.SignPKCS1v15(rand.Reader, k.PrivateKey, sigAlg.HashID(), hash)
214if err != nil {
215return nil, "", fmt.Errorf("error producing signature: %s", err)
216}
217
218alg = sigAlg.HeaderParam()
219
220return
221}
222
223// CryptoPrivateKey returns the internal object which can be used as a
224// crypto.PublicKey for use with other standard library operations. The type
225// is either *rsa.PublicKey or *ecdsa.PublicKey
226func (k *rsaPrivateKey) CryptoPrivateKey() crypto.PrivateKey {
227return k.PrivateKey
228}
229
230func (k *rsaPrivateKey) toMap() map[string]interface{} {
231k.Precompute() // Make sure the precomputed values are stored.
232jwk := k.rsaPublicKey.toMap()
233
234jwk["d"] = joseBase64UrlEncode(k.D.Bytes())
235jwk["p"] = joseBase64UrlEncode(k.Primes[0].Bytes())
236jwk["q"] = joseBase64UrlEncode(k.Primes[1].Bytes())
237jwk["dp"] = joseBase64UrlEncode(k.Precomputed.Dp.Bytes())
238jwk["dq"] = joseBase64UrlEncode(k.Precomputed.Dq.Bytes())
239jwk["qi"] = joseBase64UrlEncode(k.Precomputed.Qinv.Bytes())
240
241otherPrimes := k.Primes[2:]
242
243if len(otherPrimes) > 0 {
244otherPrimesInfo := make([]interface{}, len(otherPrimes))
245for i, r := range otherPrimes {
246otherPrimeInfo := make(map[string]string, 3)
247otherPrimeInfo["r"] = joseBase64UrlEncode(r.Bytes())
248crtVal := k.Precomputed.CRTValues[i]
249otherPrimeInfo["d"] = joseBase64UrlEncode(crtVal.Exp.Bytes())
250otherPrimeInfo["t"] = joseBase64UrlEncode(crtVal.Coeff.Bytes())
251otherPrimesInfo[i] = otherPrimeInfo
252}
253jwk["oth"] = otherPrimesInfo
254}
255
256return jwk
257}
258
259// MarshalJSON serializes this Private Key using the JWK JSON serialization format for
260// RSA keys.
261func (k *rsaPrivateKey) MarshalJSON() (data []byte, err error) {
262return json.Marshal(k.toMap())
263}
264
265// PEMBlock serializes this Private Key to DER-encoded PKIX format.
266func (k *rsaPrivateKey) PEMBlock() (*pem.Block, error) {
267derBytes := x509.MarshalPKCS1PrivateKey(k.PrivateKey)
268k.extended["keyID"] = k.KeyID() // For display purposes.
269return createPemBlock("RSA PRIVATE KEY", derBytes, k.extended)
270}
271
272func rsaPrivateKeyFromMap(jwk map[string]interface{}) (*rsaPrivateKey, error) {
273// The JWA spec for RSA Private Keys (draft rfc section 5.3.2) states that
274// only the private key exponent 'd' is REQUIRED, the others are just for
275// signature/decryption optimizations and SHOULD be included when the JWK
276// is produced. We MAY choose to accept a JWK which only includes 'd', but
277// we're going to go ahead and not choose to accept it without the extra
278// fields. Only the 'oth' field will be optional (for multi-prime keys).
279privateExponent, err := parseRSAPrivateKeyParamFromMap(jwk, "d")
280if err != nil {
281return nil, fmt.Errorf("JWK RSA Private Key exponent: %s", err)
282}
283firstPrimeFactor, err := parseRSAPrivateKeyParamFromMap(jwk, "p")
284if err != nil {
285return nil, fmt.Errorf("JWK RSA Private Key prime factor: %s", err)
286}
287secondPrimeFactor, err := parseRSAPrivateKeyParamFromMap(jwk, "q")
288if err != nil {
289return nil, fmt.Errorf("JWK RSA Private Key prime factor: %s", err)
290}
291firstFactorCRT, err := parseRSAPrivateKeyParamFromMap(jwk, "dp")
292if err != nil {
293return nil, fmt.Errorf("JWK RSA Private Key CRT exponent: %s", err)
294}
295secondFactorCRT, err := parseRSAPrivateKeyParamFromMap(jwk, "dq")
296if err != nil {
297return nil, fmt.Errorf("JWK RSA Private Key CRT exponent: %s", err)
298}
299crtCoeff, err := parseRSAPrivateKeyParamFromMap(jwk, "qi")
300if err != nil {
301return nil, fmt.Errorf("JWK RSA Private Key CRT coefficient: %s", err)
302}
303
304var oth interface{}
305if _, ok := jwk["oth"]; ok {
306oth = jwk["oth"]
307delete(jwk, "oth")
308}
309
310// JWK key type (kty) has already been determined to be "RSA".
311// Need to extract the public key information, then extract the private
312// key values.
313publicKey, err := rsaPublicKeyFromMap(jwk)
314if err != nil {
315return nil, err
316}
317
318privateKey := &rsa.PrivateKey{
319PublicKey: *publicKey.PublicKey,
320D: privateExponent,
321Primes: []*big.Int{firstPrimeFactor, secondPrimeFactor},
322Precomputed: rsa.PrecomputedValues{
323Dp: firstFactorCRT,
324Dq: secondFactorCRT,
325Qinv: crtCoeff,
326},
327}
328
329if oth != nil {
330// Should be an array of more JSON objects.
331otherPrimesInfo, ok := oth.([]interface{})
332if !ok {
333return nil, errors.New("JWK RSA Private Key: Invalid other primes info: must be an array")
334}
335numOtherPrimeFactors := len(otherPrimesInfo)
336if numOtherPrimeFactors == 0 {
337return nil, errors.New("JWK RSA Privake Key: Invalid other primes info: must be absent or non-empty")
338}
339otherPrimeFactors := make([]*big.Int, numOtherPrimeFactors)
340productOfPrimes := new(big.Int).Mul(firstPrimeFactor, secondPrimeFactor)
341crtValues := make([]rsa.CRTValue, numOtherPrimeFactors)
342
343for i, val := range otherPrimesInfo {
344otherPrimeinfo, ok := val.(map[string]interface{})
345if !ok {
346return nil, errors.New("JWK RSA Private Key: Invalid other prime info: must be a JSON object")
347}
348
349otherPrimeFactor, err := parseRSAPrivateKeyParamFromMap(otherPrimeinfo, "r")
350if err != nil {
351return nil, fmt.Errorf("JWK RSA Private Key prime factor: %s", err)
352}
353otherFactorCRT, err := parseRSAPrivateKeyParamFromMap(otherPrimeinfo, "d")
354if err != nil {
355return nil, fmt.Errorf("JWK RSA Private Key CRT exponent: %s", err)
356}
357otherCrtCoeff, err := parseRSAPrivateKeyParamFromMap(otherPrimeinfo, "t")
358if err != nil {
359return nil, fmt.Errorf("JWK RSA Private Key CRT coefficient: %s", err)
360}
361
362crtValue := crtValues[i]
363crtValue.Exp = otherFactorCRT
364crtValue.Coeff = otherCrtCoeff
365crtValue.R = productOfPrimes
366otherPrimeFactors[i] = otherPrimeFactor
367productOfPrimes = new(big.Int).Mul(productOfPrimes, otherPrimeFactor)
368}
369
370privateKey.Primes = append(privateKey.Primes, otherPrimeFactors...)
371privateKey.Precomputed.CRTValues = crtValues
372}
373
374key := &rsaPrivateKey{
375rsaPublicKey: *publicKey,
376PrivateKey: privateKey,
377}
378
379return key, nil
380}
381
382/*
383* Key Generation Functions.
384*/
385
386func generateRSAPrivateKey(bits int) (k *rsaPrivateKey, err error) {
387k = new(rsaPrivateKey)
388k.PrivateKey, err = rsa.GenerateKey(rand.Reader, bits)
389if err != nil {
390return nil, err
391}
392
393k.rsaPublicKey.PublicKey = &k.PrivateKey.PublicKey
394k.extended = make(map[string]interface{})
395
396return
397}
398
399// GenerateRSA2048PrivateKey generates a key pair using 2048-bit RSA.
400func GenerateRSA2048PrivateKey() (PrivateKey, error) {
401k, err := generateRSAPrivateKey(2048)
402if err != nil {
403return nil, fmt.Errorf("error generating RSA 2048-bit key: %s", err)
404}
405
406return k, nil
407}
408
409// GenerateRSA3072PrivateKey generates a key pair using 3072-bit RSA.
410func GenerateRSA3072PrivateKey() (PrivateKey, error) {
411k, err := generateRSAPrivateKey(3072)
412if err != nil {
413return nil, fmt.Errorf("error generating RSA 3072-bit key: %s", err)
414}
415
416return k, nil
417}
418
419// GenerateRSA4096PrivateKey generates a key pair using 4096-bit RSA.
420func GenerateRSA4096PrivateKey() (PrivateKey, error) {
421k, err := generateRSAPrivateKey(4096)
422if err != nil {
423return nil, fmt.Errorf("error generating RSA 4096-bit key: %s", err)
424}
425
426return k, nil
427}
428