Skip to content

Commit 0da8532

Browse files
committed
decryptpdf.py: added some clarifying comments
1 parent 4a8cd38 commit 0da8532

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

decryptpdf.py

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -34,31 +34,36 @@ def findtrailer(stk):
3434
retnext = True
3535

3636
pdfname, certname, certpw = sys.argv[1:]
37-
stk, objs = parsepdf(args, UngetStream(open(pdfname, "rb")))
3837

3938
certpw += '\x00'
4039
certpw = certpw.encode('utf-16be')
4140

4241
privkey = usercert = None
4342

43+
# read the private and public keys from the PKCS12 file
4444
with open(certname, "rb") as fh:
4545
""" tries to decrypt any encrypted blobs from a pkcs12 encoded keybag """
4646
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
4848
keysize = 24
49-
else:
49+
else: # 1.2.840.113549.1.12.1.6 -> pbewithSHAAnd40BitRC2CBC
5050
keysize = 5
5151
key = genkey(salt, 1, certpw, n, keysize)
5252
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)))
5455
data = des3(data, key, iv)
55-
print("priv", b2a_hex(data[-16:]))
56+
print("priv", b2a_hex(data))
5657
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)))
5860
data = rc2(data, key, iv)
59-
print("cert", b2a_hex(data[-16:]))
61+
print("cert", b2a_hex(data))
6062
usercert = data
6163

64+
# parse the PDF into tokens
65+
stk, objs = parsepdf(args, UngetStream(open(pdfname, "rb")))
66+
6267
trailer = findtrailer(stk)
6368
encref = trailer['Encrypt']
6469
enc = encref.dereference(objs)
@@ -76,7 +81,9 @@ def objkey(oid, gen, mkey):
7681
""" generate decryption key for the specified object """
7782
return md5(mkey[:16] + struct.pack("<HBH", oid&0xFFFF, oid>>16, gen) + b'sAlT')
7883

84+
# now for all keys found in the PDF's Recipients dictionary try to extract a masterkey.
7985
for (rsadata, symalg, num, iv, symdata) in XXXXdecoder(rcp[0].asbytes()):
86+
# first decrypt using the rsa private key
8087
decrypted = i2bin(pow(b2int(rsadata), privkey[2], privkey[0]), len(rsadata))
8188
if decrypted[:2] != b'\x00\x02':
8289
raise Exception("failed rsa decrypted")

0 commit comments

Comments
 (0)