author | rptlab |
Tue, 30 Apr 2013 14:28:14 +0100 | |
branch | py33 |
changeset 3723 | 99aa837b6703 |
parent 3721 | 0c93dd8ff567 |
child 3746 | b7143a1c34c6 |
permissions | -rw-r--r-- |
3617 | 1 |
#copyright ReportLab Europe Limited. 2000-2012 |
3035 | 2 |
#see license.txt for license details |
3 |
__version__=''' $Id$ ''' |
|
4 |
||
5 |
"""helpers for pdf encryption/decryption""" |
|
6 |
||
3723
99aa837b6703
second stage of port to Python 3.3; working hello world
rptlab
parents:
3721
diff
changeset
|
7 |
import sys, os |
3098
318ba6cb2cb1
reportlab: fix md5 usage in pdfencrypt.py & fontfinder.py
rgbecker
parents:
3073
diff
changeset
|
8 |
try: |
318ba6cb2cb1
reportlab: fix md5 usage in pdfencrypt.py & fontfinder.py
rgbecker
parents:
3073
diff
changeset
|
9 |
from hashlib import md5 |
318ba6cb2cb1
reportlab: fix md5 usage in pdfencrypt.py & fontfinder.py
rgbecker
parents:
3073
diff
changeset
|
10 |
except ImportError: |
318ba6cb2cb1
reportlab: fix md5 usage in pdfencrypt.py & fontfinder.py
rgbecker
parents:
3073
diff
changeset
|
11 |
from md5 import md5 |
318ba6cb2cb1
reportlab: fix md5 usage in pdfencrypt.py & fontfinder.py
rgbecker
parents:
3073
diff
changeset
|
12 |
|
3723
99aa837b6703
second stage of port to Python 3.3; working hello world
rptlab
parents:
3721
diff
changeset
|
13 |
from reportlab.lib.utils import getBytesIO |
3035 | 14 |
import tempfile |
15 |
||
16 |
from reportlab.pdfgen.canvas import Canvas |
|
17 |
from reportlab.pdfbase import pdfutils |
|
18 |
from reportlab.platypus.flowables import Flowable |
|
19 |
||
20 |
#AR debug hooks - leaving in for now |
|
21 |
CLOBBERID = 0 # set a constant Doc ID to allow comparison with other software like iText |
|
22 |
CLOBBERPERMISSIONS = 0 |
|
23 |
DEBUG = 0 # print stuff to trace calculations |
|
24 |
||
25 |
# permission bits |
|
26 |
reserved1 = 1 # bit 1 must be 0 |
|
27 |
reserved2 = 1<<1 # bit 2 must be 0 |
|
28 |
printable = 1<<2 |
|
29 |
modifiable = 1<<3 |
|
30 |
copypastable = 1<<4 |
|
31 |
annotatable = 1<<5 |
|
32 |
# others [7..32] are reserved, must be 1 |
|
33 |
higherbits = 0 |
|
34 |
for i in range(6,31): |
|
35 |
higherbits = higherbits | (1<<i) |
|
36 |
||
37 |
||
38 |
# no encryption |
|
39 |
class StandardEncryption: |
|
40 |
prepared = 0 |
|
41 |
def __init__(self, userPassword, ownerPassword=None, canPrint=1, canModify=1, canCopy=1, canAnnotate=1, strength=40): |
|
3053
e238a5851dd0
Added docstring to the reportlab.lib.pdfencrypt.StandardEncryption constructor.
jonas
parents:
3035
diff
changeset
|
42 |
''' |
e238a5851dd0
Added docstring to the reportlab.lib.pdfencrypt.StandardEncryption constructor.
jonas
parents:
3035
diff
changeset
|
43 |
This class defines the encryption properties to be used while creating a pdf document. |
e238a5851dd0
Added docstring to the reportlab.lib.pdfencrypt.StandardEncryption constructor.
jonas
parents:
3035
diff
changeset
|
44 |
Once initiated, a StandardEncryption object can be applied to a Canvas or a BaseDocTemplate. |
e238a5851dd0
Added docstring to the reportlab.lib.pdfencrypt.StandardEncryption constructor.
jonas
parents:
3035
diff
changeset
|
45 |
The userPassword parameter sets the user password on the encrypted pdf. |
e238a5851dd0
Added docstring to the reportlab.lib.pdfencrypt.StandardEncryption constructor.
jonas
parents:
3035
diff
changeset
|
46 |
The ownerPassword parameter sets the owner password on the encrypted pdf. |
e238a5851dd0
Added docstring to the reportlab.lib.pdfencrypt.StandardEncryption constructor.
jonas
parents:
3035
diff
changeset
|
47 |
The boolean flags canPrint, canModify, canCopy, canAnnotate determine wether a user can |
e238a5851dd0
Added docstring to the reportlab.lib.pdfencrypt.StandardEncryption constructor.
jonas
parents:
3035
diff
changeset
|
48 |
perform the corresponding actions on the pdf when only a user password has been supplied. |
e238a5851dd0
Added docstring to the reportlab.lib.pdfencrypt.StandardEncryption constructor.
jonas
parents:
3035
diff
changeset
|
49 |
If the user supplies the owner password while opening the pdf, all actions can be performed regardless |
e238a5851dd0
Added docstring to the reportlab.lib.pdfencrypt.StandardEncryption constructor.
jonas
parents:
3035
diff
changeset
|
50 |
of the flags. |
e238a5851dd0
Added docstring to the reportlab.lib.pdfencrypt.StandardEncryption constructor.
jonas
parents:
3035
diff
changeset
|
51 |
Note that the security provided by these encryption settings (and even more so for the flags) is very weak. |
e238a5851dd0
Added docstring to the reportlab.lib.pdfencrypt.StandardEncryption constructor.
jonas
parents:
3035
diff
changeset
|
52 |
''' |
3035 | 53 |
self.ownerPassword = ownerPassword |
54 |
self.userPassword = userPassword |
|
55 |
if strength == 40: |
|
56 |
self.revision = 2 |
|
57 |
elif strength == 128: |
|
58 |
self.revision = 3 |
|
59 |
self.canPrint = canPrint |
|
60 |
self.canModify = canModify |
|
61 |
self.canCopy = canCopy |
|
62 |
self.canAnnotate = canAnnotate |
|
63 |
self.O = self.U = self.P = self.key = None |
|
64 |
def setAllPermissions(self, value): |
|
65 |
self.canPrint = \ |
|
66 |
self.canModify = \ |
|
67 |
self.canCopy = \ |
|
68 |
self.canAnnotate = value |
|
69 |
def permissionBits(self): |
|
70 |
p = 0 |
|
71 |
if self.canPrint: p = p | printable |
|
72 |
if self.canModify: p = p | modifiable |
|
73 |
if self.canCopy: p = p | copypastable |
|
74 |
if self.canAnnotate: p = p | annotatable |
|
75 |
p = p | higherbits |
|
76 |
return p |
|
77 |
def encode(self, t): |
|
78 |
"encode a string, stream, text" |
|
79 |
if not self.prepared: |
|
3721 | 80 |
raise ValueError("encryption not prepared!") |
3035 | 81 |
if self.objnum is None: |
3721 | 82 |
raise ValueError("not registered in PDF object") |
3035 | 83 |
return encodePDF(self.key, self.objnum, self.version, t, revision=self.revision) |
84 |
def prepare(self, document, overrideID=None): |
|
85 |
# get ready to do encryption |
|
3721 | 86 |
if DEBUG: print('StandardEncryption.prepare(...) - revision %d' % self.revision) |
3035 | 87 |
if self.prepared: |
3721 | 88 |
raise ValueError("encryption already prepared!") |
3035 | 89 |
# get the unescaped string value of the document id (first array element). |
90 |
# we allow one to be passed in instead to permit reproducible tests |
|
91 |
# of our algorithm, but in real life overrideID will always be None |
|
92 |
if overrideID: |
|
93 |
internalID = overrideID |
|
94 |
else: |
|
95 |
externalID = document.ID() # initialize it... |
|
96 |
internalID = document.signature.digest() |
|
97 |
#AR debugging |
|
98 |
if CLOBBERID: |
|
99 |
internalID = "xxxxxxxxxxxxxxxx" |
|
100 |
||
101 |
if DEBUG: |
|
3721 | 102 |
print('userPassword = %s' % self.userPassword) |
103 |
print('ownerPassword = %s' % self.ownerPassword) |
|
104 |
print('internalID = %s' % internalID) |
|
105 |
self.P = int(self.permissionBits() - 2**31) |
|
3035 | 106 |
if CLOBBERPERMISSIONS: self.P = -44 # AR hack |
107 |
if DEBUG: |
|
3721 | 108 |
print("self.P = %s" % repr(self.P)) |
3035 | 109 |
self.O = computeO(self.userPassword, self.ownerPassword, self.revision) |
110 |
if DEBUG: |
|
3721 | 111 |
print("self.O (as hex) = %s" % hexText(self.O)) |
3035 | 112 |
|
113 |
#print "\nself.O", self.O, repr(self.O) |
|
114 |
self.key = encryptionkey(self.userPassword, self.O, self.P, internalID, revision=self.revision) |
|
115 |
if DEBUG: |
|
3721 | 116 |
print("self.key (hex) = %s" % hexText(self.key)) |
3035 | 117 |
self.U = computeU(self.key, revision=self.revision, documentId=internalID) |
118 |
if DEBUG: |
|
3721 | 119 |
print("self.U (as hex) = %s" % hexText(self.U)) |
3035 | 120 |
self.objnum = self.version = None |
121 |
self.prepared = 1 |
|
122 |
def register(self, objnum, version): |
|
123 |
# enter a new direct object |
|
124 |
if not self.prepared: |
|
3721 | 125 |
raise ValueError("encryption not prepared!") |
3035 | 126 |
self.objnum = objnum |
127 |
self.version = version |
|
128 |
def info(self): |
|
129 |
# the representation of self in file if any (should be None or PDFDict) |
|
130 |
if not self.prepared: |
|
3721 | 131 |
raise ValueError("encryption not prepared!") |
3035 | 132 |
return StandardEncryptionDictionary(O=self.O, U=self.U, P=self.P, revision=self.revision) |
133 |
||
3099 | 134 |
class StandardEncryptionDictionary: |
3035 | 135 |
__RefOnly__ = 1 |
3101
ec18b8a44cd2
reportlab:attempt to make PDF objects more explicit
rgbecker
parents:
3099
diff
changeset
|
136 |
__PDFObject__ = True |
3035 | 137 |
def __init__(self, O, U, P, revision): |
138 |
self.O, self.U, self.P = O,U,P |
|
139 |
self.revision = revision |
|
140 |
def format(self, document): |
|
141 |
# use a dummy document to bypass encryption |
|
142 |
from reportlab.pdfbase.pdfdoc import DummyDoc, PDFDictionary, PDFString, PDFName |
|
143 |
dummy = DummyDoc() |
|
144 |
dict = {"Filter": PDFName("Standard"), |
|
145 |
"O": hexText(self.O), #PDFString(self.O), |
|
146 |
"U": hexText(self.U), #PDFString(self.U), |
|
147 |
"P": self.P} |
|
148 |
if self.revision == 3: |
|
149 |
dict['Length'] = 128 |
|
150 |
dict['R'] = 3 |
|
151 |
dict['V'] = 2 |
|
152 |
else: |
|
153 |
dict['R'] = 2 |
|
154 |
dict['V'] = 1 |
|
155 |
pdfdict = PDFDictionary(dict) |
|
156 |
return pdfdict.format(dummy) |
|
157 |
||
158 |
# from pdf spec |
|
159 |
padding = """ |
|
160 |
28 BF 4E 5E 4E 75 8A 41 64 00 4E 56 FF FA 01 08 |
|
161 |
2E 2E 00 B6 D0 68 3E 80 2F 0C A9 FE 64 53 69 7A |
|
162 |
""" |
|
163 |
if hasattr(padding,'join'): |
|
164 |
def xorKey(num,key): |
|
165 |
"xor's each bytes of the key with the number, which is <256" |
|
166 |
if num==0: return key |
|
167 |
from operator import xor |
|
3721 | 168 |
return ''.join(map(chr,list(map(xor,len(key)*[num],list(map(ord,key)))))) |
3035 | 169 |
else: |
170 |
def xorKey(num, key): |
|
171 |
"xor's each bytes of the key with the number, which is <256" |
|
172 |
from operator import xor |
|
173 |
out = '' |
|
174 |
for ch in key: |
|
175 |
out = out + chr(xor(num, ord(ch))) |
|
176 |
return out |
|
177 |
||
178 |
def hexchar(x): |
|
3723
99aa837b6703
second stage of port to Python 3.3; working hello world
rptlab
parents:
3721
diff
changeset
|
179 |
return chr(int(x, 16)) |
3035 | 180 |
|
181 |
def hexText(text): |
|
182 |
"a legitimate way to show strings in PDF" |
|
183 |
out = '' |
|
184 |
for char in text: |
|
185 |
out = out + '%02X' % ord(char) |
|
186 |
return '<' + out + '>' |
|
187 |
||
188 |
def unHexText(hexText): |
|
189 |
assert hexText[0] == '<', 'bad hex text' |
|
190 |
assert hexText[-1] == '>', 'bad hex text' |
|
191 |
hexText = hexText[1:-1] |
|
192 |
out = '' |
|
3326 | 193 |
for i in range(int(len(hexText)/2.0)): |
3035 | 194 |
slice = hexText[i*2: i*2+2] |
195 |
char = chr(eval('0x'+slice)) |
|
196 |
out = out + char |
|
197 |
return out |
|
198 |
||
3723
99aa837b6703
second stage of port to Python 3.3; working hello world
rptlab
parents:
3721
diff
changeset
|
199 |
PadString = ''.join(map(hexchar, padding.strip().split())) |
3035 | 200 |
|
201 |
def encryptionkey(password, OwnerKey, Permissions, FileId1, revision=2): |
|
202 |
# FileId1 is first string of the fileid array |
|
203 |
# add padding string |
|
204 |
#AR force same as iText example |
|
205 |
#Permissions = -1836 #int(Permissions - 2**31) |
|
206 |
password = password + PadString |
|
207 |
# truncate to 32 bytes |
|
208 |
password = password[:32] |
|
209 |
# translate permissions to string, low order byte first |
|
210 |
p = Permissions# + 2**32L |
|
211 |
permissionsString = "" |
|
212 |
for i in range(4): |
|
213 |
byte = (p & 0xff) # seems to match what iText does |
|
214 |
p = p>>8 |
|
215 |
permissionsString = permissionsString + chr(byte % 256) |
|
216 |
||
3098
318ba6cb2cb1
reportlab: fix md5 usage in pdfencrypt.py & fontfinder.py
rgbecker
parents:
3073
diff
changeset
|
217 |
hash = md5(password) |
3035 | 218 |
hash.update(OwnerKey) |
219 |
hash.update(permissionsString) |
|
220 |
hash.update(FileId1) |
|
221 |
||
222 |
md5output = hash.digest() |
|
223 |
||
224 |
if revision==2: |
|
225 |
key = md5output[:5] |
|
226 |
elif revision==3: #revision 3 algorithm - loop 50 times |
|
227 |
for x in range(50): |
|
3098
318ba6cb2cb1
reportlab: fix md5 usage in pdfencrypt.py & fontfinder.py
rgbecker
parents:
3073
diff
changeset
|
228 |
md5output = md5(md5output).digest() |
3035 | 229 |
key = md5output[:16] |
3721 | 230 |
if DEBUG: print('encryptionkey(%s,%s,%s,%s,%s)==>%s' % tuple([hexText(str(x)) for x in (password, OwnerKey, Permissions, FileId1, revision, key)])) |
3035 | 231 |
return key |
232 |
||
233 |
def computeO(userPassword, ownerPassword, revision): |
|
3071 | 234 |
from reportlab.lib.arciv import ArcIV |
3098
318ba6cb2cb1
reportlab: fix md5 usage in pdfencrypt.py & fontfinder.py
rgbecker
parents:
3073
diff
changeset
|
235 |
#print 'digest of hello is %s' % md5('hello').digest() |
3035 | 236 |
assert revision in (2,3), 'Unknown algorithm revision %s' % revision |
237 |
if ownerPassword in (None, ''): |
|
238 |
ownerPassword = userPassword |
|
239 |
||
240 |
ownerPad = ownerPassword + PadString |
|
241 |
ownerPad = ownerPad[0:32] |
|
242 |
||
243 |
password = userPassword + PadString |
|
244 |
userPad = password[:32] |
|
245 |
||
3098
318ba6cb2cb1
reportlab: fix md5 usage in pdfencrypt.py & fontfinder.py
rgbecker
parents:
3073
diff
changeset
|
246 |
digest = md5(ownerPad).digest() |
3035 | 247 |
if revision == 2: |
3071 | 248 |
O = ArcIV(digest[:5]).encode(userPad) |
3035 | 249 |
elif revision == 3: |
250 |
for i in range(50): |
|
3098
318ba6cb2cb1
reportlab: fix md5 usage in pdfencrypt.py & fontfinder.py
rgbecker
parents:
3073
diff
changeset
|
251 |
digest = md5(digest).digest() |
3035 | 252 |
digest = digest[:16] |
253 |
O = userPad |
|
254 |
for i in range(20): |
|
255 |
thisKey = xorKey(i, digest) |
|
3071 | 256 |
O = ArcIV(thisKey).encode(O) |
3721 | 257 |
if DEBUG: print('computeO(%s,%s,%s)==>%s' % tuple([hexText(str(x)) for x in (userPassword, ownerPassword, revision,O)])) |
3035 | 258 |
return O |
259 |
||
260 |
def computeU(encryptionkey, encodestring=PadString,revision=2,documentId=None): |
|
3071 | 261 |
from reportlab.lib.arciv import ArcIV |
3035 | 262 |
if revision == 2: |
3071 | 263 |
result = ArcIV(encryptionkey).encode(encodestring) |
3035 | 264 |
elif revision == 3: |
265 |
assert documentId is not None, "Revision 3 algorithm needs the document ID!" |
|
3098
318ba6cb2cb1
reportlab: fix md5 usage in pdfencrypt.py & fontfinder.py
rgbecker
parents:
3073
diff
changeset
|
266 |
h = md5(PadString) |
3035 | 267 |
h.update(documentId) |
268 |
tmp = h.digest() |
|
3071 | 269 |
tmp = ArcIV(encryptionkey).encode(tmp) |
3035 | 270 |
for n in range(1,20): |
271 |
thisKey = xorKey(n, encryptionkey) |
|
3071 | 272 |
tmp = ArcIV(thisKey).encode(tmp) |
3035 | 273 |
while len(tmp) < 32: |
274 |
tmp = tmp + '\000' |
|
275 |
result = tmp |
|
3721 | 276 |
if DEBUG: print('computeU(%s,%s,%s,%s)==>%s' % tuple([hexText(str(x)) for x in (encryptionkey, encodestring,revision,documentId,result)])) |
3035 | 277 |
return result |
278 |
||
279 |
def checkU(encryptionkey, U): |
|
280 |
decoded = computeU(encryptionkey, U) |
|
281 |
#print len(decoded), len(U), len(PadString) |
|
282 |
if decoded!=PadString: |
|
283 |
if len(decoded)!=len(PadString): |
|
3721 | 284 |
raise ValueError("lengths don't match! (password failed)") |
285 |
raise ValueError("decode of U doesn't match fixed padstring (password failed)") |
|
3035 | 286 |
|
287 |
def encodePDF(key, objectNumber, generationNumber, string, revision=2): |
|
288 |
"Encodes a string or stream" |
|
289 |
#print 'encodePDF (%s, %d, %d, %s)' % (hexText(key), objectNumber, generationNumber, string) |
|
290 |
# extend 3 bytes of the object Number, low byte first |
|
291 |
newkey = key |
|
292 |
n = objectNumber |
|
293 |
for i in range(3): |
|
294 |
newkey = newkey + chr(n & 0xff) |
|
295 |
n = n>>8 |
|
296 |
# extend 2 bytes of the generationNumber |
|
297 |
n = generationNumber |
|
298 |
for i in range(2): |
|
299 |
newkey = newkey + chr(n & 0xff) |
|
300 |
n = n>>8 |
|
3098
318ba6cb2cb1
reportlab: fix md5 usage in pdfencrypt.py & fontfinder.py
rgbecker
parents:
3073
diff
changeset
|
301 |
md5output = md5(newkey).digest() |
3035 | 302 |
if revision == 2: |
3071 | 303 |
key = md5output[:10] |
3035 | 304 |
elif revision == 3: |
3071 | 305 |
key = md5output #all 16 bytes |
306 |
from reportlab.lib.arciv import ArcIV |
|
307 |
encrypted = ArcIV(key).encode(string) |
|
3035 | 308 |
#print 'encrypted=', hexText(encrypted) |
3721 | 309 |
if DEBUG: print('encodePDF(%s,%s,%s,%s,%s)==>%s' % tuple([hexText(str(x)) for x in (key, objectNumber, generationNumber, string, revision,encrypted)])) |
3035 | 310 |
return encrypted |
311 |
||
312 |
###################################################################### |
|
313 |
# |
|
314 |
# quick tests of algorithm, should be moved elsewhere |
|
315 |
# |
|
316 |
###################################################################### |
|
317 |
||
318 |
def test(): |
|
319 |
# do a 40 bit example known to work in Acrobat Reader 4.0 |
|
320 |
enc = StandardEncryption('userpass','ownerpass', strength=40) |
|
321 |
enc.prepare(None, overrideID = 'xxxxxxxxxxxxxxxx') |
|
322 |
||
323 |
expectedO = '<6A835A92E99DCEA39D51CF34FDBDA42162690D2BD5F8E08E3008F91FE5B8512E>' |
|
324 |
expectedU = '<9997BDB61E7F288DAE6A8C4246A8F9CDCDBBC3D909D703CABA5D65A0CC6D4083>' |
|
325 |
expectedKey = '<A3A68B5CB1>' # 5 byte key = 40 bits |
|
326 |
||
327 |
assert hexText(enc.O) == expectedO, '40 bit unexpected O value %s' % hexText(enc.O) |
|
328 |
assert hexText(enc.U) == expectedU, '40 bit unexpected U value %s' % hexText(enc.U) |
|
329 |
assert hexText(enc.key) == expectedKey, '40 bit unexpected key value %s' % hexText(enc.key) |
|
330 |
||
331 |
# now for 128 bit example |
|
332 |
enc = StandardEncryption('userpass','ownerpass', strength=128) |
|
333 |
enc.prepare(None, overrideID = 'xxxxxxxxxxxxxxxx') |
|
334 |
||
335 |
expectedO = '<19BDBD240E0866B84C49AEEF7E2350045DB8BDAE96E039BF4E3F12DAC3427DB6>' |
|
336 |
expectedU = '<564747DADFF35F5F2078A2CA1705B50800000000000000000000000000000000>' |
|
337 |
expectedKey = '<DC1E019846B1EEABA0CDB8ED6D53B5C4>' # 16 byte key = 128 bits |
|
338 |
||
339 |
assert hexText(enc.O) == expectedO, '128 bit unexpected O value %s' % hexText(enc.O) |
|
340 |
assert hexText(enc.U) == expectedU, '128 bit unexpected U value %s' % hexText(enc.U) |
|
341 |
assert hexText(enc.key) == expectedKey, '128 bit unexpected key value %s' % hexText(enc.key) |
|
342 |
||
343 |
###################################################################### |
|
344 |
# |
|
345 |
# These represent the higher level API functions |
|
346 |
# |
|
347 |
###################################################################### |
|
348 |
||
349 |
def encryptCanvas(canvas, |
|
350 |
userPassword, ownerPassword=None, |
|
351 |
canPrint=1, canModify=1, canCopy=1, canAnnotate=1, |
|
352 |
strength=40): |
|
353 |
"Applies encryption to the document being generated" |
|
354 |
||
355 |
enc = StandardEncryption(userPassword, ownerPassword, |
|
356 |
canPrint, canModify, canCopy, canAnnotate, |
|
357 |
strength=strength) |
|
358 |
canvas._doc.encrypt = enc |
|
359 |
||
360 |
# Platypus stuff needs work, sadly. I wanted to do it without affecting |
|
361 |
# needing changes to latest release. |
|
362 |
class EncryptionFlowable(StandardEncryption, Flowable): |
|
363 |
"""Drop this in your Platypus story and it will set up the encryption options. |
|
364 |
||
365 |
If you do it multiple times, the last one before saving will win.""" |
|
366 |
||
367 |
def wrap(self, availWidth, availHeight): |
|
368 |
return (0,0) |
|
369 |
||
370 |
def draw(self): |
|
371 |
encryptCanvas(self.canv, |
|
372 |
self.userPassword, |
|
373 |
self.ownerPassword, |
|
374 |
self.canPrint, |
|
375 |
self.canModify, |
|
376 |
self.canCopy, |
|
377 |
self.canAnnotate) |
|
378 |
||
379 |
## I am thinking about this one. Needs a change to reportlab to |
|
380 |
## work. |
|
381 |
def encryptDocTemplate(dt, |
|
382 |
userPassword, ownerPassword=None, |
|
383 |
canPrint=1, canModify=1, canCopy=1, canAnnotate=1, |
|
384 |
strength=40): |
|
385 |
"For use in Platypus. Call before build()." |
|
386 |
raise Exception("Not implemented yet") |
|
387 |
||
388 |
||
389 |
def encryptPdfInMemory(inputPDF, |
|
390 |
userPassword, ownerPassword=None, |
|
391 |
canPrint=1, canModify=1, canCopy=1, canAnnotate=1, |
|
392 |
strength=40): |
|
393 |
"""accepts a PDF file 'as a byte array in memory'; return encrypted one. |
|
394 |
||
395 |
This is a high level convenience and does not touch the hard disk in any way. |
|
396 |
If you are encrypting the same file over and over again, it's better to use |
|
397 |
pageCatcher and cache the results.""" |
|
398 |
||
3073
6554a30b7450
Stop pdfencrypt from expecting rlextra to be present.
jonas
parents:
3071
diff
changeset
|
399 |
try: |
6554a30b7450
Stop pdfencrypt from expecting rlextra to be present.
jonas
parents:
3071
diff
changeset
|
400 |
from rlextra.pageCatcher.pageCatcher import storeFormsInMemory, restoreFormsInMemory |
6554a30b7450
Stop pdfencrypt from expecting rlextra to be present.
jonas
parents:
3071
diff
changeset
|
401 |
except ImportError: |
6554a30b7450
Stop pdfencrypt from expecting rlextra to be present.
jonas
parents:
3071
diff
changeset
|
402 |
raise ImportError('''reportlab.lib.pdfencrypt.encryptPdfInMemory failed because rlextra cannot be imported. |
6554a30b7450
Stop pdfencrypt from expecting rlextra to be present.
jonas
parents:
3071
diff
changeset
|
403 |
See http://developer.reportlab.com''') |
6554a30b7450
Stop pdfencrypt from expecting rlextra to be present.
jonas
parents:
3071
diff
changeset
|
404 |
|
3035 | 405 |
(bboxInfo, pickledForms) = storeFormsInMemory(inputPDF, all=1, BBoxes=1) |
3721 | 406 |
names = list(bboxInfo.keys()) |
3035 | 407 |
|
408 |
firstPageSize = bboxInfo['PageForms0'][2:] |
|
409 |
||
410 |
#now make a new PDF document |
|
3723
99aa837b6703
second stage of port to Python 3.3; working hello world
rptlab
parents:
3721
diff
changeset
|
411 |
buf = getBytesIO() |
3035 | 412 |
canv = Canvas(buf, pagesize=firstPageSize) |
413 |
||
414 |
# set a standard ID while debugging |
|
415 |
if CLOBBERID: |
|
416 |
canv._doc._ID = "[(xxxxxxxxxxxxxxxx)(xxxxxxxxxxxxxxxx)]" |
|
417 |
encryptCanvas(canv, |
|
418 |
userPassword, ownerPassword, |
|
419 |
canPrint, canModify, canCopy, canAnnotate, |
|
420 |
strength=strength) |
|
421 |
||
422 |
formNames = restoreFormsInMemory(pickledForms, canv) |
|
423 |
for formName in formNames: |
|
424 |
#need to extract page size in future |
|
425 |
canv.doForm(formName) |
|
426 |
canv.showPage() |
|
427 |
canv.save() |
|
428 |
return buf.getvalue() |
|
429 |
||
430 |
||
431 |
def encryptPdfOnDisk(inputFileName, outputFileName, |
|
432 |
userPassword, ownerPassword=None, |
|
433 |
canPrint=1, canModify=1, canCopy=1, canAnnotate=1, |
|
434 |
strength=40): |
|
435 |
"Creates encrypted file OUTPUTFILENAME. Returns size in bytes." |
|
436 |
||
437 |
inputPDF = open(inputFileName, 'rb').read() |
|
438 |
outputPDF = encryptPdfInMemory(inputPDF, |
|
439 |
userPassword, ownerPassword, |
|
440 |
canPrint, canModify, canCopy, canAnnotate, |
|
441 |
strength=strength) |
|
442 |
open(outputFileName, 'wb').write(outputPDF) |
|
443 |
return len(outputPDF) |
|
444 |
||
445 |
||
446 |
def scriptInterp(): |
|
447 |
sys_argv = sys.argv[:] # copy |
|
448 |
||
449 |
usage = """PDFENCRYPT USAGE: |
|
450 |
||
451 |
PdfEncrypt encrypts your PDF files. |
|
452 |
||
453 |
Line mode usage: |
|
454 |
||
455 |
% pdfencrypt.exe pdffile [-o ownerpassword] | [owner ownerpassword], |
|
456 |
\t[-u userpassword] | [user userpassword], |
|
457 |
\t[-p 1|0] | [printable 1|0], |
|
458 |
\t[-m 1|0] | [modifiable 1|0], |
|
459 |
\t[-c 1|0] | [copypastable 1|0], |
|
460 |
\t[-a 1|0] | [annotatable 1|0], |
|
461 |
\t[-s savefilename] | [savefile savefilename], |
|
462 |
\t[-v 1|0] | [verbose 1|0], |
|
463 |
\t[-e128], [encrypt128], |
|
464 |
\t[-h] | [help] |
|
465 |
||
466 |
-o or owner set the owner password. |
|
467 |
-u or user set the user password. |
|
468 |
-p or printable set the printable attribute (must be 1 or 0). |
|
469 |
-m or modifiable sets the modifiable attribute (must be 1 or 0). |
|
470 |
-c or copypastable sets the copypastable attribute (must be 1 or 0). |
|
471 |
-a or annotatable sets the annotatable attribute (must be 1 or 0). |
|
472 |
-s or savefile sets the name for the output PDF file |
|
473 |
-v or verbose prints useful output to the screen. |
|
474 |
(this defaults to 'pdffile_encrypted.pdf'). |
|
475 |
'-e128' or 'encrypt128' allows you to use 128 bit encryption (in beta). |
|
476 |
||
477 |
-h or help prints this message. |
|
478 |
||
479 |
See PdfEncryptIntro.pdf for more information. |
|
480 |
""" |
|
481 |
||
482 |
known_modes = ['-o', 'owner', |
|
483 |
'-u', 'user', |
|
484 |
'-p', 'printable', |
|
485 |
'-m', 'modifiable', |
|
486 |
'-c', 'copypastable', |
|
487 |
'-a', 'annotatable', |
|
488 |
'-s', 'savefile', |
|
489 |
'-v', 'verbose', |
|
490 |
'-h', 'help', |
|
491 |
'-e128', 'encrypt128'] |
|
492 |
||
493 |
OWNER = '' |
|
494 |
USER = '' |
|
495 |
PRINTABLE = 1 |
|
496 |
MODIFIABLE = 1 |
|
497 |
COPYPASTABLE = 1 |
|
498 |
ANNOTATABLE = 1 |
|
499 |
SAVEFILE = 'encrypted.pdf' |
|
500 |
||
501 |
#try: |
|
502 |
caller = sys_argv[0] # may be required later - eg if called by security.py |
|
503 |
argv = list(sys_argv)[1:] |
|
504 |
if len(argv)>0: |
|
505 |
if argv[0] == '-h' or argv[0] == 'help': |
|
3721 | 506 |
print(usage) |
3035 | 507 |
return |
508 |
if len(argv)<2: |
|
3328 | 509 |
raise ValueError("Must include a filename and one or more arguments!") |
3035 | 510 |
if argv[0] not in known_modes: |
511 |
infile = argv[0] |
|
512 |
argv = argv[1:] |
|
513 |
if not os.path.isfile(infile): |
|
3328 | 514 |
raise ValueError("Can't open input file '%s'!" % infile) |
3035 | 515 |
else: |
3328 | 516 |
raise ValueError("First argument must be name of the PDF input file!") |
3035 | 517 |
|
518 |
# meaningful name at this stage |
|
519 |
STRENGTH = 40 |
|
520 |
if 'encrypt128' in argv: |
|
521 |
STRENGTH = 128 |
|
522 |
argv.remove('encrypt128') |
|
523 |
if '-e128' in argv: |
|
524 |
STRENGTH = 128 |
|
525 |
argv.remove('-e128') |
|
526 |
||
527 |
if ('-v' in argv) or ('verbose' in argv): |
|
528 |
if '-v' in argv: |
|
529 |
pos = argv.index('-v') |
|
530 |
arg = "-v" |
|
531 |
elif 'verbose' in argv: |
|
532 |
pos = argv.index('verbose') |
|
533 |
arg = "verbose" |
|
534 |
try: |
|
535 |
verbose = int(argv[pos+1]) |
|
536 |
except: |
|
537 |
verbose = 1 |
|
538 |
argv.remove(argv[pos+1]) |
|
539 |
argv.remove(arg) |
|
540 |
else: |
|
541 |
from reportlab.rl_config import verbose |
|
542 |
||
543 |
#argument, valid license variable, invalid license variable, text for print |
|
544 |
arglist = (('-o', 'OWNER', OWNER, 'Owner password'), |
|
545 |
('owner', 'OWNER', OWNER, 'Owner password'), |
|
546 |
('-u', 'USER', USER, 'User password'), |
|
547 |
('user', 'USER', USER, 'User password'), |
|
548 |
('-p', 'PRINTABLE', PRINTABLE, "'Printable'"), |
|
549 |
('printable', 'PRINTABLE', PRINTABLE, "'Printable'"), |
|
550 |
('-m', 'MODIFIABLE', MODIFIABLE, "'Modifiable'"), |
|
551 |
('modifiable', 'MODIFIABLE', MODIFIABLE, "'Modifiable'"), |
|
552 |
('-c', 'COPYPASTABLE', COPYPASTABLE, "'Copypastable'"), |
|
553 |
('copypastable', 'COPYPASTABLE', COPYPASTABLE, "'Copypastable'"), |
|
554 |
('-a', 'ANNOTATABLE', ANNOTATABLE, "'Annotatable'"), |
|
555 |
('annotatable', 'ANNOTATABLE', ANNOTATABLE, "'Annotatable'"), |
|
556 |
('-s', 'SAVEFILE', SAVEFILE, "Output file"), |
|
557 |
('savefile', 'SAVEFILE', SAVEFILE, "Output file"), |
|
558 |
) |
|
559 |
||
560 |
binaryrequired = ('-p', 'printable', '-m', 'modifiable', 'copypastable', '-c', 'annotatable', '-a') |
|
561 |
||
562 |
for thisarg in arglist: |
|
563 |
if thisarg[0] in argv: |
|
564 |
pos = argv.index(thisarg[0]) |
|
565 |
if thisarg[0] in binaryrequired: |
|
566 |
#try: |
|
567 |
if argv[pos+1] not in ('1', '0'): |
|
568 |
raise "%s value must be either '1' or '0'!" % thisarg[1] |
|
569 |
#except: |
|
570 |
#raise "Unable to set %s." % thisarg[4] |
|
571 |
try: |
|
572 |
if argv[pos+1] not in known_modes: |
|
573 |
if thisarg[0] in binaryrequired: |
|
574 |
exec(thisarg[1] +' = int(argv[pos+1])') |
|
575 |
else: |
|
576 |
exec(thisarg[1] +' = argv[pos+1]') |
|
577 |
if verbose: |
|
3721 | 578 |
print("%s set to: '%s'." % (thisarg[3], argv[pos+1])) |
3035 | 579 |
argv.remove(argv[pos+1]) |
580 |
argv.remove(thisarg[0]) |
|
581 |
except: |
|
582 |
raise "Unable to set %s." % thisarg[3] |
|
583 |
||
584 |
if verbose>4: |
|
585 |
#useful if feeling paranoid and need to double check things at this point... |
|
3721 | 586 |
print("\ninfile:", infile) |
587 |
print("STRENGTH:", STRENGTH) |
|
588 |
print("SAVEFILE:", SAVEFILE) |
|
589 |
print("USER:", USER) |
|
590 |
print("OWNER:", OWNER) |
|
591 |
print("PRINTABLE:", PRINTABLE) |
|
592 |
print("MODIFIABLE:", MODIFIABLE) |
|
593 |
print("COPYPASTABLE:", COPYPASTABLE) |
|
594 |
print("ANNOTATABLE:", ANNOTATABLE) |
|
595 |
print("SAVEFILE:", SAVEFILE) |
|
596 |
print("VERBOSE:", verbose) |
|
3035 | 597 |
|
598 |
||
599 |
if SAVEFILE == 'encrypted.pdf': |
|
600 |
if infile[-4:] == '.pdf' or infile[-4:] == '.PDF': |
|
601 |
tinfile = infile[:-4] |
|
602 |
else: |
|
603 |
tinfile = infile |
|
604 |
SAVEFILE = tinfile+"_encrypted.pdf" |
|
605 |
||
606 |
filesize = encryptPdfOnDisk(infile, SAVEFILE, USER, OWNER, |
|
607 |
PRINTABLE, MODIFIABLE, COPYPASTABLE, ANNOTATABLE, |
|
608 |
strength=STRENGTH) |
|
609 |
||
610 |
if verbose: |
|
3721 | 611 |
print("wrote output file '%s'(%s bytes)\n owner password is '%s'\n user password is '%s'" % (SAVEFILE, filesize, OWNER, USER)) |
3035 | 612 |
|
613 |
if len(argv)>0: |
|
614 |
raise "\nUnrecognised arguments : %s\nknown arguments are:\n%s" % (str(argv)[1:-1], known_modes) |
|
615 |
else: |
|
3721 | 616 |
print(usage) |
3035 | 617 |
|
618 |
def main(): |
|
619 |
from reportlab.rl_config import verbose |
|
620 |
scriptInterp() |
|
621 |
||
622 |
if __name__=="__main__": #NO RUNTESTS |
|
3721 | 623 |
a = [x for x in sys.argv if x[:7]=='--debug'] |
3035 | 624 |
if a: |
3721 | 625 |
sys.argv = [x for x in sys.argv if x[:7]!='--debug'] |
3035 | 626 |
DEBUG = len(a) |
627 |
if '--test' in sys.argv: test() |
|
628 |
else: main() |