blob: 68726e06efcd371e637b56705e161629be6d1b2f [file] [log] [blame]
A R Karthick307483c2016-06-06 17:05:19 -07001## This file is part of Scapy
2## See http://www.secdev.org/projects/scapy for more informations
3## Copyright (C) Arnaud Ebalard <arno@natisbad.org>
4## This program is published under a GPLv2 license
5
6"""
7Cryptographic certificates.
8"""
9
10import os, sys, math, struct, random
11from scapy.utils import strxor
12from scapy_ssl_tls.ssl_tls_crypto import x509_extract_pubkey_from_der
13try:
14 HAS_HASHLIB=True
15 import hashlib
16except:
17 HAS_HASHLIB=False
18
19from Crypto.PublicKey import *
20from Crypto.Cipher import *
21from Crypto.Hash import *
22from Crypto.Util import number
23
24# Maximum allowed size in bytes for a certificate file, to avoid
25# loading huge file when importing a cert
26MAX_KEY_SIZE=50*1024
27
28#####################################################################
29# Some helpers
30#####################################################################
31
32def warning(m):
33 print "WARNING: %s" % m
34
35def randstring(l):
36 """
37 Returns a random string of length l (l >= 0)
38 """
39 tmp = map(lambda x: struct.pack("B", random.randrange(0, 256, 1)), [""]*l)
40 return "".join(tmp)
41
42def zerofree_randstring(l):
43 """
44 Returns a random string of length l (l >= 0) without zero in it.
45 """
46 tmp = map(lambda x: struct.pack("B", random.randrange(1, 256, 1)), [""]*l)
47 return "".join(tmp)
48
49def strand(s1, s2):
50 """
51 Returns the binary AND of the 2 provided strings s1 and s2. s1 and s2
52 must be of same length.
53 """
54 return "".join(map(lambda x,y:chr(ord(x)&ord(y)), s1, s2))
55
56# OS2IP function defined in RFC 3447 for octet string to integer conversion
57def pkcs_os2ip(x):
58 """
59 Accepts a byte string as input parameter and return the associated long
60 value:
61
62 Input : x octet string to be converted
63
64 Output: x corresponding nonnegative integer
65
66 Reverse function is pkcs_i2osp()
67 """
68 return number.bytes_to_long(x)
69
70# IP2OS function defined in RFC 3447 for octet string to integer conversion
71def pkcs_i2osp(x,xLen):
72 """
73 Converts a long (the first parameter) to the associated byte string
74 representation of length l (second parameter). Basically, the length
75 parameters allow the function to perform the associated padding.
76
77 Input : x nonnegative integer to be converted
78 xLen intended length of the resulting octet string
79
80 Output: x corresponding nonnegative integer
81
82 Reverse function is pkcs_os2ip().
83 """
84 z = number.long_to_bytes(x)
85 padlen = max(0, xLen-len(z))
86 return '\x00'*padlen + z
87
88# for every hash function a tuple is provided, giving access to
89# - hash output length in byte
90# - associated hash function that take data to be hashed as parameter
91# XXX I do not provide update() at the moment.
92# - DER encoding of the leading bits of digestInfo (the hash value
93# will be concatenated to create the complete digestInfo).
94#
95# Notes:
96# - MD4 asn.1 value should be verified. Also, as stated in
97# PKCS#1 v2.1, MD4 should not be used.
98# - hashlib is available from http://code.krypto.org/python/hashlib/
99# - 'tls' one is the concatenation of both md5 and sha1 hashes used
100# by SSL/TLS when signing/verifying things
101_hashFuncParams = {
102 "md2" : (16,
103 lambda x: MD2.new(x).digest(),
104 '\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x02\x05\x00\x04\x10'),
105 "md4" : (16,
106 lambda x: MD4.new(x).digest(),
107 '\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x04\x05\x00\x04\x10'), # is that right ?
108 "md5" : (16,
109 lambda x: MD5.new(x).digest(),
110 '\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05\x05\x00\x04\x10'),
111 "sha1" : (20,
112 lambda x: SHA.new(x).digest(),
113 '\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14'),
114 "tls" : (36,
115 lambda x: MD5.new(x).digest() + SHA.new(x).digest(),
116 '') }
117
118if HAS_HASHLIB:
119 _hashFuncParams["sha224"] = (28,
120 lambda x: hashlib.sha224(x).digest(),
121 '\x30\x2d\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04\x05\x00\x04\x1c')
122 _hashFuncParams["sha256"] = (32,
123 lambda x: hashlib.sha256(x).digest(),
124 '\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20')
125 _hashFuncParams["sha384"] = (48,
126 lambda x: hashlib.sha384(x).digest(),
127 '\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02\x05\x00\x04\x30')
128 _hashFuncParams["sha512"] = (64,
129 lambda x: hashlib.sha512(x).digest(),
130 '\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03\x05\x00\x04\x40')
131else:
132 warning("hashlib support is not available. Consider installing it")
133 warning("if you need sha224, sha256, sha384 and sha512 algs.")
134
135def pkcs_mgf1(mgfSeed, maskLen, h):
136 """
137 Implements generic MGF1 Mask Generation function as described in
138 Appendix B.2.1 of RFC 3447. The hash function is passed by name.
139 valid values are 'md2', 'md4', 'md5', 'sha1', 'tls, 'sha256',
140 'sha384' and 'sha512'. Returns None on error.
141
142 Input:
143 mgfSeed: seed from which mask is generated, an octet string
144 maskLen: intended length in octets of the mask, at most 2^32 * hLen
145 hLen (see below)
146 h : hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls',
147 'sha256', 'sha384'). hLen denotes the length in octets of
148 the hash function output.
149
150 Output:
151 an octet string of length maskLen
152 """
153
154 # steps are those of Appendix B.2.1
155 if not _hashFuncParams.has_key(h):
156 warning("pkcs_mgf1: invalid hash (%s) provided")
157 return None
158 hLen = _hashFuncParams[h][0]
159 hFunc = _hashFuncParams[h][1]
160 if maskLen > 2**32 * hLen: # 1)
161 warning("pkcs_mgf1: maskLen > 2**32 * hLen")
162 return None
163 T = "" # 2)
164 maxCounter = math.ceil(float(maskLen) / float(hLen)) # 3)
165 counter = 0
166 while counter < maxCounter:
167 C = pkcs_i2osp(counter, 4)
168 T += hFunc(mgfSeed + C)
169 counter += 1
170 return T[:maskLen]
171
172
173def pkcs_emsa_pss_encode(M, emBits, h, mgf, sLen):
174 """
175 Implements EMSA-PSS-ENCODE() function described in Sect. 9.1.1 of RFC 3447
176
177 Input:
178 M : message to be encoded, an octet string
179 emBits: maximal bit length of the integer resulting of pkcs_os2ip(EM),
180 where EM is the encoded message, output of the function.
181 h : hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls',
182 'sha256', 'sha384'). hLen denotes the length in octets of
183 the hash function output.
184 mgf : the mask generation function f : seed, maskLen -> mask
185 sLen : intended length in octets of the salt
186
187 Output:
188 encoded message, an octet string of length emLen = ceil(emBits/8)
189
190 On error, None is returned.
191 """
192
193 # 1) is not done
194 hLen = _hashFuncParams[h][0] # 2)
195 hFunc = _hashFuncParams[h][1]
196 mHash = hFunc(M)
197 emLen = int(math.ceil(emBits/8.))
198 if emLen < hLen + sLen + 2: # 3)
199 warning("encoding error (emLen < hLen + sLen + 2)")
200 return None
201 salt = randstring(sLen) # 4)
202 MPrime = '\x00'*8 + mHash + salt # 5)
203 H = hFunc(MPrime) # 6)
204 PS = '\x00'*(emLen - sLen - hLen - 2) # 7)
205 DB = PS + '\x01' + salt # 8)
206 dbMask = mgf(H, emLen - hLen - 1) # 9)
207 maskedDB = strxor(DB, dbMask) # 10)
208 l = (8*emLen - emBits)/8 # 11)
209 rem = 8*emLen - emBits - 8*l # additionnal bits
210 andMask = l*'\x00'
211 if rem:
212 j = chr(reduce(lambda x,y: x+y, map(lambda x: 1<<x, range(8-rem))))
213 andMask += j
214 l += 1
215 maskedDB = strand(maskedDB[:l], andMask) + maskedDB[l:]
216 EM = maskedDB + H + '\xbc' # 12)
217 return EM # 13)
218
219
220def pkcs_emsa_pss_verify(M, EM, emBits, h, mgf, sLen):
221 """
222 Implements EMSA-PSS-VERIFY() function described in Sect. 9.1.2 of RFC 3447
223
224 Input:
225 M : message to be encoded, an octet string
226 EM : encoded message, an octet string of length emLen = ceil(emBits/8)
227 emBits: maximal bit length of the integer resulting of pkcs_os2ip(EM)
228 h : hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls',
229 'sha256', 'sha384'). hLen denotes the length in octets of
230 the hash function output.
231 mgf : the mask generation function f : seed, maskLen -> mask
232 sLen : intended length in octets of the salt
233
234 Output:
235 True if the verification is ok, False otherwise.
236 """
237
238 # 1) is not done
239 hLen = _hashFuncParams[h][0] # 2)
240 hFunc = _hashFuncParams[h][1]
241 mHash = hFunc(M)
242 emLen = int(math.ceil(emBits/8.)) # 3)
243 if emLen < hLen + sLen + 2:
244 return False
245 if EM[-1] != '\xbc': # 4)
246 return False
247 l = emLen - hLen - 1 # 5)
248 maskedDB = EM[:l]
249 H = EM[l:l+hLen]
250 l = (8*emLen - emBits)/8 # 6)
251 rem = 8*emLen - emBits - 8*l # additionnal bits
252 andMask = l*'\xff'
253 if rem:
254 val = reduce(lambda x,y: x+y, map(lambda x: 1<<x, range(8-rem)))
255 j = chr(~val & 0xff)
256 andMask += j
257 l += 1
258 if strand(maskedDB[:l], andMask) != '\x00'*l:
259 return False
260 dbMask = mgf(H, emLen - hLen - 1) # 7)
261 DB = strxor(maskedDB, dbMask) # 8)
262 l = (8*emLen - emBits)/8 # 9)
263 rem = 8*emLen - emBits - 8*l # additionnal bits
264 andMask = l*'\x00'
265 if rem:
266 j = chr(reduce(lambda x,y: x+y, map(lambda x: 1<<x, range(8-rem))))
267 andMask += j
268 l += 1
269 DB = strand(DB[:l], andMask) + DB[l:]
270 l = emLen - hLen - sLen - 1 # 10)
271 if DB[:l] != '\x00'*(l-1) + '\x01':
272 return False
273 salt = DB[-sLen:] # 11)
274 MPrime = '\x00'*8 + mHash + salt # 12)
275 HPrime = hFunc(MPrime) # 13)
276 return H == HPrime # 14)
277
278
279def pkcs_emsa_pkcs1_v1_5_encode(M, emLen, h): # section 9.2 of RFC 3447
280 """
281 Implements EMSA-PKCS1-V1_5-ENCODE() function described in Sect.
282 9.2 of RFC 3447.
283
284 Input:
285 M : message to be encode, an octet string
286 emLen: intended length in octets of the encoded message, at least
287 tLen + 11, where tLen is the octet length of the DER encoding
288 T of a certain value computed during the encoding operation.
289 h : hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls',
290 'sha256', 'sha384'). hLen denotes the length in octets of
291 the hash function output.
292
293 Output:
294 encoded message, an octet string of length emLen
295
296 On error, None is returned.
297 """
298 hLen = _hashFuncParams[h][0] # 1)
299 hFunc = _hashFuncParams[h][1]
300 H = hFunc(M)
301 hLeadingDigestInfo = _hashFuncParams[h][2] # 2)
302 T = hLeadingDigestInfo + H
303 tLen = len(T)
304 if emLen < tLen + 11: # 3)
305 warning("pkcs_emsa_pkcs1_v1_5_encode: intended encoded message length too short")
306 return None
307 PS = '\xff'*(emLen - tLen - 3) # 4)
308 EM = '\x00' + '\x01' + PS + '\x00' + T # 5)
309 return EM # 6)
310
311
312#####################################################################
313# Public Key Cryptography related stuff
314#####################################################################
315
316class _EncryptAndVerify:
317 ### Below are encryption methods
318
319 def _rsaep(self, m):
320 """
321 Internal method providing raw RSA encryption, i.e. simple modular
322 exponentiation of the given message representative 'm', a long
323 between 0 and n-1.
324
325 This is the encryption primitive RSAEP described in PKCS#1 v2.1,
326 i.e. RFC 3447 Sect. 5.1.1.
327
328 Input:
329 m: message representative, a long between 0 and n-1, where
330 n is the key modulus.
331
332 Output:
333 ciphertext representative, a long between 0 and n-1
334
335 Not intended to be used directly. Please, see encrypt() method.
336 """
337
338 n = self.modulus
339 if type(m) is int:
340 m = long(m)
341 if type(m) is not long or m > n-1:
342 warning("Key._rsaep() expects a long between 0 and n-1")
343 return None
344
345 return self.key.encrypt(m, "")[0]
346
347
348 def _rsaes_pkcs1_v1_5_encrypt(self, M):
349 """
350 Implements RSAES-PKCS1-V1_5-ENCRYPT() function described in section
351 7.2.1 of RFC 3447.
352
353 Input:
354 M: message to be encrypted, an octet string of length mLen, where
355 mLen <= k - 11 (k denotes the length in octets of the key modulus)
356
357 Output:
358 ciphertext, an octet string of length k
359
360 On error, None is returned.
361 """
362
363 # 1) Length checking
364 mLen = len(M)
365 k = self.modulusLen / 8
366 if mLen > k - 11:
367 warning("Key._rsaes_pkcs1_v1_5_encrypt(): message too "
368 "long (%d > %d - 11)" % (mLen, k))
369 return None
370
371 # 2) EME-PKCS1-v1_5 encoding
372 PS = zerofree_randstring(k - mLen - 3) # 2.a)
373 EM = '\x00' + '\x02' + PS + '\x00' + M # 2.b)
374
375 # 3) RSA encryption
376 m = pkcs_os2ip(EM) # 3.a)
377 c = self._rsaep(m) # 3.b)
378 C = pkcs_i2osp(c, k) # 3.c)
379
380 return C # 4)
381
382
383 def _rsaes_oaep_encrypt(self, M, h=None, mgf=None, L=None):
384 """
385 Internal method providing RSAES-OAEP-ENCRYPT as defined in Sect.
386 7.1.1 of RFC 3447. Not intended to be used directly. Please, see
387 encrypt() method for type "OAEP".
388
389
390 Input:
391 M : message to be encrypted, an octet string of length mLen
392 where mLen <= k - 2*hLen - 2 (k denotes the length in octets
393 of the RSA modulus and hLen the length in octets of the hash
394 function output)
395 h : hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls',
396 'sha256', 'sha384'). hLen denotes the length in octets of
397 the hash function output. 'sha1' is used by default if not
398 provided.
399 mgf: the mask generation function f : seed, maskLen -> mask
400 L : optional label to be associated with the message; the default
401 value for L, if not provided is the empty string
402
403 Output:
404 ciphertext, an octet string of length k
405
406 On error, None is returned.
407 """
408 # The steps below are the one described in Sect. 7.1.1 of RFC 3447.
409 # 1) Length Checking
410 # 1.a) is not done
411 mLen = len(M)
412 if h is None:
413 h = "sha1"
414 if not _hashFuncParams.has_key(h):
415 warning("Key._rsaes_oaep_encrypt(): unknown hash function %s.", h)
416 return None
417 hLen = _hashFuncParams[h][0]
418 hFun = _hashFuncParams[h][1]
419 k = self.modulusLen / 8
420 if mLen > k - 2*hLen - 2: # 1.b)
421 warning("Key._rsaes_oaep_encrypt(): message too long.")
422 return None
423
424 # 2) EME-OAEP encoding
425 if L is None: # 2.a)
426 L = ""
427 lHash = hFun(L)
428 PS = '\x00'*(k - mLen - 2*hLen - 2) # 2.b)
429 DB = lHash + PS + '\x01' + M # 2.c)
430 seed = randstring(hLen) # 2.d)
431 if mgf is None: # 2.e)
432 mgf = lambda x,y: pkcs_mgf1(x,y,h)
433 dbMask = mgf(seed, k - hLen - 1)
434 maskedDB = strxor(DB, dbMask) # 2.f)
435 seedMask = mgf(maskedDB, hLen) # 2.g)
436 maskedSeed = strxor(seed, seedMask) # 2.h)
437 EM = '\x00' + maskedSeed + maskedDB # 2.i)
438
439 # 3) RSA Encryption
440 m = pkcs_os2ip(EM) # 3.a)
441 c = self._rsaep(m) # 3.b)
442 C = pkcs_i2osp(c, k) # 3.c)
443
444 return C # 4)
445
446
447 def encrypt(self, m, t=None, h=None, mgf=None, L=None):
448 """
449 Encrypt message 'm' using 't' encryption scheme where 't' can be:
450
451 - None: the message 'm' is directly applied the RSAEP encryption
452 primitive, as described in PKCS#1 v2.1, i.e. RFC 3447
453 Sect 5.1.1. Simply put, the message undergo a modular
454 exponentiation using the public key. Additionnal method
455 parameters are just ignored.
456
457 - 'pkcs': the message 'm' is applied RSAES-PKCS1-V1_5-ENCRYPT encryption
458 scheme as described in section 7.2.1 of RFC 3447. In that
459 context, other parameters ('h', 'mgf', 'l') are not used.
460
461 - 'oaep': the message 'm' is applied the RSAES-OAEP-ENCRYPT encryption
462 scheme, as described in PKCS#1 v2.1, i.e. RFC 3447 Sect
463 7.1.1. In that context,
464
465 o 'h' parameter provides the name of the hash method to use.
466 Possible values are "md2", "md4", "md5", "sha1", "tls",
467 "sha224", "sha256", "sha384" and "sha512". if none is provided,
468 sha1 is used.
469
470 o 'mgf' is the mask generation function. By default, mgf
471 is derived from the provided hash function using the
472 generic MGF1 (see pkcs_mgf1() for details).
473
474 o 'L' is the optional label to be associated with the
475 message. If not provided, the default value is used, i.e
476 the empty string. No check is done on the input limitation
477 of the hash function regarding the size of 'L' (for
478 instance, 2^61 - 1 for SHA-1). You have been warned.
479 """
480
481 if t is None: # Raw encryption
482 m = pkcs_os2ip(m)
483 c = self._rsaep(m)
484 return pkcs_i2osp(c, self.modulusLen/8)
485
486 elif t == "pkcs":
487 return self._rsaes_pkcs1_v1_5_encrypt(m)
488
489 elif t == "oaep":
490 return self._rsaes_oaep_encrypt(m, h, mgf, L)
491
492 else:
493 warning("Key.encrypt(): Unknown encryption type (%s) provided" % t)
494 return None
495
496 ### Below are verification related methods
497
498 def _rsavp1(self, s):
499 """
500 Internal method providing raw RSA verification, i.e. simple modular
501 exponentiation of the given signature representative 'c', an integer
502 between 0 and n-1.
503
504 This is the signature verification primitive RSAVP1 described in
505 PKCS#1 v2.1, i.e. RFC 3447 Sect. 5.2.2.
506
507 Input:
508 s: signature representative, an integer between 0 and n-1,
509 where n is the key modulus.
510
511 Output:
512 message representative, an integer between 0 and n-1
513
514 Not intended to be used directly. Please, see verify() method.
515 """
516 return self._rsaep(s)
517
518 def _rsassa_pss_verify(self, M, S, h=None, mgf=None, sLen=None):
519 """
520 Implements RSASSA-PSS-VERIFY() function described in Sect 8.1.2
521 of RFC 3447
522
523 Input:
524 M: message whose signature is to be verified
525 S: signature to be verified, an octet string of length k, where k
526 is the length in octets of the RSA modulus n.
527
528 Output:
529 True is the signature is valid. False otherwise.
530 """
531
532 # Set default parameters if not provided
533 if h is None: # By default, sha1
534 h = "sha1"
535 if not _hashFuncParams.has_key(h):
536 warning("Key._rsassa_pss_verify(): unknown hash function "
537 "provided (%s)" % h)
538 return False
539 if mgf is None: # use mgf1 with underlying hash function
540 mgf = lambda x,y: pkcs_mgf1(x, y, h)
541 if sLen is None: # use Hash output length (A.2.3 of RFC 3447)
542 hLen = _hashFuncParams[h][0]
543 sLen = hLen
544
545 # 1) Length checking
546 modBits = self.modulusLen
547 k = modBits / 8
548 if len(S) != k:
549 return False
550
551 # 2) RSA verification
552 s = pkcs_os2ip(S) # 2.a)
553 m = self._rsavp1(s) # 2.b)
554 emLen = math.ceil((modBits - 1) / 8.) # 2.c)
555 EM = pkcs_i2osp(m, emLen)
556
557 # 3) EMSA-PSS verification
558 Result = pkcs_emsa_pss_verify(M, EM, modBits - 1, h, mgf, sLen)
559
560 return Result # 4)
561
562
563 def _rsassa_pkcs1_v1_5_verify(self, M, S, h):
564 """
565 Implements RSASSA-PKCS1-v1_5-VERIFY() function as described in
566 Sect. 8.2.2 of RFC 3447.
567
568 Input:
569 M: message whose signature is to be verified, an octet string
570 S: signature to be verified, an octet string of length k, where
571 k is the length in octets of the RSA modulus n
572 h: hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls',
573 'sha256', 'sha384').
574
575 Output:
576 True if the signature is valid. False otherwise.
577 """
578
579 # 1) Length checking
580 k = self.modulusLen / 8
581 if len(S) != k:
582 warning("invalid signature (len(S) != k)")
583 return False
584
585 # 2) RSA verification
586 s = pkcs_os2ip(S) # 2.a)
587 m = self._rsavp1(s) # 2.b)
588 EM = pkcs_i2osp(m, k) # 2.c)
589
590 # 3) EMSA-PKCS1-v1_5 encoding
591 EMPrime = pkcs_emsa_pkcs1_v1_5_encode(M, k, h)
592 if EMPrime is None:
593 warning("Key._rsassa_pkcs1_v1_5_verify(): unable to encode.")
594 return False
595
596 # 4) Comparison
597 return EM == EMPrime
598
599
600 def verify(self, M, S, t=None, h=None, mgf=None, sLen=None):
601 """
602 Verify alleged signature 'S' is indeed the signature of message 'M' using
603 't' signature scheme where 't' can be:
604
605 - None: the alleged signature 'S' is directly applied the RSAVP1 signature
606 primitive, as described in PKCS#1 v2.1, i.e. RFC 3447 Sect
607 5.2.1. Simply put, the provided signature is applied a moular
608 exponentiation using the public key. Then, a comparison of the
609 result is done against 'M'. On match, True is returned.
610 Additionnal method parameters are just ignored.
611
612 - 'pkcs': the alleged signature 'S' and message 'M' are applied
613 RSASSA-PKCS1-v1_5-VERIFY signature verification scheme as
614 described in Sect. 8.2.2 of RFC 3447. In that context,
615 the hash function name is passed using 'h'. Possible values are
616 "md2", "md4", "md5", "sha1", "tls", "sha224", "sha256", "sha384"
617 and "sha512". If none is provided, sha1 is used. Other additionnal
618 parameters are ignored.
619
620 - 'pss': the alleged signature 'S' and message 'M' are applied
621 RSASSA-PSS-VERIFY signature scheme as described in Sect. 8.1.2.
622 of RFC 3447. In that context,
623
624 o 'h' parameter provides the name of the hash method to use.
625 Possible values are "md2", "md4", "md5", "sha1", "tls", "sha224",
626 "sha256", "sha384" and "sha512". if none is provided, sha1
627 is used.
628
629 o 'mgf' is the mask generation function. By default, mgf
630 is derived from the provided hash function using the
631 generic MGF1 (see pkcs_mgf1() for details).
632
633 o 'sLen' is the length in octet of the salt. You can overload the
634 default value (the octet length of the hash value for provided
635 algorithm) by providing another one with that parameter.
636 """
637 if t is None: # RSAVP1
638 S = pkcs_os2ip(S)
639 n = self.modulus
640 if S > n-1:
641 warning("Signature to be verified is too long for key modulus")
642 return False
643 m = self._rsavp1(S)
644 if m is None:
645 return False
646 l = int(math.ceil(math.log(m, 2) / 8.)) # Hack
647 m = pkcs_i2osp(m, l)
648 return M == m
649
650 elif t == "pkcs": # RSASSA-PKCS1-v1_5-VERIFY
651 if h is None:
652 h = "sha1"
653 return self._rsassa_pkcs1_v1_5_verify(M, S, h)
654
655 elif t == "pss": # RSASSA-PSS-VERIFY
656 return self._rsassa_pss_verify(M, S, h, mgf, sLen)
657
658 else:
659 warning("Key.verify(): Unknown signature type (%s) provided" % t)
660 return None
661
662class _DecryptAndSignMethods:
663 ### Below are decryption related methods. Encryption ones are inherited
664 ### from PubKey
665
666 def _rsadp(self, c):
667 """
668 Internal method providing raw RSA decryption, i.e. simple modular
669 exponentiation of the given ciphertext representative 'c', a long
670 between 0 and n-1.
671
672 This is the decryption primitive RSADP described in PKCS#1 v2.1,
673 i.e. RFC 3447 Sect. 5.1.2.
674
675 Input:
676 c: ciphertest representative, a long between 0 and n-1, where
677 n is the key modulus.
678
679 Output:
680 ciphertext representative, a long between 0 and n-1
681
682 Not intended to be used directly. Please, see encrypt() method.
683 """
684
685 n = self.modulus
686 if type(c) is int:
687 c = long(c)
688 if type(c) is not long or c > n-1:
689 warning("Key._rsaep() expects a long between 0 and n-1")
690 return None
691
692 return self.key.decrypt(c)
693
694
695 def _rsaes_pkcs1_v1_5_decrypt(self, C):
696 """
697 Implements RSAES-PKCS1-V1_5-DECRYPT() function described in section
698 7.2.2 of RFC 3447.
699
700 Input:
701 C: ciphertext to be decrypted, an octet string of length k, where
702 k is the length in octets of the RSA modulus n.
703
704 Output:
705 an octet string of length k at most k - 11
706
707 on error, None is returned.
708 """
709
710 # 1) Length checking
711 cLen = len(C)
712 k = self.modulusLen / 8
713 if cLen != k or k < 11:
714 warning("Key._rsaes_pkcs1_v1_5_decrypt() decryption error "
715 "(cLen != k or k < 11)")
716 return None
717
718 # 2) RSA decryption
719 c = pkcs_os2ip(C) # 2.a)
720 m = self._rsadp(c) # 2.b)
721 EM = pkcs_i2osp(m, k) # 2.c)
722
723 # 3) EME-PKCS1-v1_5 decoding
724
725 # I am aware of the note at the end of 7.2.2 regarding error
726 # conditions reporting but the one provided below are for _local_
727 # debugging purposes. --arno
728
729 if EM[0] != '\x00':
730 warning("Key._rsaes_pkcs1_v1_5_decrypt(): decryption error "
731 "(first byte is not 0x00)")
732 return None
733
734 if EM[1] != '\x02':
735 warning("Key._rsaes_pkcs1_v1_5_decrypt(): decryption error "
736 "(second byte is not 0x02)")
737 return None
738
739 tmp = EM[2:].split('\x00', 1)
740 if len(tmp) != 2:
741 warning("Key._rsaes_pkcs1_v1_5_decrypt(): decryption error "
742 "(no 0x00 to separate PS from M)")
743 return None
744
745 PS, M = tmp
746 if len(PS) < 8:
747 warning("Key._rsaes_pkcs1_v1_5_decrypt(): decryption error "
748 "(PS is less than 8 byte long)")
749 return None
750
751 return M # 4)
752
753
754 def _rsaes_oaep_decrypt(self, C, h=None, mgf=None, L=None):
755 """
756 Internal method providing RSAES-OAEP-DECRYPT as defined in Sect.
757 7.1.2 of RFC 3447. Not intended to be used directly. Please, see
758 encrypt() method for type "OAEP".
759
760
761 Input:
762 C : ciphertext to be decrypted, an octet string of length k, where
763 k = 2*hLen + 2 (k denotes the length in octets of the RSA modulus
764 and hLen the length in octets of the hash function output)
765 h : hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls',
766 'sha256', 'sha384'). 'sha1' is used if none is provided.
767 mgf: the mask generation function f : seed, maskLen -> mask
768 L : optional label whose association with the message is to be
769 verified; the default value for L, if not provided is the empty
770 string.
771
772 Output:
773 message, an octet string of length k mLen, where mLen <= k - 2*hLen - 2
774
775 On error, None is returned.
776 """
777 # The steps below are the one described in Sect. 7.1.2 of RFC 3447.
778
779 # 1) Length Checking
780 # 1.a) is not done
781 if h is None:
782 h = "sha1"
783 if not _hashFuncParams.has_key(h):
784 warning("Key._rsaes_oaep_decrypt(): unknown hash function %s.", h)
785 return None
786 hLen = _hashFuncParams[h][0]
787 hFun = _hashFuncParams[h][1]
788 k = self.modulusLen / 8
789 cLen = len(C)
790 if cLen != k: # 1.b)
791 warning("Key._rsaes_oaep_decrypt(): decryption error. "
792 "(cLen != k)")
793 return None
794 if k < 2*hLen + 2:
795 warning("Key._rsaes_oaep_decrypt(): decryption error. "
796 "(k < 2*hLen + 2)")
797 return None
798
799 # 2) RSA decryption
800 c = pkcs_os2ip(C) # 2.a)
801 m = self._rsadp(c) # 2.b)
802 EM = pkcs_i2osp(m, k) # 2.c)
803
804 # 3) EME-OAEP decoding
805 if L is None: # 3.a)
806 L = ""
807 lHash = hFun(L)
808 Y = EM[:1] # 3.b)
809 if Y != '\x00':
810 warning("Key._rsaes_oaep_decrypt(): decryption error. "
811 "(Y is not zero)")
812 return None
813 maskedSeed = EM[1:1+hLen]
814 maskedDB = EM[1+hLen:]
815 if mgf is None:
816 mgf = lambda x,y: pkcs_mgf1(x, y, h)
817 seedMask = mgf(maskedDB, hLen) # 3.c)
818 seed = strxor(maskedSeed, seedMask) # 3.d)
819 dbMask = mgf(seed, k - hLen - 1) # 3.e)
820 DB = strxor(maskedDB, dbMask) # 3.f)
821
822 # I am aware of the note at the end of 7.1.2 regarding error
823 # conditions reporting but the one provided below are for _local_
824 # debugging purposes. --arno
825
826 lHashPrime = DB[:hLen] # 3.g)
827 tmp = DB[hLen:].split('\x01', 1)
828 if len(tmp) != 2:
829 warning("Key._rsaes_oaep_decrypt(): decryption error. "
830 "(0x01 separator not found)")
831 return None
832 PS, M = tmp
833 if PS != '\x00'*len(PS):
834 warning("Key._rsaes_oaep_decrypt(): decryption error. "
835 "(invalid padding string)")
836 return None
837 if lHash != lHashPrime:
838 warning("Key._rsaes_oaep_decrypt(): decryption error. "
839 "(invalid hash)")
840 return None
841 return M # 4)
842
843
844 def decrypt(self, C, t=None, h=None, mgf=None, L=None):
845 """
846 Decrypt ciphertext 'C' using 't' decryption scheme where 't' can be:
847
848 - None: the ciphertext 'C' is directly applied the RSADP decryption
849 primitive, as described in PKCS#1 v2.1, i.e. RFC 3447
850 Sect 5.1.2. Simply, put the message undergo a modular
851 exponentiation using the private key. Additionnal method
852 parameters are just ignored.
853
854 - 'pkcs': the ciphertext 'C' is applied RSAES-PKCS1-V1_5-DECRYPT
855 decryption scheme as described in section 7.2.2 of RFC 3447.
856 In that context, other parameters ('h', 'mgf', 'l') are not
857 used.
858
859 - 'oaep': the ciphertext 'C' is applied the RSAES-OAEP-DECRYPT decryption
860 scheme, as described in PKCS#1 v2.1, i.e. RFC 3447 Sect
861 7.1.2. In that context,
862
863 o 'h' parameter provides the name of the hash method to use.
864 Possible values are "md2", "md4", "md5", "sha1", "tls",
865 "sha224", "sha256", "sha384" and "sha512". if none is provided,
866 sha1 is used by default.
867
868 o 'mgf' is the mask generation function. By default, mgf
869 is derived from the provided hash function using the
870 generic MGF1 (see pkcs_mgf1() for details).
871
872 o 'L' is the optional label to be associated with the
873 message. If not provided, the default value is used, i.e
874 the empty string. No check is done on the input limitation
875 of the hash function regarding the size of 'L' (for
876 instance, 2^61 - 1 for SHA-1). You have been warned.
877 """
878 if t is None:
879 C = pkcs_os2ip(C)
880 c = self._rsadp(C)
881 l = int(math.ceil(math.log(c, 2) / 8.)) # Hack
882 return pkcs_i2osp(c, l)
883
884 elif t == "pkcs":
885 return self._rsaes_pkcs1_v1_5_decrypt(C)
886
887 elif t == "oaep":
888 return self._rsaes_oaep_decrypt(C, h, mgf, L)
889
890 else:
891 warning("Key.decrypt(): Unknown decryption type (%s) provided" % t)
892 return None
893
894 ### Below are signature related methods. Verification ones are inherited from
895 ### PubKey
896
897 def _rsasp1(self, m):
898 """
899 Internal method providing raw RSA signature, i.e. simple modular
900 exponentiation of the given message representative 'm', an integer
901 between 0 and n-1.
902
903 This is the signature primitive RSASP1 described in PKCS#1 v2.1,
904 i.e. RFC 3447 Sect. 5.2.1.
905
906 Input:
907 m: message representative, an integer between 0 and n-1, where
908 n is the key modulus.
909
910 Output:
911 signature representative, an integer between 0 and n-1
912
913 Not intended to be used directly. Please, see sign() method.
914 """
915 return self._rsadp(m)
916
917
918 def _rsassa_pss_sign(self, M, h=None, mgf=None, sLen=None):
919 """
920 Implements RSASSA-PSS-SIGN() function described in Sect. 8.1.1 of
921 RFC 3447.
922
923 Input:
924 M: message to be signed, an octet string
925
926 Output:
927 signature, an octet string of length k, where k is the length in
928 octets of the RSA modulus n.
929
930 On error, None is returned.
931 """
932
933 # Set default parameters if not provided
934 if h is None: # By default, sha1
935 h = "sha1"
936 if not _hashFuncParams.has_key(h):
937 warning("Key._rsassa_pss_sign(): unknown hash function "
938 "provided (%s)" % h)
939 return None
940 if mgf is None: # use mgf1 with underlying hash function
941 mgf = lambda x,y: pkcs_mgf1(x, y, h)
942 if sLen is None: # use Hash output length (A.2.3 of RFC 3447)
943 hLen = _hashFuncParams[h][0]
944 sLen = hLen
945
946 # 1) EMSA-PSS encoding
947 modBits = self.modulusLen
948 k = modBits / 8
949 EM = pkcs_emsa_pss_encode(M, modBits - 1, h, mgf, sLen)
950 if EM is None:
951 warning("Key._rsassa_pss_sign(): unable to encode")
952 return None
953
954 # 2) RSA signature
955 m = pkcs_os2ip(EM) # 2.a)
956 s = self._rsasp1(m) # 2.b)
957 S = pkcs_i2osp(s, k) # 2.c)
958
959 return S # 3)
960
961
962 def _rsassa_pkcs1_v1_5_sign(self, M, h):
963 """
964 Implements RSASSA-PKCS1-v1_5-SIGN() function as described in
965 Sect. 8.2.1 of RFC 3447.
966
967 Input:
968 M: message to be signed, an octet string
969 h: hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls'
970 'sha256', 'sha384').
971
972 Output:
973 the signature, an octet string.
974 """
975
976 # 1) EMSA-PKCS1-v1_5 encoding
977 k = self.modulusLen / 8
978 EM = pkcs_emsa_pkcs1_v1_5_encode(M, k, h)
979 if EM is None:
980 warning("Key._rsassa_pkcs1_v1_5_sign(): unable to encode")
981 return None
982
983 # 2) RSA signature
984 m = pkcs_os2ip(EM) # 2.a)
985 s = self._rsasp1(m) # 2.b)
986 S = pkcs_i2osp(s, k) # 2.c)
987
988 return S # 3)
989
990
991 def sign(self, M, t=None, h=None, mgf=None, sLen=None):
992 """
993 Sign message 'M' using 't' signature scheme where 't' can be:
994
995 - None: the message 'M' is directly applied the RSASP1 signature
996 primitive, as described in PKCS#1 v2.1, i.e. RFC 3447 Sect
997 5.2.1. Simply put, the message undergo a modular exponentiation
998 using the private key. Additionnal method parameters are just
999 ignored.
1000
1001 - 'pkcs': the message 'M' is applied RSASSA-PKCS1-v1_5-SIGN signature
1002 scheme as described in Sect. 8.2.1 of RFC 3447. In that context,
1003 the hash function name is passed using 'h'. Possible values are
1004 "md2", "md4", "md5", "sha1", "tls", "sha224", "sha256", "sha384"
1005 and "sha512". If none is provided, sha1 is used. Other additionnal
1006 parameters are ignored.
1007
1008 - 'pss' : the message 'M' is applied RSASSA-PSS-SIGN signature scheme as
1009 described in Sect. 8.1.1. of RFC 3447. In that context,
1010
1011 o 'h' parameter provides the name of the hash method to use.
1012 Possible values are "md2", "md4", "md5", "sha1", "tls", "sha224",
1013 "sha256", "sha384" and "sha512". if none is provided, sha1
1014 is used.
1015
1016 o 'mgf' is the mask generation function. By default, mgf
1017 is derived from the provided hash function using the
1018 generic MGF1 (see pkcs_mgf1() for details).
1019
1020 o 'sLen' is the length in octet of the salt. You can overload the
1021 default value (the octet length of the hash value for provided
1022 algorithm) by providing another one with that parameter.
1023 """
1024
1025 if t is None: # RSASP1
1026 M = pkcs_os2ip(M)
1027 n = self.modulus
1028 if M > n-1:
1029 warning("Message to be signed is too long for key modulus")
1030 return None
1031 s = self._rsasp1(M)
1032 if s is None:
1033 return None
1034 return pkcs_i2osp(s, self.modulusLen/8)
1035
1036 elif t == "pkcs": # RSASSA-PKCS1-v1_5-SIGN
1037 if h is None:
1038 h = "sha1"
1039 return self._rsassa_pkcs1_v1_5_sign(M, h)
1040
1041 elif t == "pss": # RSASSA-PSS-SIGN
1042 return self._rsassa_pss_sign(M, h, mgf, sLen)
1043
1044 else:
1045 warning("Key.sign(): Unknown signature type (%s) provided" % t)
1046 return None
1047
1048class Key(_DecryptAndSignMethods, _EncryptAndVerify):
1049
1050 def __init__(self, pem_data):
1051 self.key = RSA.importKey(pem_data)
1052 self.modulus = self.key.key.n
1053 self.modulusLen = self.key.key.size() + 1
1054 self.privExp = self.key.key.d
1055 self.pubExp = self.key.key.e
1056 self.prime1 = self.key.key.p
1057 self.prime2 = self.key.key.q
1058 self.exponent1 = 0
1059 self.exponent2 = 0
1060 self.coefficient = self.key.key.u