Debian Codegraph @

lib/Crypto/IO/PKCS8.py

raw symbols SCIP
1 #
2 # PublicKey/PKCS8.py : PKCS#8 functions
3 #
4 # ===================================================================
5 #
6 # Copyright (c) 2014, Legrandin <[email protected]>
7 # All rights reserved.
8 #
9 # Redistribution and use in source and binary forms, with or without
10 # modification, are permitted provided that the following conditions
11 # are met:
12 #
13 # 1. Redistributions of source code must retain the above copyright
14 # notice, this list of conditions and the following disclaimer.
15 # 2. Redistributions in binary form must reproduce the above copyright
16 # notice, this list of conditions and the following disclaimer in
17 # the documentation and/or other materials provided with the
18 # distribution.
19 #
20 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 # POSSIBILITY OF SUCH DAMAGE.
32 # ===================================================================
33
34
35 from Crypto.Util.py3compat import *
36
37 from Crypto.Util.asn1 import (
38 DerNull,
39 DerSequence,
40 DerObjectId,
41 DerOctetString,
42 )
43
44 from Crypto.IO._PBES import PBES1, PBES2, PbesError
45
46
47 __all__ = ['wrap', 'unwrap']
48
49
50 def wrap(private_key, key_oid, passphrase=None, protection=None,
51 prot_params=None, key_params=DerNull(), randfunc=None):
52 """Wrap a private key into a PKCS#8 blob (clear or encrypted).
53
54 Args:
55
56 private_key (bytes):
57 The private key encoded in binary form. The actual encoding is
58 algorithm specific. In most cases, it is DER.
59
60 key_oid (string):
61 The object identifier (OID) of the private key to wrap.
62 It is a dotted string, like ``'1.2.840.113549.1.1.1'`` (for RSA keys)
63 or ``'1.2.840.10045.2.1'`` (for ECC keys).
64
65 Keyword Args:
66
67 passphrase (bytes or string):
68 The secret passphrase from which the wrapping key is derived.
69 Set it only if encryption is required.
70
71 protection (string):
72 The identifier of the algorithm to use for securely wrapping the key.
73 Refer to :ref:`the encryption parameters<enc_params>` .
74 The default value is ``'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC'``.
75
76 prot_params (dictionary):
77 Parameters for the key derivation function (KDF).
78 Refer to :ref:`the encryption parameters<enc_params>` .
79
80 key_params (DER object or None):
81 The ``parameters`` field to use in the ``AlgorithmIdentifier``
82 SEQUENCE. If ``None``, no ``parameters`` field will be added.
83 By default, the ASN.1 type ``NULL`` is used.
84
85 randfunc (callable):
86 Random number generation function; it should accept a single integer
87 N and return a string of random data, N bytes long.
88 If not specified, a new RNG will be instantiated
89 from :mod:`Crypto.Random`.
90
91 Returns:
92 bytes: The PKCS#8-wrapped private key (possibly encrypted).
93 """
94
95 #
96 # PrivateKeyInfo ::= SEQUENCE {
97 # version Version,
98 # privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
99 # privateKey PrivateKey,
100 # attributes [0] IMPLICIT Attributes OPTIONAL
101 # }
102 #
103 if key_params is None:
104 algorithm = DerSequence([DerObjectId(key_oid)])
105 else:
106 algorithm = DerSequence([DerObjectId(key_oid), key_params])
107
108 pk_info = DerSequence([
109 0,
110 algorithm,
111 DerOctetString(private_key)
112 ])
113 pk_info_der = pk_info.encode()
114
115 if passphrase is None:
116 return pk_info_der
117
118 if not passphrase:
119 raise ValueError("Empty passphrase")
120
121 # Encryption with PBES2
122 passphrase = tobytes(passphrase)
123 if protection is None:
124 protection = 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC'
125 return PBES2.encrypt(pk_info_der, passphrase,
126 protection, prot_params, randfunc)
127
128
129 def unwrap(p8_private_key, passphrase=None):
130 """Unwrap a private key from a PKCS#8 blob (clear or encrypted).
131
132 Args:
133 p8_private_key (bytes):
134 The private key wrapped into a PKCS#8 container, DER encoded.
135
136 Keyword Args:
137 passphrase (byte string or string):
138 The passphrase to use to decrypt the blob (if it is encrypted).
139
140 Return:
141 A tuple containing
142
143 #. the algorithm identifier of the wrapped key (OID, dotted string)
144 #. the private key (bytes, DER encoded)
145 #. the associated parameters (bytes, DER encoded) or ``None``
146
147 Raises:
148 ValueError : if decoding fails
149 """
150
151 if passphrase:
152 passphrase = tobytes(passphrase)
153
154 found = False
155 try:
156 p8_private_key = PBES1.decrypt(p8_private_key, passphrase)
157 found = True
158 except PbesError as e:
159 error_str = "PBES1[%s]" % str(e)
160 except ValueError:
161 error_str = "PBES1[Invalid]"
162
163 if not found:
164 try:
165 p8_private_key = PBES2.decrypt(p8_private_key, passphrase)
166 found = True
167 except PbesError as e:
168 error_str += ",PBES2[%s]" % str(e)
169 except ValueError:
170 error_str += ",PBES2[Invalid]"
171
172 if not found:
173 raise ValueError("Error decoding PKCS#8 (%s)" % error_str)
174
175 pk_info = DerSequence().decode(p8_private_key, nr_elements=(2, 3, 4, 5))
176 if len(pk_info) == 2 and not passphrase:
177 raise ValueError("Not a valid clear PKCS#8 structure "
178 "(maybe it is encrypted?)")
179
180 # RFC5208, PKCS#8, version is v1(0)
181 #
182 # PrivateKeyInfo ::= SEQUENCE {
183 # version Version,
184 # privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
185 # privateKey PrivateKey,
186 # attributes [0] IMPLICIT Attributes OPTIONAL
187 # }
188 #
189 # RFC5915, Asymmetric Key Package, version is v2(1)
190 #
191 # OneAsymmetricKey ::= SEQUENCE {
192 # version Version,
193 # privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
194 # privateKey PrivateKey,
195 # attributes [0] Attributes OPTIONAL,
196 # ...,
197 # [[2: publicKey [1] PublicKey OPTIONAL ]],
198 # ...
199 # }
200
201 if pk_info[0] == 0:
202 if len(pk_info) not in (3, 4):
203 raise ValueError("Not a valid PrivateKeyInfo SEQUENCE")
204 elif pk_info[0] == 1:
205 if len(pk_info) not in (3, 4, 5):
206 raise ValueError("Not a valid PrivateKeyInfo SEQUENCE")
207 else:
208 raise ValueError("Not a valid PrivateKeyInfo SEQUENCE")
209
210 algo = DerSequence().decode(pk_info[1], nr_elements=(1, 2))
211 algo_oid = DerObjectId().decode(algo[0]).value
212 if len(algo) == 1:
213 algo_params = None
214 else:
215 try:
216 DerNull().decode(algo[1])
217 algo_params = None
218 except:
219 algo_params = algo[1]
220
221 # PrivateKey ::= OCTET STRING
222 private_key = DerOctetString().decode(pk_info[2]).payload
223
224 # We ignore attributes and (for v2 only) publickey
225
226 return (algo_oid, private_key, algo_params)