Debian Codegraph @

crypto/pemutil/pkcs8.go

raw symbols SCIP
1 package pemutil
2
3 import (
4 "crypto/aes"
5 "crypto/cipher"
6 "crypto/des"
7 "crypto/ecdsa"
8 "crypto/ed25519"
9 "crypto/rsa"
10 "crypto/sha1"
11 "crypto/sha256"
12 "crypto/x509"
13 "crypto/x509/pkix"
14 "encoding/asn1"
15 "encoding/pem"
16 "hash"
17 "io"
18
19 "github.com/pkg/errors"
20 "golang.org/x/crypto/pbkdf2"
21 )
22
23 // PBKDF2SaltSize is the default size of the salt for PBKDF2, 128-bit salt.
24 const PBKDF2SaltSize = 16
25
26 // PBKDF2Iterations is the default number of iterations for PBKDF2, 100k
27 // iterations. Nist recommends at least 10k, 1Passsword uses 100k.
28 const PBKDF2Iterations = 100000
29
30 // pkcs8 reflects an ASN.1, PKCS#8 PrivateKey. See
31 // ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-8/pkcs-8v1_2.asn
32 // and RFC 5208.
33 type pkcs8 struct {
34 Version int
35 Algo pkix.AlgorithmIdentifier
36 PrivateKey []byte
37 // optional attributes omitted.
38 }
39
40 type publicKeyInfo struct {
41 Raw asn1.RawContent
42 Algo pkix.AlgorithmIdentifier
43 PublicKey asn1.BitString
44 }
45
46 // Encrypted pkcs8
47 // Based on https://github.com/youmark/pkcs8
48 // MIT license
49 type prfParam struct {
50 Algo asn1.ObjectIdentifier
51 NullParam asn1.RawValue
52 }
53
54 type pbkdf2Params struct {
55 Salt []byte
56 IterationCount int
57 PrfParam prfParam `asn1:"optional"`
58 }
59
60 type pbkdf2Algorithms struct {
61 Algo asn1.ObjectIdentifier
62 PBKDF2Params pbkdf2Params
63 }
64
65 type pbkdf2Encs struct {
66 EncryAlgo asn1.ObjectIdentifier
67 IV []byte
68 }
69
70 type pbes2Params struct {
71 KeyDerivationFunc pbkdf2Algorithms
72 EncryptionScheme pbkdf2Encs
73 }
74
75 type encryptedlAlgorithmIdentifier struct {
76 Algorithm asn1.ObjectIdentifier
77 Parameters pbes2Params
78 }
79
80 type encryptedPrivateKeyInfo struct {
81 Algo encryptedlAlgorithmIdentifier
82 PrivateKey []byte
83 }
84
85 // Algorithm Identifiers for Ed25519, Ed448, X25519 and X448 for use in the
86 // Internet X.509 Public Key Infrastructure
87 // https://tools.ietf.org/html/draft-ietf-curdle-pkix-10
88 var (
89 // oidX25519 = asn1.ObjectIdentifier{1, 3, 101, 110}
90 oidEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
91
92 // key derivation functions
93 oidPKCS5PBKDF2 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 5, 12}
94 oidPBES2 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 5, 13}
95 oidHMACWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 113549, 2, 9}
96
97 // encryption
98 oidAES128CBC = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 1, 2}
99 oidAES196CBC = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 1, 22}
100 oidAES256CBC = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 1, 42}
101 oidDESCBC = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 7}
102 oidD3DESCBC = asn1.ObjectIdentifier{1, 2, 840, 113549, 3, 7}
103 )
104
105 // rfc1423Algo holds a method for enciphering a PEM block.
106 type rfc1423Algo struct {
107 cipher x509.PEMCipher
108 name string
109 cipherFunc func(key []byte) (cipher.Block, error)
110 keySize int
111 blockSize int
112 identifier asn1.ObjectIdentifier
113 }
114
115 // rfc1423Algos holds a slice of the possible ways to encrypt a PEM
116 // block. The ivSize numbers were taken from the OpenSSL source.
117 var rfc1423Algos = []rfc1423Algo{{
118 cipher: x509.PEMCipherDES,
119 name: "DES-CBC",
120 cipherFunc: des.NewCipher,
121 keySize: 8,
122 blockSize: des.BlockSize,
123 identifier: oidDESCBC,
124 }, {
125 cipher: x509.PEMCipher3DES,
126 name: "DES-EDE3-CBC",
127 cipherFunc: des.NewTripleDESCipher,
128 keySize: 24,
129 blockSize: des.BlockSize,
130 identifier: oidD3DESCBC,
131 }, {
132 cipher: x509.PEMCipherAES128,
133 name: "AES-128-CBC",
134 cipherFunc: aes.NewCipher,
135 keySize: 16,
136 blockSize: aes.BlockSize,
137 identifier: oidAES128CBC,
138 }, {
139 cipher: x509.PEMCipherAES192,
140 name: "AES-192-CBC",
141 cipherFunc: aes.NewCipher,
142 keySize: 24,
143 blockSize: aes.BlockSize,
144 identifier: oidAES196CBC,
145 }, {
146 cipher: x509.PEMCipherAES256,
147 name: "AES-256-CBC",
148 cipherFunc: aes.NewCipher,
149 keySize: 32,
150 blockSize: aes.BlockSize,
151 identifier: oidAES256CBC,
152 },
153 }
154
155 func cipherByKey(key x509.PEMCipher) *rfc1423Algo {
156 for i := range rfc1423Algos {
157 alg := &rfc1423Algos[i]
158 if alg.cipher == key {
159 return alg
160 }
161 }
162 return nil
163 }
164
165 // deriveKey uses a key derivation function to stretch the password into a key
166 // with the number of bits our cipher requires. This algorithm was derived from
167 // the OpenSSL source.
168 func (c rfc1423Algo) deriveKey(password, salt []byte, h func() hash.Hash) []byte {
169 return pbkdf2.Key(password, salt, PBKDF2Iterations, c.keySize, h)
170 }
171
172 // ParsePKCS8PrivateKey parses an unencrypted, PKCS#8 private key. See RFC
173 // 5208.
174 //
175 // Supported key types include RSA, ECDSA, and Ed25519. Unknown key types
176 // result in an error.
177 //
178 // On success, key will be of type *rsa.PrivateKey, *ecdsa.PublicKey, or
179 // ed25519.PrivateKey.
180 func ParsePKCS8PrivateKey(der []byte) (key interface{}, err error) {
181 var privKey pkcs8
182 if _, err := asn1.Unmarshal(der, &privKey); err != nil {
183 return nil, err
184 }
185
186 switch {
187 case privKey.Algo.Algorithm.Equal(oidEd25519):
188 seed := make([]byte, ed25519.SeedSize)
189 copy(seed, privKey.PrivateKey[2:])
190 key = ed25519.NewKeyFromSeed(seed)
191 return key, nil
192 // Proof of concept for key agreement algorithm X25519.
193 // A real implementation would use their own types.
194 //
195 // case privKey.Algo.Algorithm.Equal(oidX25519):
196 // k := make([]byte, ed25519.PrivateKeySize)
197 // var pub, priv [32]byte
198 // copy(priv[:], privKey.PrivateKey[2:])
199 // curve25519.ScalarBaseMult(&pub, &priv)
200 // copy(k, priv[:])
201 // copy(k[32:], pub[:])
202 // key = ed25519.PrivateKey(k)
203 // return key, nil
204 default:
205 return x509.ParsePKCS8PrivateKey(der)
206 }
207 }
208
209 // ParsePKIXPublicKey parses a DER encoded public key. These values are
210 // typically found in PEM blocks with "BEGIN PUBLIC KEY".
211 //
212 // Supported key types include RSA, DSA, ECDSA, and Ed25519. Unknown key types
213 // result in an error.
214 //
215 // On success, pub will be of type *rsa.PublicKey, *dsa.PublicKey,
216 // *ecdsa.PublicKey, or ed25519.PublicKey.
217 func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
218 var pki publicKeyInfo
219 if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
220 return nil, err
221 } else if len(rest) != 0 {
222 return nil, errors.New("x509: trailing data after ASN.1 of public-key")
223 }
224
225 switch {
226 case pki.Algo.Algorithm.Equal(oidEd25519):
227 pub = ed25519.PublicKey(pki.PublicKey.Bytes)
228 return pub, nil
229 // Prove of concept for key agreement algorithm X25519.
230 // A real implementation would use their own types.
231 //
232 // case pki.Algo.Algorithm.Equal(oidX25519):
233 // pub = ed25519.PublicKey(pki.PublicKey.Bytes)
234 // fmt.Fprintf(os.Stderr, "% x\n", pub)
235 // return pub, nil
236 default:
237 return x509.ParsePKIXPublicKey(derBytes)
238 }
239 }
240
241 // MarshalPKIXPublicKey serializes a public key to DER-encoded PKIX format. The
242 // following key types are supported: *rsa.PublicKey, *ecdsa.PublicKey,
243 // ed25519.Publickey. Unsupported key types result in an error.
244 func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
245 switch p := pub.(type) {
246 case *rsa.PublicKey, *ecdsa.PublicKey:
247 return x509.MarshalPKIXPublicKey(pub)
248 case ed25519.PublicKey:
249 var pkix publicKeyInfo
250 pkix.Algo.Algorithm = oidEd25519
251 pkix.PublicKey = asn1.BitString{
252 Bytes: p,
253 BitLength: 8 * len(p),
254 }
255 return asn1.Marshal(pkix)
256 default:
257 return nil, errors.Errorf("x509: unknown public key type: %T", pub)
258 }
259 }
260
261 // MarshalPKCS8PrivateKey converts a private key to PKCS#8 encoded form. The
262 // following key types are supported: *rsa.PrivateKey, *ecdsa.PublicKey,
263 // ed25519.PrivateKey. Unsupported key types result in an error.
264 func MarshalPKCS8PrivateKey(key interface{}) ([]byte, error) {
265 switch k := key.(type) {
266 case *rsa.PrivateKey, *ecdsa.PrivateKey:
267 b, err := x509.MarshalPKCS8PrivateKey(key)
268 return b, errors.Wrap(err, "error marshaling PKCS#8")
269 case ed25519.PrivateKey:
270 var priv pkcs8
271 priv.PrivateKey = append([]byte{4, 32}, k.Seed()...)[:34]
272 priv.Algo = pkix.AlgorithmIdentifier{
273 Algorithm: asn1.ObjectIdentifier{1, 3, 101, 112},
274 }
275 b, err := asn1.Marshal(priv)
276 return b, errors.Wrap(err, "error marshaling PKCS#8")
277 default:
278 return nil, errors.Errorf("x509: unknown key type while marshaling PKCS#8: %T", key)
279 }
280 }
281
282 // DecryptPEMBlock takes a password encrypted PEM block and the password used
283 // to encrypt it and returns a slice of decrypted DER encoded bytes.
284 //
285 // If the PEM blocks has the Proc-Type header set to "4,ENCRYPTED" it uses
286 // x509.DecryptPEMBlock to decrypt the block. If not it tries to decrypt the
287 // block using AES-128-CBC, AES-192-CBC, AES-256-CBC, DES, or 3DES using the
288 // key derived using PBKDF2 over the given password.
289 func DecryptPEMBlock(block *pem.Block, password []byte) ([]byte, error) {
290 if block.Headers["Proc-Type"] == "4,ENCRYPTED" {
291 //nolint
292 return x509.DecryptPEMBlock(block, password)
293 }
294
295 // PKCS#8 header defined in RFC7468 section 11
296 if block.Type == "ENCRYPTED PRIVATE KEY" {
297 return DecryptPKCS8PrivateKey(block.Bytes, password)
298 }
299
300 return nil, errors.New("unsupported encrypted PEM")
301 }
302
303 // DecryptPKCS8PrivateKey takes a password encrypted private key using the
304 // PKCS#8 encoding and returns the decrypted data in PKCS#8 form.
305 //
306 // It supports AES-128-CBC, AES-192-CBC, AES-256-CBC, DES, or 3DES encrypted
307 // data using the key derived with PBKDF2 over the given password.
308 func DecryptPKCS8PrivateKey(data, password []byte) ([]byte, error) {
309 var pki encryptedPrivateKeyInfo
310 if _, err := asn1.Unmarshal(data, &pki); err != nil {
311 return nil, errors.Wrap(err, "failed to unmarshal private key")
312 }
313
314 if !pki.Algo.Algorithm.Equal(oidPBES2) {
315 return nil, errors.New("unsupported encrypted PEM: only PBES2 is supported")
316 }
317
318 if !pki.Algo.Parameters.KeyDerivationFunc.Algo.Equal(oidPKCS5PBKDF2) {
319 return nil, errors.New("unsupported encrypted PEM: only PBKDF2 is supported")
320 }
321
322 encParam := pki.Algo.Parameters.EncryptionScheme
323 kdfParam := pki.Algo.Parameters.KeyDerivationFunc.PBKDF2Params
324
325 iv := encParam.IV
326 salt := kdfParam.Salt
327 iter := kdfParam.IterationCount
328
329 // pbkdf2 hash function
330 keyHash := sha1.New
331 if kdfParam.PrfParam.Algo.Equal(oidHMACWithSHA256) {
332 keyHash = sha256.New
333 }
334
335 encryptedKey := pki.PrivateKey
336 var symkey []byte
337 var block cipher.Block
338 var err error
339 switch {
340 // AES-128-CBC, AES-192-CBC, AES-256-CBC
341 case encParam.EncryAlgo.Equal(oidAES128CBC):
342 symkey = pbkdf2.Key(password, salt, iter, 16, keyHash)
343 block, err = aes.NewCipher(symkey)
344 case encParam.EncryAlgo.Equal(oidAES196CBC):
345 symkey = pbkdf2.Key(password, salt, iter, 24, keyHash)
346 block, err = aes.NewCipher(symkey)
347 case encParam.EncryAlgo.Equal(oidAES256CBC):
348 symkey = pbkdf2.Key(password, salt, iter, 32, keyHash)
349 block, err = aes.NewCipher(symkey)
350 // DES, TripleDES
351 case encParam.EncryAlgo.Equal(oidDESCBC):
352 symkey = pbkdf2.Key(password, salt, iter, 8, keyHash)
353 block, err = des.NewCipher(symkey)
354 case encParam.EncryAlgo.Equal(oidD3DESCBC):
355 symkey = pbkdf2.Key(password, salt, iter, 24, keyHash)
356 block, err = des.NewTripleDESCipher(symkey)
357 default:
358 return nil, errors.Errorf("unsupported encrypted PEM: unknown algorithm %v", encParam.EncryAlgo)
359 }
360 if err != nil {
361 return nil, err
362 }
363
364 mode := cipher.NewCBCDecrypter(block, iv)
365 mode.CryptBlocks(encryptedKey, encryptedKey)
366
367 return encryptedKey, nil
368 }
369
370 // EncryptPKCS8PrivateKey returns a PEM block holding the given PKCS#8 encroded
371 // private key, encrypted with the specified algorithm and a PBKDF2 derived key
372 // from the given password.
373 func EncryptPKCS8PrivateKey(rand io.Reader, data, password []byte, alg x509.PEMCipher) (*pem.Block, error) {
374 ciph := cipherByKey(alg)
375 if ciph == nil {
376 return nil, errors.Errorf("failed to encrypt PEM: unknown algorithm %v", alg)
377 }
378
379 salt := make([]byte, PBKDF2SaltSize)
380 if _, err := io.ReadFull(rand, salt); err != nil {
381 return nil, errors.Wrap(err, "failed to generate salt")
382 }
383 iv := make([]byte, ciph.blockSize)
384 if _, err := io.ReadFull(rand, iv); err != nil {
385 return nil, errors.Wrap(err, "failed to generate IV")
386 }
387
388 key := ciph.deriveKey(password, salt, sha256.New)
389 block, err := ciph.cipherFunc(key)
390 if err != nil {
391 return nil, errors.Wrap(err, "failed to create cipher")
392 }
393 enc := cipher.NewCBCEncrypter(block, iv)
394 pad := ciph.blockSize - len(data)%ciph.blockSize
395 encrypted := make([]byte, len(data), len(data)+pad)
396 // We could save this copy by encrypting all the whole blocks in
397 // the data separately, but it doesn't seem worth the additional
398 // code.
399 copy(encrypted, data)
400 // See RFC 1423, section 1.1
401 for i := 0; i < pad; i++ {
402 encrypted = append(encrypted, byte(pad))
403 }
404 enc.CryptBlocks(encrypted, encrypted)
405
406 // Build encrypted ans1 data
407 pki := encryptedPrivateKeyInfo{
408 Algo: encryptedlAlgorithmIdentifier{
409 Algorithm: oidPBES2,
410 Parameters: pbes2Params{
411 KeyDerivationFunc: pbkdf2Algorithms{
412 Algo: oidPKCS5PBKDF2,
413 PBKDF2Params: pbkdf2Params{
414 Salt: salt,
415 IterationCount: PBKDF2Iterations,
416 PrfParam: prfParam{
417 Algo: oidHMACWithSHA256,
418 },
419 },
420 },
421 EncryptionScheme: pbkdf2Encs{
422 EncryAlgo: ciph.identifier,
423 IV: iv,
424 },
425 },
426 },
427 PrivateKey: encrypted,
428 }
429
430 b, err := asn1.Marshal(pki)
431 if err != nil {
432 return nil, errors.Wrap(err, "error marshaling encrypted key")
433 }
434 return &pem.Block{
435 Type: "ENCRYPTED PRIVATE KEY",
436 Bytes: b,
437 }, nil
438 }