@@ -34,31 +34,36 @@ def findtrailer(stk):
34
34
retnext = True
35
35
36
36
pdfname , certname , certpw = sys .argv [1 :]
37
- stk , objs = parsepdf (args , UngetStream (open (pdfname , "rb" )))
38
37
39
38
certpw += '\x00 '
40
39
certpw = certpw .encode ('utf-16be' )
41
40
42
41
privkey = usercert = None
43
42
43
+ # read the private and public keys from the PKCS12 file
44
44
with open (certname , "rb" ) as fh :
45
45
""" tries to decrypt any encrypted blobs from a pkcs12 encoded keybag """
46
46
for (alg , salt , n , data ) in pkcs12decoder (fh .read ()):
47
- if alg == '1.2.840.113549.1.12.1.3' :
47
+ if alg == '1.2.840.113549.1.12.1.3' : # pbeWithSHAAnd3-KeyTripleDES-CBC
48
48
keysize = 24
49
- else :
49
+ else : # 1.2.840.113549.1.12.1.6 -> pbewithSHAAnd40BitRC2CBC
50
50
keysize = 5
51
51
key = genkey (salt , 1 , certpw , n , keysize )
52
52
iv = genkey (salt , 2 , certpw , n , 8 )
53
- if alg == '1.2.840.113549.1.12.1.3' :
53
+ if alg == '1.2.840.113549.1.12.1.3' : # pbeWithSHAAnd3-KeyTripleDES-CBC
54
+ print ("3des - salt = %s -> iv = %s, key = %s" % (b2a_hex (salt ), b2a_hex (iv ), b2a_hex (key )))
54
55
data = des3 (data , key , iv )
55
- print ("priv" , b2a_hex (data [ - 16 :] ))
56
+ print ("priv" , b2a_hex (data ))
56
57
privkey = privdecoder (data )
57
- else :
58
+ else : # pbewithSHAAnd40BitRC2CBC
59
+ print ("rc2 - salt = %s -> iv = %s, key = %s" % (b2a_hex (salt ), b2a_hex (iv ), b2a_hex (key )))
58
60
data = rc2 (data , key , iv )
59
- print ("cert" , b2a_hex (data [ - 16 :] ))
61
+ print ("cert" , b2a_hex (data ))
60
62
usercert = data
61
63
64
+ # parse the PDF into tokens
65
+ stk , objs = parsepdf (args , UngetStream (open (pdfname , "rb" )))
66
+
62
67
trailer = findtrailer (stk )
63
68
encref = trailer ['Encrypt' ]
64
69
enc = encref .dereference (objs )
@@ -76,7 +81,9 @@ def objkey(oid, gen, mkey):
76
81
""" generate decryption key for the specified object """
77
82
return md5 (mkey [:16 ] + struct .pack ("<HBH" , oid & 0xFFFF , oid >> 16 , gen ) + b'sAlT' )
78
83
84
+ # now for all keys found in the PDF's Recipients dictionary try to extract a masterkey.
79
85
for (rsadata , symalg , num , iv , symdata ) in XXXXdecoder (rcp [0 ].asbytes ()):
86
+ # first decrypt using the rsa private key
80
87
decrypted = i2bin (pow (b2int (rsadata ), privkey [2 ], privkey [0 ]), len (rsadata ))
81
88
if decrypted [:2 ] != b'\x00 \x02 ' :
82
89
raise Exception ("failed rsa decrypted" )
0 commit comments