Debian Codegraph @

dkim/crypto.py

raw symbols SCIP
1 # This software is provided 'as-is', without any express or implied
2 # warranty. In no event will the author be held liable for any damages
3 # arising from the use of this software.
4 #
5 # Permission is granted to anyone to use this software for any purpose,
6 # including commercial applications, and to alter it and redistribute it
7 # freely, subject to the following restrictions:
8 #
9 # 1. The origin of this software must not be misrepresented; you must not
10 # claim that you wrote the original software. If you use this software
11 # in a product, an acknowledgment in the product documentation would be
12 # appreciated but is not required.
13 # 2. Altered source versions must be plainly marked as such, and must not be
14 # misrepresented as being the original software.
15 # 3. This notice may not be removed or altered from any source distribution.
16 #
17 # Copyright (c) 2008 Greg Hewgill http://hewgill.com
18 #
19 # This has been modified from the original software.
20 # Copyright (c) 2011 William Grant <[email protected]>
21 # Copyright (c) 2018 Scott Kitterman <[email protected]>
22
23 __all__ = [
24 'DigestTooLargeError',
25 'HASH_ALGORITHMS',
26 'ARC_HASH_ALGORITHMS',
27 'parse_pem_private_key',
28 'parse_private_key',
29 'parse_public_key',
30 'RSASSA_PKCS1_v1_5_sign',
31 'RSASSA_PKCS1_v1_5_verify',
32 'UnparsableKeyError',
33 ]
34
35 import base64
36 import hashlib
37 import re
38
39 from dkim.asn1 import (
40 ASN1FormatError,
41 asn1_build,
42 asn1_parse,
43 BIT_STRING,
44 INTEGER,
45 SEQUENCE,
46 OBJECT_IDENTIFIER,
47 OCTET_STRING,
48 NULL,
49 )
50
51 ASN1_PKCS8_PrivateKey = [
52 (SEQUENCE, [
53 (INTEGER,),
54 (SEQUENCE, [ (OBJECT_IDENTIFIER,), (NULL,),]),
55 (OCTET_STRING,),
56 ])
57 ]
58
59 ASN1_Object = [
60 (SEQUENCE, [
61 (SEQUENCE, [
62 (OBJECT_IDENTIFIER,),
63 (NULL,),
64 ]),
65 (BIT_STRING,),
66 ])
67 ]
68
69 ASN1_RSAPublicKey = [
70 (SEQUENCE, [
71 (INTEGER,),
72 (INTEGER,),
73 ])
74 ]
75
76 ASN1_RSAPrivateKey = [
77 (SEQUENCE, [
78 (INTEGER,),
79 (INTEGER,),
80 (INTEGER,),
81 (INTEGER,),
82 (INTEGER,),
83 (INTEGER,),
84 (INTEGER,),
85 (INTEGER,),
86 (INTEGER,),
87 ])
88 ]
89
90 HASH_ALGORITHMS = {
91 b'rsa-sha1': hashlib.sha1,
92 b'rsa-sha256': hashlib.sha256,
93 b'ed25519-sha256': hashlib.sha256
94 }
95
96 ARC_HASH_ALGORITHMS = {
97 b'rsa-sha256': hashlib.sha256,
98 }
99
100 # These values come from RFC 8017, section 9.2 Notes, page 46.
101 HASH_ID_MAP = {
102 'sha1': b"\x2b\x0e\x03\x02\x1a",
103 'sha256': b"\x60\x86\x48\x01\x65\x03\x04\x02\x01",
104 }
105
106
107 class DigestTooLargeError(Exception):
108 """The digest is too large to fit within the requested length."""
109 pass
110
111
112 class UnparsableKeyError(Exception):
113 """The data could not be parsed as a key."""
114 pass
115
116
117 def parse_public_key(data):
118 """Parse an RSA public key.
119
120 @param data: DER-encoded X.509 subjectPublicKeyInfo
121 containing an RFC8017 RSAPublicKey.
122 @return: RSA public key
123 """
124 try:
125 # Not sure why the [1:] is necessary to skip a byte.
126 x = asn1_parse(ASN1_Object, data)
127 pkd = asn1_parse(ASN1_RSAPublicKey, x[0][1][1:])
128 except ASN1FormatError as e_spki:
129 try:
130 pkd = asn1_parse(ASN1_RSAPublicKey, data)
131 except ASN1FormatError as e_rsa:
132 raise UnparsableKeyError('Unparsable public key; SubjectPublicKeyInfo: ' + str(e_spki) + '; RSAPublicKey: ' + str(e_rsa))
133 pk = {
134 'modulus': pkd[0][0],
135 'publicExponent': pkd[0][1],
136 }
137 return pk
138
139
140 def parse_private_key(data):
141 """Parse an RSA private key.
142
143 @param data: DER-encoded RFC8017 RSAPrivateKey or CMS-encoded RFC5958 asymetric key package.
144 @return: RSA private key
145 """
146 try:
147 pka = asn1_parse(ASN1_RSAPrivateKey, data)
148 except ASN1FormatError:
149 try:
150 #If it fails it might be because of PKCS#8 (key generated with openSSL 3.X)
151 pkt = asn1_parse(ASN1_PKCS8_PrivateKey, data)
152 pka = asn1_parse(ASN1_RSAPrivateKey, pkt[0][2])
153 except ASN1FormatError as e:
154 raise UnparsableKeyError("Unparsable private key (are your sure it is encoded in PKCS#1 or PKCS#8 standard ?):\n" + str(e))
155
156 pk = {
157 'version': pka[0][0],
158 'modulus': pka[0][1],
159 'publicExponent': pka[0][2],
160 'privateExponent': pka[0][3],
161 'prime1': pka[0][4],
162 'prime2': pka[0][5],
163 'exponent1': pka[0][6],
164 'exponent2': pka[0][7],
165 'coefficient': pka[0][8],
166 }
167 return pk
168
169
170 def parse_pem_private_key(data):
171 """Parse a PEM RSA private key.
172
173 @param data: RFC8017 RSAPrivateKey in PEM format.
174 @return: RSA private key
175 """
176 m = re.search(b"--\n(.*?)\n--", data, re.DOTALL)
177 if m is None:
178 raise UnparsableKeyError("Private key not found")
179 try:
180 pkdata = base64.b64decode(m.group(1))
181 except TypeError as e:
182 raise UnparsableKeyError(str(e))
183 return parse_private_key(pkdata)
184
185
186 def EMSA_PKCS1_v1_5_encode(hash, mlen):
187 """Encode a digest with RFC8017 EMSA-PKCS1-v1_5.
188
189 @param hash: hash object to encode
190 @param mlen: desired message length
191 @return: encoded digest byte string
192 """
193 dinfo = asn1_build(
194 (SEQUENCE, [
195 (SEQUENCE, [
196 (OBJECT_IDENTIFIER, HASH_ID_MAP[hash.name.lower()]),
197 (NULL, None),
198 ]),
199 (OCTET_STRING, hash.digest()),
200 ]))
201 if len(dinfo) + 11 > mlen:
202 raise DigestTooLargeError()
203 return b"\x00\x01"+b"\xff"*(mlen-len(dinfo)-3)+b"\x00"+dinfo
204
205
206 def str2int(s):
207 """Convert a byte string to an integer.
208
209 @param s: byte string representing a positive integer to convert
210 @return: converted integer
211 """
212 s = bytearray(s)
213 r = 0
214 for c in s:
215 r = (r << 8) | c
216 return r
217
218
219 def int2str(n, length=-1):
220 """Convert an integer to a byte string.
221
222 @param n: positive integer to convert
223 @param length: minimum length
224 @return: converted bytestring, of at least the minimum length if it was
225 specified
226 """
227 assert n >= 0
228 r = bytearray()
229 while length < 0 or len(r) < length:
230 r.append(n & 0xff)
231 n >>= 8
232 if length < 0 and n == 0:
233 break
234 r.reverse()
235 assert length < 0 or len(r) == length
236 return r
237
238
239 def rsa_decrypt(message, pk, mlen):
240 """Perform RSA decryption/signing
241
242 @param message: byte string to operate on
243 @param pk: private key data
244 @param mlen: desired output length
245 @return: byte string result of the operation
246 """
247 c = str2int(message)
248
249 m1 = pow(c, pk['exponent1'], pk['prime1'])
250 m2 = pow(c, pk['exponent2'], pk['prime2'])
251
252 if m1 < m2:
253 h = pk['coefficient'] * (m1 + pk['prime1'] - m2) % pk['prime1']
254 else:
255 h = pk['coefficient'] * (m1 - m2) % pk['prime1']
256
257 return int2str(m2 + h * pk['prime2'], mlen)
258
259
260 def rsa_encrypt(message, pk, mlen):
261 """Perform RSA encryption/verification
262
263 @param message: byte string to operate on
264 @param pk: public key data
265 @param mlen: desired output length
266 @return: byte string result of the operation
267 """
268 m = str2int(message)
269 return int2str(pow(m, pk['publicExponent'], pk['modulus']), mlen)
270
271
272 def RSASSA_PKCS1_v1_5_sign(hash, private_key):
273 """Sign a digest with RFC8017 RSASSA-PKCS1-v1_5.
274
275 @param hash: hash object to sign
276 @param private_key: private key data
277 @return: signed digest byte string
278 """
279 modlen = len(int2str(private_key['modulus']))
280 encoded_digest = EMSA_PKCS1_v1_5_encode(hash, modlen)
281 return rsa_decrypt(encoded_digest, private_key, modlen)
282
283
284 def RSASSA_PKCS1_v1_5_verify(hash, signature, public_key):
285 """Verify a digest signed with RFC8017 RSASSA-PKCS1-v1_5.
286
287 @param hash: hash object to check
288 @param signature: signed digest byte string
289 @param public_key: public key data
290 @return: True if the signature is valid, False otherwise
291 """
292 modlen = len(int2str(public_key['modulus']))
293 encoded_digest = EMSA_PKCS1_v1_5_encode(hash, modlen)
294 signed_digest = rsa_encrypt(signature, public_key, modlen)
295 return encoded_digest == signed_digest