prawn-security 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/COPYING ADDED
@@ -0,0 +1,340 @@
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 2, June 1991
3
+
4
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
5
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
6
+ Everyone is permitted to copy and distribute verbatim copies
7
+ of this license document, but changing it is not allowed.
8
+
9
+ Preamble
10
+
11
+ The licenses for most software are designed to take away your
12
+ freedom to share and change it. By contrast, the GNU General Public
13
+ License is intended to guarantee your freedom to share and change free
14
+ software--to make sure the software is free for all its users. This
15
+ General Public License applies to most of the Free Software
16
+ Foundation's software and to any other program whose authors commit to
17
+ using it. (Some other Free Software Foundation software is covered by
18
+ the GNU Library General Public License instead.) You can apply it to
19
+ your programs, too.
20
+
21
+ When we speak of free software, we are referring to freedom, not
22
+ price. Our General Public Licenses are designed to make sure that you
23
+ have the freedom to distribute copies of free software (and charge for
24
+ this service if you wish), that you receive source code or can get it
25
+ if you want it, that you can change the software or use pieces of it
26
+ in new free programs; and that you know you can do these things.
27
+
28
+ To protect your rights, we need to make restrictions that forbid
29
+ anyone to deny you these rights or to ask you to surrender the rights.
30
+ These restrictions translate to certain responsibilities for you if you
31
+ distribute copies of the software, or if you modify it.
32
+
33
+ For example, if you distribute copies of such a program, whether
34
+ gratis or for a fee, you must give the recipients all the rights that
35
+ you have. You must make sure that they, too, receive or can get the
36
+ source code. And you must show them these terms so they know their
37
+ rights.
38
+
39
+ We protect your rights with two steps: (1) copyright the software, and
40
+ (2) offer you this license which gives you legal permission to copy,
41
+ distribute and/or modify the software.
42
+
43
+ Also, for each author's protection and ours, we want to make certain
44
+ that everyone understands that there is no warranty for this free
45
+ software. If the software is modified by someone else and passed on, we
46
+ want its recipients to know that what they have is not the original, so
47
+ that any problems introduced by others will not reflect on the original
48
+ authors' reputations.
49
+
50
+ Finally, any free program is threatened constantly by software
51
+ patents. We wish to avoid the danger that redistributors of a free
52
+ program will individually obtain patent licenses, in effect making the
53
+ program proprietary. To prevent this, we have made it clear that any
54
+ patent must be licensed for everyone's free use or not licensed at all.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ GNU GENERAL PUBLIC LICENSE
60
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61
+
62
+ 0. This License applies to any program or other work which contains
63
+ a notice placed by the copyright holder saying it may be distributed
64
+ under the terms of this General Public License. The "Program", below,
65
+ refers to any such program or work, and a "work based on the Program"
66
+ means either the Program or any derivative work under copyright law:
67
+ that is to say, a work containing the Program or a portion of it,
68
+ either verbatim or with modifications and/or translated into another
69
+ language. (Hereinafter, translation is included without limitation in
70
+ the term "modification".) Each licensee is addressed as "you".
71
+
72
+ Activities other than copying, distribution and modification are not
73
+ covered by this License; they are outside its scope. The act of
74
+ running the Program is not restricted, and the output from the Program
75
+ is covered only if its contents constitute a work based on the
76
+ Program (independent of having been made by running the Program).
77
+ Whether that is true depends on what the Program does.
78
+
79
+ 1. You may copy and distribute verbatim copies of the Program's
80
+ source code as you receive it, in any medium, provided that you
81
+ conspicuously and appropriately publish on each copy an appropriate
82
+ copyright notice and disclaimer of warranty; keep intact all the
83
+ notices that refer to this License and to the absence of any warranty;
84
+ and give any other recipients of the Program a copy of this License
85
+ along with the Program.
86
+
87
+ You may charge a fee for the physical act of transferring a copy, and
88
+ you may at your option offer warranty protection in exchange for a fee.
89
+
90
+ 2. You may modify your copy or copies of the Program or any portion
91
+ of it, thus forming a work based on the Program, and copy and
92
+ distribute such modifications or work under the terms of Section 1
93
+ above, provided that you also meet all of these conditions:
94
+
95
+ a) You must cause the modified files to carry prominent notices
96
+ stating that you changed the files and the date of any change.
97
+
98
+ b) You must cause any work that you distribute or publish, that in
99
+ whole or in part contains or is derived from the Program or any
100
+ part thereof, to be licensed as a whole at no charge to all third
101
+ parties under the terms of this License.
102
+
103
+ c) If the modified program normally reads commands interactively
104
+ when run, you must cause it, when started running for such
105
+ interactive use in the most ordinary way, to print or display an
106
+ announcement including an appropriate copyright notice and a
107
+ notice that there is no warranty (or else, saying that you provide
108
+ a warranty) and that users may redistribute the program under
109
+ these conditions, and telling the user how to view a copy of this
110
+ License. (Exception: if the Program itself is interactive but
111
+ does not normally print such an announcement, your work based on
112
+ the Program is not required to print an announcement.)
113
+
114
+ These requirements apply to the modified work as a whole. If
115
+ identifiable sections of that work are not derived from the Program,
116
+ and can be reasonably considered independent and separate works in
117
+ themselves, then this License, and its terms, do not apply to those
118
+ sections when you distribute them as separate works. But when you
119
+ distribute the same sections as part of a whole which is a work based
120
+ on the Program, the distribution of the whole must be on the terms of
121
+ this License, whose permissions for other licensees extend to the
122
+ entire whole, and thus to each and every part regardless of who wrote it.
123
+
124
+ Thus, it is not the intent of this section to claim rights or contest
125
+ your rights to work written entirely by you; rather, the intent is to
126
+ exercise the right to control the distribution of derivative or
127
+ collective works based on the Program.
128
+
129
+ In addition, mere aggregation of another work not based on the Program
130
+ with the Program (or with a work based on the Program) on a volume of
131
+ a storage or distribution medium does not bring the other work under
132
+ the scope of this License.
133
+
134
+ 3. You may copy and distribute the Program (or a work based on it,
135
+ under Section 2) in object code or executable form under the terms of
136
+ Sections 1 and 2 above provided that you also do one of the following:
137
+
138
+ a) Accompany it with the complete corresponding machine-readable
139
+ source code, which must be distributed under the terms of Sections
140
+ 1 and 2 above on a medium customarily used for software interchange; or,
141
+
142
+ b) Accompany it with a written offer, valid for at least three
143
+ years, to give any third party, for a charge no more than your
144
+ cost of physically performing source distribution, a complete
145
+ machine-readable copy of the corresponding source code, to be
146
+ distributed under the terms of Sections 1 and 2 above on a medium
147
+ customarily used for software interchange; or,
148
+
149
+ c) Accompany it with the information you received as to the offer
150
+ to distribute corresponding source code. (This alternative is
151
+ allowed only for noncommercial distribution and only if you
152
+ received the program in object code or executable form with such
153
+ an offer, in accord with Subsection b above.)
154
+
155
+ The source code for a work means the preferred form of the work for
156
+ making modifications to it. For an executable work, complete source
157
+ code means all the source code for all modules it contains, plus any
158
+ associated interface definition files, plus the scripts used to
159
+ control compilation and installation of the executable. However, as a
160
+ special exception, the source code distributed need not include
161
+ anything that is normally distributed (in either source or binary
162
+ form) with the major components (compiler, kernel, and so on) of the
163
+ operating system on which the executable runs, unless that component
164
+ itself accompanies the executable.
165
+
166
+ If distribution of executable or object code is made by offering
167
+ access to copy from a designated place, then offering equivalent
168
+ access to copy the source code from the same place counts as
169
+ distribution of the source code, even though third parties are not
170
+ compelled to copy the source along with the object code.
171
+
172
+ 4. You may not copy, modify, sublicense, or distribute the Program
173
+ except as expressly provided under this License. Any attempt
174
+ otherwise to copy, modify, sublicense or distribute the Program is
175
+ void, and will automatically terminate your rights under this License.
176
+ However, parties who have received copies, or rights, from you under
177
+ this License will not have their licenses terminated so long as such
178
+ parties remain in full compliance.
179
+
180
+ 5. You are not required to accept this License, since you have not
181
+ signed it. However, nothing else grants you permission to modify or
182
+ distribute the Program or its derivative works. These actions are
183
+ prohibited by law if you do not accept this License. Therefore, by
184
+ modifying or distributing the Program (or any work based on the
185
+ Program), you indicate your acceptance of this License to do so, and
186
+ all its terms and conditions for copying, distributing or modifying
187
+ the Program or works based on it.
188
+
189
+ 6. Each time you redistribute the Program (or any work based on the
190
+ Program), the recipient automatically receives a license from the
191
+ original licensor to copy, distribute or modify the Program subject to
192
+ these terms and conditions. You may not impose any further
193
+ restrictions on the recipients' exercise of the rights granted herein.
194
+ You are not responsible for enforcing compliance by third parties to
195
+ this License.
196
+
197
+ 7. If, as a consequence of a court judgment or allegation of patent
198
+ infringement or for any other reason (not limited to patent issues),
199
+ conditions are imposed on you (whether by court order, agreement or
200
+ otherwise) that contradict the conditions of this License, they do not
201
+ excuse you from the conditions of this License. If you cannot
202
+ distribute so as to satisfy simultaneously your obligations under this
203
+ License and any other pertinent obligations, then as a consequence you
204
+ may not distribute the Program at all. For example, if a patent
205
+ license would not permit royalty-free redistribution of the Program by
206
+ all those who receive copies directly or indirectly through you, then
207
+ the only way you could satisfy both it and this License would be to
208
+ refrain entirely from distribution of the Program.
209
+
210
+ If any portion of this section is held invalid or unenforceable under
211
+ any particular circumstance, the balance of the section is intended to
212
+ apply and the section as a whole is intended to apply in other
213
+ circumstances.
214
+
215
+ It is not the purpose of this section to induce you to infringe any
216
+ patents or other property right claims or to contest validity of any
217
+ such claims; this section has the sole purpose of protecting the
218
+ integrity of the free software distribution system, which is
219
+ implemented by public license practices. Many people have made
220
+ generous contributions to the wide range of software distributed
221
+ through that system in reliance on consistent application of that
222
+ system; it is up to the author/donor to decide if he or she is willing
223
+ to distribute software through any other system and a licensee cannot
224
+ impose that choice.
225
+
226
+ This section is intended to make thoroughly clear what is believed to
227
+ be a consequence of the rest of this License.
228
+
229
+ 8. If the distribution and/or use of the Program is restricted in
230
+ certain countries either by patents or by copyrighted interfaces, the
231
+ original copyright holder who places the Program under this License
232
+ may add an explicit geographical distribution limitation excluding
233
+ those countries, so that distribution is permitted only in or among
234
+ countries not thus excluded. In such case, this License incorporates
235
+ the limitation as if written in the body of this License.
236
+
237
+ 9. The Free Software Foundation may publish revised and/or new versions
238
+ of the General Public License from time to time. Such new versions will
239
+ be similar in spirit to the present version, but may differ in detail to
240
+ address new problems or concerns.
241
+
242
+ Each version is given a distinguishing version number. If the Program
243
+ specifies a version number of this License which applies to it and "any
244
+ later version", you have the option of following the terms and conditions
245
+ either of that version or of any later version published by the Free
246
+ Software Foundation. If the Program does not specify a version number of
247
+ this License, you may choose any version ever published by the Free Software
248
+ Foundation.
249
+
250
+ 10. If you wish to incorporate parts of the Program into other free
251
+ programs whose distribution conditions are different, write to the author
252
+ to ask for permission. For software which is copyrighted by the Free
253
+ Software Foundation, write to the Free Software Foundation; we sometimes
254
+ make exceptions for this. Our decision will be guided by the two goals
255
+ of preserving the free status of all derivatives of our free software and
256
+ of promoting the sharing and reuse of software generally.
257
+
258
+ NO WARRANTY
259
+
260
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261
+ FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262
+ OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263
+ PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264
+ OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265
+ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266
+ TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267
+ PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268
+ REPAIR OR CORRECTION.
269
+
270
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272
+ REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273
+ INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274
+ OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275
+ TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276
+ YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277
+ PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278
+ POSSIBILITY OF SUCH DAMAGES.
279
+
280
+ END OF TERMS AND CONDITIONS
281
+
282
+ How to Apply These Terms to Your New Programs
283
+
284
+ If you develop a new program, and you want it to be of the greatest
285
+ possible use to the public, the best way to achieve this is to make it
286
+ free software which everyone can redistribute and change under these terms.
287
+
288
+ To do so, attach the following notices to the program. It is safest
289
+ to attach them to the start of each source file to most effectively
290
+ convey the exclusion of warranty; and each file should have at least
291
+ the "copyright" line and a pointer to where the full notice is found.
292
+
293
+ <one line to give the program's name and a brief idea of what it does.>
294
+ Copyright (C) <year> <name of author>
295
+
296
+ This program is free software; you can redistribute it and/or modify
297
+ it under the terms of the GNU General Public License as published by
298
+ the Free Software Foundation; either version 2 of the License, or
299
+ (at your option) any later version.
300
+
301
+ This program is distributed in the hope that it will be useful,
302
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
303
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304
+ GNU General Public License for more details.
305
+
306
+ You should have received a copy of the GNU General Public License
307
+ along with this program; if not, write to the Free Software
308
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
309
+
310
+
311
+ Also add information on how to contact you by electronic and paper mail.
312
+
313
+ If the program is interactive, make it output a short notice like this
314
+ when it starts in an interactive mode:
315
+
316
+ Gnomovision version 69, Copyright (C) year name of author
317
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
318
+ This is free software, and you are welcome to redistribute it
319
+ under certain conditions; type `show c' for details.
320
+
321
+ The hypothetical commands `show w' and `show c' should show the appropriate
322
+ parts of the General Public License. Of course, the commands you use may
323
+ be called something other than `show w' and `show c'; they could even be
324
+ mouse-clicks or menu items--whatever suits your program.
325
+
326
+ You should also get your employer (if you work as a programmer) or your
327
+ school, if any, to sign a "copyright disclaimer" for the program, if
328
+ necessary. Here is a sample; alter the names:
329
+
330
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
331
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
332
+
333
+ <signature of Ty Coon>, 1 April 1989
334
+ Ty Coon, President of Vice
335
+
336
+ This General Public License does not permit incorporating your program into
337
+ proprietary programs. If your program is a subroutine library, you may
338
+ consider it more useful to permit linking proprietary applications with the
339
+ library. If this is what you want to do, use the GNU Library General
340
+ Public License instead of this License.
data/LICENSE ADDED
@@ -0,0 +1,56 @@
1
+ Prawn/Security is copyrighted free software produced by Brad Ediger along with
2
+ community contributions. See git log for authorship information.
3
+
4
+ Licensing terms follow (License of Ruby 1.8):
5
+
6
+ You can redistribute Prawn and/or modify it under either the terms of the GPL
7
+ (see COPYING file), or the conditions below:
8
+
9
+ 1. You may make and give away verbatim copies of the source form of the
10
+ software without restriction, provided that you duplicate all of the
11
+ original copyright notices and associated disclaimers.
12
+
13
+ 2. You may modify your copy of the software in any way, provided that
14
+ you do at least ONE of the following:
15
+
16
+ a) place your modifications in the Public Domain or otherwise
17
+ make them Freely Available, such as by posting said
18
+ modifications to Usenet or an equivalent medium, or by allowing
19
+ the author to include your modifications in the software.
20
+
21
+ b) use the modified software only within your corporation or
22
+ organization.
23
+
24
+ c) rename any non-standard executables so the names do not conflict
25
+ with standard executables, which must also be provided.
26
+
27
+ d) make other distribution arrangements with the author.
28
+
29
+ 3. You may distribute the software in object code or executable
30
+ form, provided that you do at least ONE of the following:
31
+
32
+ a) distribute the executables and library files of the software,
33
+ together with instructions (in the manual page or equivalent)
34
+ on where to get the original distribution.
35
+
36
+ b) accompany the distribution with the machine-readable source of
37
+ the software.
38
+
39
+ c) give non-standard executables non-standard names, with
40
+ instructions on where to get the original software distribution.
41
+
42
+ d) make other distribution arrangements with the author.
43
+
44
+ 4. You may modify and include the part of the software into any other
45
+ software (possibly commercial).
46
+
47
+ 5. The scripts and library files supplied as input to or produced as
48
+ output from the software do not automatically fall under the
49
+ copyright of the software, but belong to whomever generated them,
50
+ and may be sold commercially, and may be aggregated with this
51
+ software.
52
+
53
+ 6. THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
54
+ IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
55
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
56
+ PURPOSE.
data/README ADDED
@@ -0,0 +1,28 @@
1
+ = Prawn/Security: Popular Password Protection & Permissions for Prawn PDFs
2
+
3
+ Prawn/Security adds encryption, password protection, and permissions to Prawn.
4
+
5
+ == Usage
6
+
7
+ See the examples/ directory and/or the RDoc for detailed info. Basically, it's
8
+ as simple as the first example:
9
+
10
+ require 'prawn/security'
11
+
12
+ Prawn::Document.generate("hello_foo.pdf") do
13
+ text "Hello, world!"
14
+ encrypt_document :user_password => 'foo', :owner_password => 'bar',
15
+ :permissions => { :print_document => false }
16
+ end
17
+
18
+ This creates a document that requires the password 'foo' to be opened,
19
+ and cannot be printed without entering the owner password 'bar'.
20
+
21
+ If you want to prohibit most anyone from performing a certain activity, you can
22
+ pass :owner_password => :random to generate a probably-unguessable owner
23
+ password.
24
+
25
+ == Contributors
26
+
27
+ Brad Ediger <brad.ediger@madriska.com>
28
+
@@ -0,0 +1,65 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+ require 'rake/testtask'
4
+ require "rake/rdoctask"
5
+ require "rake/gempackagetask"
6
+
7
+ # Version numbering: http://wiki.github.com/sandal/prawn/development-roadmap
8
+ PRAWN_SECURITY_VERSION = "0.1.1"
9
+
10
+ task :default => [:test]
11
+
12
+ desc "Run all tests, test-spec and mocha required"
13
+ Rake::TestTask.new do |test|
14
+ test.libs << "spec"
15
+ test.test_files = Dir[ "spec/*_spec.rb" ]
16
+ test.verbose = true
17
+ end
18
+
19
+ desc "genrates documentation"
20
+ Rake::RDocTask.new do |rdoc|
21
+ rdoc.rdoc_files.include( "README", "lib/" )
22
+ rdoc.main = "README"
23
+ rdoc.rdoc_dir = "doc/html"
24
+ rdoc.title = "Prawn/Security documentation"
25
+ end
26
+
27
+ desc "run all examples, and then diff them against reference PDFs"
28
+ task :examples do
29
+ mkdir_p "output"
30
+ examples = Dir["examples/**/*.rb"]
31
+ t = Time.now
32
+ puts "Running Examples"
33
+ examples.each { |file| `ruby -Ilib #{file}` }
34
+ puts "Ran in #{Time.now - t} s"
35
+ `mv *.pdf output`
36
+ end
37
+
38
+ spec = Gem::Specification.new do |spec|
39
+ spec.name = "prawn-security"
40
+ spec.version = PRAWN_SECURITY_VERSION
41
+ spec.platform = Gem::Platform::RUBY
42
+ spec.summary = "Popular Password Protection & Permissions for Prawn PDFs"
43
+ spec.files = Dir.glob("{examples,lib,spec}/**/*") +
44
+ ["Rakefile"]
45
+ spec.require_path = "lib"
46
+
47
+ spec.test_files = Dir[ "spec/*_spec.rb" ]
48
+ spec.has_rdoc = true
49
+ spec.extra_rdoc_files = %w{README LICENSE COPYING}
50
+ spec.rdoc_options << '--title' << 'Prawn/Security Documentation' <<
51
+ '--main' << 'README' << '-q'
52
+ spec.author = "Brad Ediger"
53
+ spec.email = "brad.ediger@madriska.com"
54
+ spec.rubyforge_project = "prawn-security"
55
+ spec.homepage = "http://github.com/madriska/prawn-security/"
56
+ spec.description = <<END_DESC
57
+ Prawn/Security adds document encryption, password protection, and permissions to Prawn.
58
+ END_DESC
59
+ end
60
+
61
+ Rake::GemPackageTask.new(spec) do |pkg|
62
+ pkg.need_zip = true
63
+ pkg.need_tar = true
64
+ end
65
+
@@ -0,0 +1,4 @@
1
+ $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
2
+ require 'prawn/core'
3
+ require 'prawn/security'
4
+ Prawn.debug = true
@@ -0,0 +1,8 @@
1
+ require File.join(File.dirname(__FILE__), "example_helper")
2
+
3
+ Prawn::Document.generate("hello_foo.pdf") do
4
+ text "Hello, world!"
5
+ encrypt_document :user_password => 'foo', :owner_password => 'bar',
6
+ :permissions => { :print_document => false }
7
+ end
8
+
@@ -0,0 +1,51 @@
1
+ # Implementation of the "ARCFOUR" algorithm ("alleged RC4 (tm)"). Implemented
2
+ # as described at:
3
+ # http://www.mozilla.org/projects/security/pki/nss/draft-kaukonen-cipher-arcfour-03.txt
4
+ #
5
+ # "RC4" is a trademark of RSA Data Security, Inc.
6
+ #
7
+ # Copyright August 2009, Brad Ediger. All Rights Reserved.
8
+ #
9
+ # This is free software. Please see the LICENSE and COPYING files for details.
10
+
11
+ class Arcfour
12
+ def initialize(key)
13
+ # Convert string key to Array of integers
14
+ key = key.unpack('c*') if key.is_a?(String)
15
+
16
+ # 1. Allocate an 256 element array of 8 bit bytes to be used as an S-box
17
+ # 2. Initialize the S-box. Fill each entry first with it's index
18
+ @sbox = (0..255).to_a
19
+
20
+ # 3. Fill another array of the same size (256) with the key, repeating
21
+ # bytes as necessary.
22
+ s2 = []
23
+ while s2.length < 256
24
+ s2 += key
25
+ end
26
+ s2 = s2[0, 256]
27
+
28
+ # 4. Set j to zero and initialize the S-box
29
+ j = 0
30
+ (0..255).each do |i|
31
+ j = (j + @sbox[i] + s2[i]) % 256
32
+ @sbox[i], @sbox[j] = @sbox[j], @sbox[i]
33
+ end
34
+
35
+ @i = @j = 0
36
+ end
37
+
38
+ def encrypt(string)
39
+ string.unpack('c*').map{|byte| byte ^ key_byte}.pack('c*')
40
+ end
41
+
42
+ private
43
+
44
+ # Produces the next byte of key material in the stream (3.2 Stream Generation)
45
+ def key_byte
46
+ @i = (@i + 1) % 256
47
+ @j = (@j + @sbox[@i]) % 256
48
+ @sbox[@i], @sbox[@j] = @sbox[@j], @sbox[@i]
49
+ @sbox[(@sbox[@i] + @sbox[@j]) % 256]
50
+ end
51
+ end
@@ -0,0 +1,270 @@
1
+ # encoding: utf-8
2
+ #
3
+ # encryption.rb : Implements encrypted PDF and access permissions.
4
+ #
5
+ # Copyright August 2008, Brad Ediger. All Rights Reserved.
6
+ #
7
+ # This is free software. Please see the LICENSE and COPYING files for details.
8
+
9
+ require 'digest/md5'
10
+ require 'prawn/arcfour'
11
+ require 'prawn/byte_string'
12
+
13
+ module Prawn
14
+ class Document
15
+
16
+ # Implements PDF encryption (password protection and permissions) as
17
+ # specified in the PDF Reference, version 1.3, section 3.5 "Encryption".
18
+ module Security
19
+
20
+ # Encrypts the document, to protect confidential data or control
21
+ # modifications to the document. The encryption algorithm used is
22
+ # detailed in the PDF Reference 1.3, section 3.5 "Encryption", and it is
23
+ # implemented by all major PDF readers.
24
+ #
25
+ # +options+ can contain the following:
26
+ #
27
+ # <tt>:user_password</tt>:: Password required to open the document. If
28
+ # this is omitted or empty, no password will be
29
+ # required. The document will still be
30
+ # encrypted, but anyone can read it.
31
+ #
32
+ # <tt>:owner_password</tt>:: Password required to make modifications to
33
+ # the document or change or override its
34
+ # permissions. If this is set to
35
+ # <tt>:random</tt>, a random password will be
36
+ # used; this can be useful if you never want
37
+ # users to be able to override the document
38
+ # permissions.
39
+ #
40
+ # <tt>:permissions</tt>:: A hash mapping permission symbols (see below) to
41
+ # <tt>true</tt> or <tt>false</tt>. True means
42
+ # "permitted", and false means "not permitted".
43
+ # All permissions default to <tt>true</tt>.
44
+ #
45
+ # The following permissions can be specified:
46
+ #
47
+ # <tt>:print_document</tt>:: Print document.
48
+ #
49
+ # <tt>:modify_document</tt>:: Modify contents of document (other than text
50
+ # annotations and interactive form fields).
51
+ #
52
+ # <tt>:copy_contents</tt>:: Copy text and graphics from document.
53
+ #
54
+ # <tt>:modify_annotations</tt>:: Add or modify text annotations and
55
+ # interactive form fields.
56
+ #
57
+ # == Examples
58
+ #
59
+ # Deny printing to everyone, but allow anyone to open without a password:
60
+ #
61
+ # encrypt_document :permissions => { :print_document => false },
62
+ # :owner_password => :random
63
+ #
64
+ # Set a user and owner password on the document, with full permissions for
65
+ # both the user and the owner:
66
+ #
67
+ # encrypt_document :user_password => 'foo', :owner_password => 'bar'
68
+ #
69
+ # Set no passwords, grant all permissions (This is useful because the
70
+ # default in some readers, if no permissions are specified, is "deny"):
71
+ #
72
+ # encrypt_document
73
+ #
74
+ # == Caveats
75
+ #
76
+ # * The encryption used is weak; the key is password-derived and is
77
+ # limited to 40 bits, due to US export controls in effect at the time
78
+ # the PDF standard was written.
79
+ #
80
+ # * There is nothing technologically requiring PDF readers to respect the
81
+ # permissions embedded in a document. Many PDF readers do not.
82
+ #
83
+ # * In short, you have <b>no security at all</b> against a moderately
84
+ # motivated person. Don't use this for anything super-serious. This is
85
+ # not a limitation of Prawn, but is rather a built-in limitation of the
86
+ # PDF format.
87
+ #
88
+ def encrypt_document(options={})
89
+ Prawn.verify_options [:user_password, :owner_password, :permissions],
90
+ options
91
+ @user_password = options.delete(:user_password) || ""
92
+
93
+ @owner_password = options.delete(:owner_password) || @user_password
94
+ if @owner_password == :random
95
+ # Generate a completely ridiculous password
96
+ @owner_password = (1..32).map{ rand(256) }.pack("c*")
97
+ end
98
+
99
+ self.permissions = options.delete(:permissions) || {}
100
+
101
+ # Shove the necessary entries in the trailer.
102
+ @trailer[:Encrypt] = encryption_dictionary
103
+ @encrypted = true
104
+ end
105
+
106
+ # Encrypts the given string under the given key, also requiring the
107
+ # object ID and generation number of the reference.
108
+ # See Algorithm 3.1.
109
+ def self.encrypt_string(str, key, id, gen)
110
+ # Convert ID and Gen number into little-endian truncated byte strings
111
+ id = [id].pack('V')[0,3]
112
+ gen = [gen].pack('V')[0,2]
113
+ extended_key = "#{key}#{id}#{gen}"
114
+
115
+ # Compute the RC4 key from the extended key and perform the encryption
116
+ rc4_key = Digest::MD5.digest(extended_key)[0, 10]
117
+ Arcfour.new(rc4_key).encrypt(str)
118
+ end
119
+
120
+ private
121
+
122
+ # Provides the values for the trailer encryption dictionary.
123
+ def encryption_dictionary
124
+ { :Filter => :Standard, # default PDF security handler
125
+ :V => 1, # "Algorithm 3.1", PDF reference 1.3
126
+ :R => 2, # Revision 2 of the algorithm
127
+ :O => ByteString.new(owner_password_hash),
128
+ :U => ByteString.new(user_password_hash),
129
+ :P => permissions_value }
130
+ end
131
+
132
+ # Flags in the permissions word, numbered as LSB = 1
133
+ PermissionsBits = { :print_document => 3,
134
+ :modify_contents => 4,
135
+ :copy_contents => 5,
136
+ :modify_annotations => 6 }
137
+
138
+ FullPermissions = 0b1111_1111_1111_1111_1111_1111_1111_1111
139
+
140
+ def permissions=(perms={})
141
+ @permissions ||= FullPermissions
142
+ perms.each do |key, value|
143
+ # 0-based bit number, from LSB
144
+ bit_position = PermissionsBits[key] - 1
145
+
146
+ if value # set bit
147
+ @permissions |= (1 << bit_position)
148
+ else # clear bit
149
+ @permissions &= ~(1 << bit_position)
150
+ end
151
+ end
152
+ end
153
+
154
+ def permissions_value
155
+ @permissions || FullPermissions
156
+ end
157
+
158
+ PasswordPadding =
159
+ "28BF4E5E4E758A4164004E56FFFA01082E2E00B6D0683E802F0CA9FE6453697A".
160
+ scan(/../).map{|x| x.to_i(16)}.pack("c*")
161
+
162
+ # Pads or truncates a password to 32 bytes as per Alg 3.2.
163
+ def pad_password(password)
164
+ password = password[0, 32]
165
+ password + PasswordPadding[0, 32 - password.length]
166
+ end
167
+
168
+ def user_encryption_key
169
+ @user_encryption_key ||= begin
170
+ md5 = Digest::MD5.new
171
+ md5 << pad_password(@user_password)
172
+ md5 << owner_password_hash
173
+ md5 << [permissions_value].pack("V")
174
+ md5.digest[0, 5]
175
+ end
176
+ end
177
+
178
+ # The O (owner) value in the encryption dictionary. Algorithm 3.3.
179
+ def owner_password_hash
180
+ @owner_password_hash ||= begin
181
+ key = Digest::MD5.digest(pad_password(@owner_password))[0, 5]
182
+ Arcfour.new(key).encrypt(pad_password(@user_password))
183
+ end
184
+ end
185
+
186
+ # The U (user) value in the encryption dictionary. Algorithm 3.4.
187
+ def user_password_hash
188
+ Arcfour.new(user_encryption_key).encrypt(PasswordPadding)
189
+ end
190
+
191
+ end
192
+
193
+ end
194
+
195
+ # Like PdfObject, but returns an encrypted result if required.
196
+ # For direct objects, requires the object identifier and generation number
197
+ # from the indirect object referencing obj.
198
+ def EncryptedPdfObject(obj, key, id, gen, in_content_stream=false)
199
+ case obj
200
+ when Array
201
+ "[" << obj.map { |e|
202
+ EncryptedPdfObject(e, key, id, gen, in_content_stream)
203
+ }.join(' ') << "]"
204
+ when Prawn::LiteralString
205
+ # FIXME: encrypted?
206
+ obj = obj.gsub(/[\\\n\(\)]/) { |m| "\\#{m}" }
207
+ "(#{obj})"
208
+ when Time
209
+ # FIXME: encrypted?
210
+ obj = obj.strftime("D:%Y%m%d%H%M%S%z").chop.chop + "'00'"
211
+ obj = obj.gsub(/[\\\n\(\)]/) { |m| "\\#{m}" }
212
+ "(#{obj})"
213
+ when String
214
+ PdfObject(
215
+ ByteString.new(Document::Security.encrypt_string(obj, key, id, gen)),
216
+ in_content_stream)
217
+ when Hash
218
+ output = "<< "
219
+ obj.each do |k,v|
220
+ unless String === k || Symbol === k
221
+ raise Prawn::Errors::FailedObjectConversion,
222
+ "A PDF Dictionary must be keyed by names"
223
+ end
224
+ output << PdfObject(k.to_sym, in_content_stream) << " " <<
225
+ EncryptedPdfObject(v, key, id, gen, in_content_stream) << "\n"
226
+ end
227
+ output << ">>"
228
+ when Prawn::NameTree::Value
229
+ PdfObject(obj.name) + " " +
230
+ EncryptedPdfObject(obj.value, key, id, gen, in_content_stream)
231
+ else # delegate back to PdfObject
232
+ PdfObject(obj, in_content_stream)
233
+ end
234
+ end
235
+
236
+ class Reference
237
+
238
+ # Returns the object definition for the object this references, keyed from
239
+ # +key+.
240
+ def encrypted_object(key)
241
+ @on_encode.call(self) if @on_encode
242
+ output = "#{@identifier} #{gen} obj\n" <<
243
+ Prawn::EncryptedPdfObject(data, key, @identifier, gen) << "\n"
244
+ if @stream
245
+ output << "stream\n" <<
246
+ Document::Security.encrypt_string(@stream, key, @identifier, gen) <<
247
+ "\nendstream\n"
248
+ end
249
+ output << "endobj\n"
250
+ end
251
+
252
+ end
253
+ end
254
+
255
+ module Prawn::Document::Internals
256
+
257
+ # Prawn/Security patches render_body so that it spits out encrypted content
258
+ # iff the document is encrypted.
259
+ def render_body(output)
260
+ @store.each do |ref|
261
+ ref.offset = output.size
262
+ output << (@encrypted ? ref.encrypted_object(user_encryption_key) :
263
+ ref.object)
264
+ end
265
+ end
266
+
267
+ end
268
+
269
+ Prawn::Document.send(:include, Prawn::Document::Security)
270
+
@@ -0,0 +1,120 @@
1
+ # encoding: utf-8
2
+ require "tempfile"
3
+
4
+ require File.join(File.expand_path(File.dirname(__FILE__)), "spec_helper")
5
+
6
+ describe "Document encryption" do
7
+
8
+ describe "Password padding" do
9
+
10
+ include Prawn::Document::Security
11
+
12
+ it "should truncate long passwords" do
13
+ pw = "Long long string" * 30
14
+ padded = pad_password(pw)
15
+ padded.length.should == 32
16
+ padded.should == pw[0, 32]
17
+ end
18
+
19
+ it "should pad short passwords" do
20
+ pw = "abcd"
21
+ padded = pad_password(pw)
22
+ padded.length.should == 32
23
+ padded.should == pw + Prawn::Document::Security::PasswordPadding[0, 28]
24
+ end
25
+
26
+ it "should fully pad null passwords" do
27
+ pw = ""
28
+ padded = pad_password(pw)
29
+ padded.length.should == 32
30
+ padded.should == Prawn::Document::Security::PasswordPadding
31
+ end
32
+
33
+ end
34
+
35
+ describe "Setting permissions" do
36
+
37
+ def doc_with_permissions(permissions)
38
+ pdf = Prawn::Document.new
39
+
40
+ class << pdf
41
+ # Make things easier to test
42
+ public :permissions_value
43
+ end
44
+
45
+ pdf.encrypt_document(:permissions => permissions)
46
+ pdf
47
+ end
48
+
49
+ it "should default to full permissions" do
50
+ doc_with_permissions({}).permissions_value.should == 0xFFFFFFFF
51
+ doc_with_permissions(:print_document => true,
52
+ :modify_contents => true,
53
+ :copy_contents => true,
54
+ :modify_annotations => true).permissions_value.
55
+ should == 0xFFFFFFFF
56
+ end
57
+
58
+ it "should clear the appropriate bits for each permission flag" do
59
+ doc_with_permissions(:print_document => false).permissions_value.
60
+ should == 0b1111_1111_1111_1111_1111_1111_1111_1011
61
+ doc_with_permissions(:modify_contents => false).permissions_value.
62
+ should == 0b1111_1111_1111_1111_1111_1111_1111_0111
63
+ doc_with_permissions(:copy_contents => false).permissions_value.
64
+ should == 0b1111_1111_1111_1111_1111_1111_1110_1111
65
+ doc_with_permissions(:modify_annotations => false).permissions_value.
66
+ should == 0b1111_1111_1111_1111_1111_1111_1101_1111
67
+ end
68
+
69
+ end
70
+
71
+ describe "Encryption keys" do
72
+ # Since PDF::Reader doesn't read encrypted PDF files, we just take the
73
+ # roundabout method of verifying each step of the encryption. This works
74
+ # fine because the encryption method is deterministic.
75
+
76
+ before(:each) do
77
+ @pdf = Prawn::Document.new
78
+ class << @pdf
79
+ public :owner_password_hash, :user_password_hash, :user_encryption_key
80
+ end
81
+ @pdf.encrypt_document :user_password => 'foo', :owner_password => 'bar',
82
+ :permissions => { :print_document => false }
83
+ end
84
+
85
+ it "should calculate the correct owner hash" do
86
+ @pdf.owner_password_hash.unpack("H*").first.should.match(/^61CA855012/i)
87
+ end
88
+
89
+ it "should calculate the correct user hash" do
90
+ @pdf.user_password_hash.unpack("H*").first.should =~ /^6BC8C51031/i
91
+ end
92
+
93
+ it "should calculate the correct user_encryption_key" do
94
+ @pdf.user_encryption_key.unpack("H*").first.upcase.should == "B100AB6429"
95
+ end
96
+
97
+
98
+ end
99
+
100
+ describe "EncryptedPdfObject" do
101
+
102
+ it "should delegate to PdfObject for simple types" do
103
+ Prawn::EncryptedPdfObject(true, nil, nil, nil).should == "true"
104
+ Prawn::EncryptedPdfObject(42, nil, nil, nil).should == "42"
105
+ end
106
+
107
+ it "should encrypt strings properly" do
108
+ Prawn::EncryptedPdfObject("foo", "12345", 123, 0).should == "<4ad6e3>"
109
+ end
110
+
111
+ it "should properly handle compound types" do
112
+ Prawn::EncryptedPdfObject({:Bar => "foo"}, "12345", 123, 0).should ==
113
+ "<< /Bar <4ad6e3>\n>>"
114
+ Prawn::EncryptedPdfObject(["foo", "bar"], "12345", 123, 0).should ==
115
+ "[<4ad6e3> <4ed8fe>]"
116
+ end
117
+
118
+ end
119
+
120
+ end
@@ -0,0 +1,13 @@
1
+ # encoding: utf-8
2
+
3
+ puts "Prawn/Security specs: Running on Ruby Version: #{RUBY_VERSION}"
4
+
5
+ require "rubygems"
6
+ require "test/spec"
7
+ require "mocha"
8
+ $LOAD_PATH.unshift File.join(File.dirname(__FILE__), '..', 'lib')
9
+ require "prawn/core"
10
+ require "prawn/security"
11
+
12
+ Prawn.debug = true
13
+
metadata ADDED
@@ -0,0 +1,70 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: prawn-security
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - Brad Ediger
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2009-11-10 00:00:00 -05:00
13
+ default_executable:
14
+ dependencies: []
15
+
16
+ description: " Prawn/Security adds document encryption, password protection, and permissions to Prawn.\n"
17
+ email: brad.ediger@madriska.com
18
+ executables: []
19
+
20
+ extensions: []
21
+
22
+ extra_rdoc_files:
23
+ - README
24
+ - LICENSE
25
+ - COPYING
26
+ files:
27
+ - examples/example_helper.rb
28
+ - examples/hello_foo.rb
29
+ - lib/prawn/arcfour.rb
30
+ - lib/prawn/security.rb
31
+ - spec/security_spec.rb
32
+ - spec/spec_helper.rb
33
+ - Rakefile
34
+ - README
35
+ - LICENSE
36
+ - COPYING
37
+ has_rdoc: true
38
+ homepage: http://github.com/madriska/prawn-security/
39
+ licenses: []
40
+
41
+ post_install_message:
42
+ rdoc_options:
43
+ - --title
44
+ - Prawn/Security Documentation
45
+ - --main
46
+ - README
47
+ - -q
48
+ require_paths:
49
+ - lib
50
+ required_ruby_version: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: "0"
55
+ version:
56
+ required_rubygems_version: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: "0"
61
+ version:
62
+ requirements: []
63
+
64
+ rubyforge_project: prawn-security
65
+ rubygems_version: 1.3.5
66
+ signing_key:
67
+ specification_version: 3
68
+ summary: Popular Password Protection & Permissions for Prawn PDFs
69
+ test_files:
70
+ - spec/security_spec.rb