1CBC(3) User Contributed Perl Documentation CBC(3)
2
3
4
6 Crypt::CBC - Encrypt Data with Cipher Block Chaining Mode
7
9 use Crypt::CBC;
10 $cipher = Crypt::CBC->new( -key => 'my secret key',
11 -cipher => 'Blowfish'
12 );
13
14 $ciphertext = $cipher->encrypt("This data is hush hush");
15 $plaintext = $cipher->decrypt($ciphertext);
16
17 $cipher->start('encrypting');
18 open(F,"./BIG_FILE");
19 while (read(F,$buffer,1024)) {
20 print $cipher->crypt($buffer);
21 }
22 print $cipher->finish;
23
24 # do-it-yourself mode -- specify key, initialization vector yourself
25 $key = Crypt::CBC->random_bytes(8); # assuming a 8-byte block cipher
26 $iv = Crypt::CBC->random_bytes(8);
27 $cipher = Crypt::CBC->new(-literal_key => 1,
28 -key => $key,
29 -iv => $iv,
30 -header => 'none');
31
32 $ciphertext = $cipher->encrypt("This data is hush hush");
33 $plaintext = $cipher->decrypt($ciphertext);
34
35 # RANDOMIV-compatible mode
36 $cipher = Crypt::CBC->new(-key => 'Super Secret!'
37 -header => 'randomiv');
38
40 This module is a Perl-only implementation of the cryptographic cipher
41 block chaining mode (CBC). In combination with a block cipher such as
42 DES or IDEA, you can encrypt and decrypt messages of arbitrarily long
43 length. The encrypted messages are compatible with the encryption for‐
44 mat used by the OpenSSL package.
45
46 To use this module, you will first create a Crypt::CBC cipher object
47 with new(). At the time of cipher creation, you specify an encryption
48 key to use and, optionally, a block encryption algorithm. You will
49 then call the start() method to initialize the encryption or decryption
50 process, crypt() to encrypt or decrypt one or more blocks of data, and
51 lastly finish(), to pad and encrypt the final block. For your conve‐
52 nience, you can call the encrypt() and decrypt() methods to operate on
53 a whole data value at once.
54
55 new()
56
57 $cipher = Crypt::CBC->new( -key => 'my secret key',
58 -cipher => 'Blowfish',
59 );
60
61 # or (for compatibility with versions prior to 2.13)
62 $cipher = Crypt::CBC->new( {
63 key => 'my secret key',
64 cipher => 'Blowfish'
65 }
66 );
67
68 # or (for compatibility with versions prior to 2.0)
69 $cipher = new Crypt::CBC('my secret key' => 'Blowfish');
70
71 The new() method creates a new Crypt::CBC object. It accepts a list of
72 -argument => value pairs selected from the following list:
73
74 Argument Description
75 -------- -----------
76
77 -key The encryption/decryption key (required)
78
79 -cipher The cipher algorithm (defaults to Crypt::DES), or
80 a preexisting cipher object.
81
82 -salt Enables OpenSSL-compatibility. If equal to a value
83 of "1" then causes a random salt to be generated
84 and used to derive the encryption key and IV. Other
85 true values are taken to be the literal salt.
86
87 -iv The initialization vector (IV)
88
89 -header What type of header to prepend to ciphertext. One of
90 'salt' -- use OpenSSL-compatible salted header
91 'randomiv' -- Randomiv-compatible "RandomIV" header
92 'none' -- prepend no header at all
93
94 -padding The padding method, one of "standard", "space",
95 "onesandzeroes", or "null". (default "standard")
96
97 -literal_key If true, the key provided by "key" is used directly
98 for encryption/decryption. Otherwise the actual
99 key used will be a hash of the provided key.
100 (default false)
101
102 -pcbc Whether to use the PCBC chaining algorithm rather than
103 the standard CBC algorithm (default false).
104
105 -keysize Force the cipher keysize to the indicated number of bytes.
106
107 -blocksize Force the cipher blocksize to the indicated number of bytes.
108
109 -insecure_legacy_decrypt
110 Allow decryption of data encrypted using the "RandomIV" header
111 produced by pre-2.17 versions of Crypt::CBC.
112
113 -add_header [deprecated; use -header instread]
114 Whether to add the salt and IV to the header of the output
115 cipher text.
116
117 -regenerate_key [deprecated; use literal_key instead]
118 Whether to use a hash of the provided key to generate
119 the actual encryption key (default true)
120
121 -prepend_iv [deprecated; use add_header instead]
122 Whether to prepend the IV to the beginning of the
123 encrypted stream (default true)
124
125 Crypt::CBC requires three pieces of information to do its job. First it
126 needs the name of the block cipher algorithm that will encrypt or
127 decrypt the data in blocks of fixed length known as the cipher's
128 "blocksize." Second, it needs an encryption/decryption key to pass to
129 the block cipher. Third, it needs an initialization vector (IV) that
130 will be used to propagate information from one encrypted block to the
131 next. Both the key and the IV must be exactly the same length as the
132 chosen cipher's blocksize.
133
134 Crypt::CBC can derive the key and the IV from a passphrase that you
135 provide, or can let you specify the true key and IV manually. In addi‐
136 tion, you have the option of embedding enough information to regenerate
137 the IV in a short header that is emitted at the start of the encrypted
138 stream, or outputting a headerless encryption stream. In the first
139 case, Crypt::CBC will be able to decrypt the stream given just the
140 original key or passphrase. In the second case, you will have to pro‐
141 vide the original IV as well as the key/passphrase.
142
143 The -cipher option specifies which block cipher algorithm to use to
144 encode each section of the message. This argument is optional and will
145 default to the quick-but-not-very-secure DES algorithm unless specified
146 otherwise. You may use any compatible block encryption algorithm that
147 you have installed. Currently, this includes Crypt::DES,
148 Crypt::DES_EDE3, Crypt::IDEA, Crypt::Blowfish, Crypt::CAST5 and
149 Crypt::Rijndael. You may refer to them using their full names
150 ("Crypt::IDEA") or in abbreviated form ("IDEA").
151
152 Instead of passing the name of a cipher class, you may pass an already-
153 created block cipher object. This allows you to take advantage of
154 cipher algorithms that have parameterized new() methods, such as
155 Crypt::Eksblowfish:
156
157 my $eksblowfish = Crypt::Eksblowfish->new(8,$salt,$key);
158 my $cbc = Crypt::CBC->new(-cipher=>$eksblowfish);
159
160 The -key argument provides either a passphrase to use to generate the
161 encryption key, or the literal value of the block cipher key. If used
162 in passphrase mode (which is the default), -key can be any number of
163 characters; the actual key will be derived by passing the passphrase
164 through a series of MD5 hash operations. To take full advantage of a
165 given block cipher, the length of the passphrase should be at least
166 equal to the cipher's blocksize. To skip this hashing operation and
167 specify the key directly, pass a true value to the -literal_key option.
168 In this case, you should choose a key of length exactly equal to the
169 cipher's key length. You should also specify the IV yourself and a
170 -header mode of 'none'.
171
172 If you pass an existing Crypt::* object to new(), then the -key argu‐
173 ment is ignored and the module will generate a warning.
174
175 The -header argument specifies what type of header, if any, to prepend
176 to the beginning of the encrypted data stream. The header allows
177 Crypt::CBC to regenerate the original IV and correctly decrypt the data
178 without your having to provide the same IV used to encrypt the data.
179 Valid values for the -header are:
180
181 "salt" -- Combine the passphrase with an 8-byte random value to
182 generate both the block cipher key and the IV from the
183 provided passphrase. The salt will be appended to the
184 beginning of the data stream allowing decryption to
185 regenerate both the key and IV given the correct passphrase.
186 This method is compatible with current versions of OpenSSL.
187
188 "randomiv" -- Generate the block cipher key from the passphrase, and
189 choose a random 8-byte value to use as the IV. The IV will
190 be prepended to the data stream. This method is compatible
191 with ciphertext produced by versions of the library prior to
192 2.17, but is incompatible with block ciphers that have non
193 8-byte block sizes, such as Rijndael. Crypt::CBC will exit
194 with a fatal error if you try to use this header mode with a
195 non 8-byte cipher.
196
197 "none" -- Do not generate a header. To decrypt a stream encrypted
198 in this way, you will have to provide the original IV
199 manually.
200
201 The "salt" header is now the default as of Crypt::CBC version 2.17. In
202 all earlier versions "randomiv" was the default.
203
204 When using a "salt" header, you may specify your own value of the salt,
205 by passing the desired 8-byte salt to the -salt argument. Otherwise,
206 the module will generate a random salt for you. Crypt::CBC will gener‐
207 ate a fatal error if you specify a salt value that isn't exactly 8
208 bytes long. For backward compatibility reasons, passing a value of "1"
209 will generate a random salt, the same as if no -salt argument was pro‐
210 vided.
211
212 The -padding argument controls how the last few bytes of the encrypted
213 stream are dealt with when they not an exact multiple of the cipher
214 block length. The default is "standard", the method specified in
215 PKCS#5.
216
217 The -pcbc argument, if true, activates a modified chaining mode known
218 as PCBC. It provides better error propagation characteristics than the
219 default CBC encryption and is required for authenticating to Kerberos4
220 systems (see RFC 2222).
221
222 The -keysize and -blocksize arguments can be used to force the cipher's
223 keysize and/or blocksize. This is only currently useful for the
224 Crypt::Blowfish module, which accepts a variable length keysize. If
225 -keysize is not specified, then Crypt::CBC will use the maximum length
226 Blowfish key size of 56 bytes (448 bits). The Openssl library defaults
227 to 16 byte Blowfish key sizes, so for compatibility with Openssl you
228 may wish to set -keysize=>16. There are currently no Crypt::* modules
229 that have variable block sizes, but an option to change the block size
230 is provided just in case.
231
232 For compatibility with earlier versions of this module, you can provide
233 new() with a hashref containing key/value pairs. The key names are the
234 same as the arguments described earlier, but without the initial
235 hyphen. You may also call new() with one or two positional arguments,
236 in which case the first argument is taken to be the key and the second
237 to be the optional block cipher algorithm.
238
239 IMPORTANT NOTE: Versions of this module prior to 2.17 were incorrectly
240 using 8-byte IVs when generating the "randomiv" style of header, even
241 when the chosen cipher's blocksize was greater than 8 bytes. This pri‐
242 marily affects the Rijndael algorithm. Such encrypted data streams were
243 not secure. From versions 2.17 onward, Crypt::CBC will refuse to
244 encrypt or decrypt using the "randomiv" header and non-8 byte block
245 ciphers. To decrypt legacy data encrypted with earlier versions of the
246 module, you can override the check using the -insecure_legacy_decrypt
247 option. It is not possible to override encryption. Please use the
248 default "salt" header style, or no headers at all.
249
250 start()
251
252 $cipher->start('encrypting');
253 $cipher->start('decrypting');
254
255 The start() method prepares the cipher for a series of encryption or
256 decryption steps, resetting the internal state of the cipher if neces‐
257 sary. You must provide a string indicating whether you wish to encrypt
258 or decrypt. "E" or any word that begins with an "e" indicates encryp‐
259 tion. "D" or any word that begins with a "d" indicates decryption.
260
261 crypt()
262
263 $ciphertext = $cipher->crypt($plaintext);
264
265 After calling start(), you should call crypt() as many times as neces‐
266 sary to encrypt the desired data.
267
268 finish()
269
270 $ciphertext = $cipher->finish();
271
272 The CBC algorithm must buffer data blocks inernally until they are even
273 multiples of the encryption algorithm's blocksize (typically 8 bytes).
274 After the last call to crypt() you should call finish(). This flushes
275 the internal buffer and returns any leftover ciphertext.
276
277 In a typical application you will read the plaintext from a file or
278 input stream and write the result to standard output in a loop that
279 might look like this:
280
281 $cipher = new Crypt::CBC('hey jude!');
282 $cipher->start('encrypting');
283 print $cipher->crypt($_) while <>;
284 print $cipher->finish();
285
286 encrypt()
287
288 $ciphertext = $cipher->encrypt($plaintext)
289
290 This convenience function runs the entire sequence of start(), crypt()
291 and finish() for you, processing the provided plaintext and returning
292 the corresponding ciphertext.
293
294 decrypt()
295
296 $plaintext = $cipher->decrypt($ciphertext)
297
298 This convenience function runs the entire sequence of start(), crypt()
299 and finish() for you, processing the provided ciphertext and returning
300 the corresponding plaintext.
301
302 encrypt_hex(), decrypt_hex()
303
304 $ciphertext = $cipher->encrypt_hex($plaintext)
305 $plaintext = $cipher->decrypt_hex($ciphertext)
306
307 These are convenience functions that operate on ciphertext in a hexa‐
308 decimal representation. encrypt_hex($plaintext) is exactly equivalent
309 to unpack('H*',encrypt($plaintext)). These functions can be useful if,
310 for example, you wish to place the encrypted in an email message.
311
312 get_initialization_vector()
313
314 $iv = $cipher->get_initialization_vector()
315
316 This function will return the IV used in encryption and or decryption.
317 The IV is not guaranteed to be set when encrypting until start() is
318 called, and when decrypting until crypt() is called the first time.
319 Unless the IV was manually specified in the new() call, the IV will
320 change with every complete encryption operation.
321
322 set_initialization_vector()
323
324 $cipher->set_initialization_vector('76543210')
325
326 This function sets the IV used in encryption and/or decryption. This
327 function may be useful if the IV is not contained within the ciphertext
328 string being decrypted, or if a particular IV is desired for encryp‐
329 tion. Note that the IV must match the chosen cipher's blocksize bytes
330 in length.
331
332 iv()
333
334 $iv = $cipher->iv();
335 $cipher->iv($new_iv);
336
337 As above, but using a single method call.
338
339 key()
340
341 $key = $cipher->key();
342 $cipher->key($new_key);
343
344 Get or set the block cipher key used for encryption/decryption. When
345 encrypting, the key is not guaranteed to exist until start() is called,
346 and when decrypting, the key is not guaranteed to exist until after the
347 first call to crypt(). The key must match the length required by the
348 underlying block cipher.
349
350 When salted headers are used, the block cipher key will change after
351 each complete sequence of encryption operations.
352
353 salt()
354
355 $salt = $cipher->salt();
356 $cipher->salt($new_salt);
357
358 Get or set the salt used for deriving the encryption key and IV when in
359 OpenSSL compatibility mode.
360
361 passphrase()
362
363 $passphrase = $cipher->passphrase();
364 $cipher->passphrase($new_passphrase);
365
366 This gets or sets the value of the key passed to new() when literal_key
367 is false.
368
369 $data = get_random_bytes($numbytes)
370
371 Return $numbytes worth of random data. On systems that support the
372 "/dev/urandom" device file, this data will be read from the device.
373 Otherwise, it will be generated by repeated calls to the Perl rand()
374 function.
375
376 cipher(), padding(), keysize(), blocksize(), pcbc()
377
378 These read-only methods return the identity of the chosen block cipher
379 algorithm, padding method, key and block size of the chosen block
380 cipher, and whether PCBC chaining is in effect.
381
382 Padding methods
383
384 Use the 'padding' option to change the padding method.
385
386 When the last block of plaintext is shorter than the block size, it
387 must be padded. Padding methods include: "standard" (i.e., PKCS#5),
388 "oneandzeroes", "space", and "null".
389
390 standard: (default) Binary safe
391 pads with the number of bytes that should be truncated. So, if
392 blocksize is 8, then "0A0B0C" will be padded with "05", resulting
393 in "0A0B0C0505050505". If the final block is a full block of 8
394 bytes, then a whole block of "0808080808080808" is appended.
395
396 oneandzeroes: Binary safe
397 pads with "80" followed by as many "00" necessary to fill the
398 block. If the last block is a full block and blocksize is 8, a
399 block of "8000000000000000" will be appended.
400
401 null: text only
402 pads with as many "00" necessary to fill the block. If the last
403 block is a full block and blocksize is 8, a block of
404 "0000000000000000" will be appended.
405
406 space: text only
407 same as "null", but with "20".
408
409 Both the standard and oneandzeroes paddings are binary safe. The space
410 and null paddings are recommended only for text data. Which type of
411 padding you use depends on whether you wish to communicate with an
412 external (non Crypt::CBC library). If this is the case, use whatever
413 padding method is compatible.
414
415 You can also pass in a custom padding function. To do this, create a
416 function that takes the arguments:
417
418 $padded_block = function($block,$blocksize,$direction);
419
420 where $block is the current block of data, $blocksize is the size to
421 pad it to, $direction is "e" for encrypting and "d" for decrypting, and
422 $padded_block is the result after padding or depadding.
423
424 When encrypting, the function should always return a string of <block‐
425 size> length, and when decrypting, can expect the string coming in to
426 always be that length. See _standard_padding(), _space_padding(),
427 _null_padding(), or _oneandzeroes_padding() in the source for examples.
428
429 Standard and oneandzeroes padding are recommended, as both space and
430 null padding can potentially truncate more characters than they should.
431
433 Two examples, des.pl and idea.pl can be found in the eg/ subdirectory
434 of the Crypt-CBC distribution. These implement command-line DES and
435 IDEA encryption algorithms.
436
438 The encryption and decryption process is about a tenth the speed of the
439 equivalent SSLeay programs (compiled C). This could be improved by
440 implementing this module in C. It may also be worthwhile to optimize
441 the DES and IDEA block algorithms further.
442
444 Please report them.
445
447 Lincoln Stein, lstein@cshl.org
448
449 This module is distributed under the ARTISTIC LICENSE using the same
450 terms as Perl itself.
451
453 perl(1), Crypt::DES(3), Crypt::IDEA(3), rfc2898 (PKCS#5)
454
455
456
457perl v5.8.8 2006-10-29 CBC(3)