1CBC(3)                User Contributed Perl Documentation               CBC(3)
2
3
4

NAME

6       Crypt::CBC - Encrypt Data with Cipher Block Chaining Mode
7

SYNOPSIS

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

DESCRIPTION

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
44       format 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
52       convenience, you can call the encrypt() and decrypt() methods to
53       operate on a whole data value at once.
54
55   new()
56         $cipher = Crypt::CBC->new( -key    => 'my secret key',
57                                    -cipher => 'Blowfish',
58                                  );
59
60         # or (for compatibility with versions prior to 2.13)
61         $cipher = Crypt::CBC->new( {
62                                     key    => 'my secret key',
63                                     cipher => 'Blowfish'
64                                    }
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" (default),
95                            "space", "oneandzeroes", "rijndael_compat",
96                            "null", or "none" (default "standard").
97
98         -literal_key    If true, the key provided by "key" is used directly
99                             for encryption/decryption.  Otherwise the actual
100                             key used will be a hash of the provided key.
101                             (default false)
102
103         -pcbc           Whether to use the PCBC chaining algorithm rather than
104                           the standard CBC algorithm (default false).
105
106         -keysize        Force the cipher keysize to the indicated number of bytes.
107
108         -blocksize      Force the cipher blocksize to the indicated number of bytes.
109
110         -insecure_legacy_decrypt
111                         Allow decryption of data encrypted using the "RandomIV" header
112                           produced by pre-2.17 versions of Crypt::CBC.
113
114         -add_header     [deprecated; use -header instread]
115                          Whether to add the salt and IV to the header of the output
116                           cipher text.
117
118         -regenerate_key [deprecated; use literal_key instead]
119                         Whether to use a hash of the provided key to generate
120                           the actual encryption key (default true)
121
122         -prepend_iv     [deprecated; use add_header instead]
123                         Whether to prepend the IV to the beginning of the
124                           encrypted stream (default true)
125
126       Crypt::CBC requires three pieces of information to do its job. First it
127       needs the name of the block cipher algorithm that will encrypt or
128       decrypt the data in blocks of fixed length known as the cipher's
129       "blocksize." Second, it needs an encryption/decryption key to pass to
130       the block cipher. Third, it needs an initialization vector (IV) that
131       will be used to propagate information from one encrypted block to the
132       next. Both the key and the IV must be exactly the same length as the
133       chosen cipher's blocksize.
134
135       Crypt::CBC can derive the key and the IV from a passphrase that you
136       provide, or can let you specify the true key and IV manually. In
137       addition, you have the option of embedding enough information to
138       regenerate the IV in a short header that is emitted at the start of the
139       encrypted stream, or outputting a headerless encryption stream. In the
140       first case, Crypt::CBC will be able to decrypt the stream given just
141       the original key or passphrase. In the second case, you will have to
142       provide the original IV as well as the key/passphrase.
143
144       The -cipher option specifies which block cipher algorithm to use to
145       encode each section of the message.  This argument is optional and will
146       default to the quick-but-not-very-secure DES algorithm unless specified
147       otherwise. You may use any compatible block encryption algorithm that
148       you have installed. Currently, this includes Crypt::DES,
149       Crypt::DES_EDE3, Crypt::IDEA, Crypt::Blowfish, Crypt::CAST5 and
150       Crypt::Rijndael. You may refer to them using their full names
151       ("Crypt::IDEA") or in abbreviated form ("IDEA").
152
153       Instead of passing the name of a cipher class, you may pass an already-
154       created block cipher object. This allows you to take advantage of
155       cipher algorithms that have parameterized new() methods, such as
156       Crypt::Eksblowfish:
157
158         my $eksblowfish = Crypt::Eksblowfish->new(8,$salt,$key);
159         my $cbc         = Crypt::CBC->new(-cipher=>$eksblowfish);
160
161       The -key argument provides either a passphrase to use to generate the
162       encryption key, or the literal value of the block cipher key. If used
163       in passphrase mode (which is the default), -key can be any number of
164       characters; the actual key will be derived by passing the passphrase
165       through a series of MD5 hash operations. To take full advantage of a
166       given block cipher, the length of the passphrase should be at least
167       equal to the cipher's blocksize. To skip this hashing operation and
168       specify the key directly, pass a true value to the -literal_key option.
169       In this case, you should choose a key of length exactly equal to the
170       cipher's key length. You should also specify the IV yourself and a
171       -header mode of 'none'.
172
173       If you pass an existing Crypt::* object to new(), then the -key
174       argument is ignored and the module will generate a warning.
175
176       The -header argument specifies what type of header, if any, to prepend
177       to the beginning of the encrypted data stream. The header allows
178       Crypt::CBC to regenerate the original IV and correctly decrypt the data
179       without your having to provide the same IV used to encrypt the data.
180       Valid values for the -header are:
181
182        "salt" -- Combine the passphrase with an 8-byte random value to
183                  generate both the block cipher key and the IV from the
184                  provided passphrase. The salt will be appended to the
185                  beginning of the data stream allowing decryption to
186                  regenerate both the key and IV given the correct passphrase.
187                  This method is compatible with current versions of OpenSSL.
188
189        "randomiv" -- Generate the block cipher key from the passphrase, and
190                  choose a random 8-byte value to use as the IV. The IV will
191                  be prepended to the data stream. This method is compatible
192                  with ciphertext produced by versions of the library prior to
193                  2.17, but is incompatible with block ciphers that have non
194                  8-byte block sizes, such as Rijndael. Crypt::CBC will exit
195                  with a fatal error if you try to use this header mode with a
196                  non 8-byte cipher.
197
198        "none"   -- Do not generate a header. To decrypt a stream encrypted
199                  in this way, you will have to provide the original IV
200                  manually.
201
202       The "salt" header is now the default as of Crypt::CBC version 2.17. In
203       all earlier versions "randomiv" was the default.
204
205       When using a "salt" header, you may specify your own value of the salt,
206       by passing the desired 8-byte salt to the -salt argument. Otherwise,
207       the module will generate a random salt for you. Crypt::CBC will
208       generate a fatal error if you specify a salt value that isn't exactly 8
209       bytes long. For backward compatibility reasons, passing a value of "1"
210       will generate a random salt, the same as if no -salt argument was
211       provided.
212
213       The -padding argument controls how the last few bytes of the encrypted
214       stream are dealt with when they not an exact multiple of the cipher
215       block length. The default is "standard", the method specified in
216       PKCS#5.
217
218       The -pcbc argument, if true, activates a modified chaining mode known
219       as PCBC. It provides better error propagation characteristics than the
220       default CBC encryption and is required for authenticating to Kerberos4
221       systems (see RFC 2222).
222
223       The -keysize and -blocksize arguments can be used to force the cipher's
224       keysize and/or blocksize. This is only currently useful for the
225       Crypt::Blowfish module, which accepts a variable length keysize. If
226       -keysize is not specified, then Crypt::CBC will use the maximum length
227       Blowfish key size of 56 bytes (448 bits). The Openssl library defaults
228       to 16 byte Blowfish key sizes, so for compatibility with Openssl you
229       may wish to set -keysize=>16. There are currently no Crypt::* modules
230       that have variable block sizes, but an option to change the block size
231       is provided just in case.
232
233       For compatibility with earlier versions of this module, you can provide
234       new() with a hashref containing key/value pairs. The key names are the
235       same as the arguments described earlier, but without the initial
236       hyphen.  You may also call new() with one or two positional arguments,
237       in which case the first argument is taken to be the key and the second
238       to be the optional block cipher algorithm.
239
240       IMPORTANT NOTE: Versions of this module prior to 2.17 were incorrectly
241       using 8-byte IVs when generating the "randomiv" style of header, even
242       when the chosen cipher's blocksize was greater than 8 bytes. This
243       primarily affects the Rijndael algorithm. Such encrypted data streams
244       were not secure. From versions 2.17 onward, Crypt::CBC will refuse to
245       encrypt or decrypt using the "randomiv" header and non-8 byte block
246       ciphers. To decrypt legacy data encrypted with earlier versions of the
247       module, you can override the check using the -insecure_legacy_decrypt
248       option. It is not possible to override encryption. Please use the
249       default "salt" header style, or no headers at all.
250
251   start()
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
257       necessary.  You must provide a string indicating whether you wish to
258       encrypt or decrypt.  "E" or any word that begins with an "e" indicates
259       encryption.  "D" or any word that begins with a "d" indicates
260       decryption.
261
262   crypt()
263          $ciphertext = $cipher->crypt($plaintext);
264
265       After calling start(), you should call crypt() as many times as
266       necessary to encrypt the desired data.
267
268   finish()
269          $ciphertext = $cipher->finish();
270
271       The CBC algorithm must buffer data blocks internally until they are
272       even multiples of the encryption algorithm's blocksize (typically 8
273       bytes).  After the last call to crypt() you should call finish().  This
274       flushes the internal buffer and returns any leftover ciphertext.
275
276       In a typical application you will read the plaintext from a file or
277       input stream and write the result to standard output in a loop that
278       might look like this:
279
280         $cipher = new Crypt::CBC('hey jude!');
281         $cipher->start('encrypting');
282         print $cipher->crypt($_) while <>;
283         print $cipher->finish();
284
285   encrypt()
286         $ciphertext = $cipher->encrypt($plaintext)
287
288       This convenience function runs the entire sequence of start(), crypt()
289       and finish() for you, processing the provided plaintext and returning
290       the corresponding ciphertext.
291
292   decrypt()
293         $plaintext = $cipher->decrypt($ciphertext)
294
295       This convenience function runs the entire sequence of start(), crypt()
296       and finish() for you, processing the provided ciphertext and returning
297       the corresponding plaintext.
298
299   encrypt_hex(), decrypt_hex()
300         $ciphertext = $cipher->encrypt_hex($plaintext)
301         $plaintext  = $cipher->decrypt_hex($ciphertext)
302
303       These are convenience functions that operate on ciphertext in a
304       hexadecimal representation.  encrypt_hex($plaintext) is exactly
305       equivalent to unpack('H*',encrypt($plaintext)).  These functions can be
306       useful if, for example, you wish to place the encrypted in an email
307       message.
308
309   get_initialization_vector()
310         $iv = $cipher->get_initialization_vector()
311
312       This function will return the IV used in encryption and or decryption.
313       The IV is not guaranteed to be set when encrypting until start() is
314       called, and when decrypting until crypt() is called the first time.
315       Unless the IV was manually specified in the new() call, the IV will
316       change with every complete encryption operation.
317
318   set_initialization_vector()
319         $cipher->set_initialization_vector('76543210')
320
321       This function sets the IV used in encryption and/or decryption. This
322       function may be useful if the IV is not contained within the ciphertext
323       string being decrypted, or if a particular IV is desired for
324       encryption.  Note that the IV must match the chosen cipher's blocksize
325       bytes in length.
326
327   iv()
328         $iv = $cipher->iv();
329         $cipher->iv($new_iv);
330
331       As above, but using a single method call.
332
333   key()
334         $key = $cipher->key();
335         $cipher->key($new_key);
336
337       Get or set the block cipher key used for encryption/decryption.  When
338       encrypting, the key is not guaranteed to exist until start() is called,
339       and when decrypting, the key is not guaranteed to exist until after the
340       first call to crypt(). The key must match the length required by the
341       underlying block cipher.
342
343       When salted headers are used, the block cipher key will change after
344       each complete sequence of encryption operations.
345
346   salt()
347         $salt = $cipher->salt();
348         $cipher->salt($new_salt);
349
350       Get or set the salt used for deriving the encryption key and IV when in
351       OpenSSL compatibility mode.
352
353   passphrase()
354         $passphrase = $cipher->passphrase();
355         $cipher->passphrase($new_passphrase);
356
357       This gets or sets the value of the key passed to new() when literal_key
358       is false.
359
360   $data = random_bytes($numbytes)
361       Return $numbytes worth of random data. On systems that support the
362       "/dev/urandom" device file, this data will be read from the device.
363       Otherwise, it will be generated by repeated calls to the Perl rand()
364       function.
365
366   cipher(), padding(), keysize(), blocksize(), pcbc()
367       These read-only methods return the identity of the chosen block cipher
368       algorithm, padding method, key and block size of the chosen block
369       cipher, and whether PCBC chaining is in effect.
370
371   Padding methods
372       Use the 'padding' option to change the padding method.
373
374       When the last block of plaintext is shorter than the block size, it
375       must be padded. Padding methods include: "standard" (i.e., PKCS#5),
376       "oneandzeroes", "space", "rijndael_compat", "null", and "none".
377
378          standard: (default) Binary safe
379             pads with the number of bytes that should be truncated. So, if
380             blocksize is 8, then "0A0B0C" will be padded with "05", resulting
381             in "0A0B0C0505050505". If the final block is a full block of 8
382             bytes, then a whole block of "0808080808080808" is appended.
383
384          oneandzeroes: Binary safe
385             pads with "80" followed by as many "00" necessary to fill the
386             block. If the last block is a full block and blocksize is 8, a
387             block of "8000000000000000" will be appended.
388
389          rijndael_compat: Binary safe, with caveats
390             similar to oneandzeroes, except that no padding is performed if
391             the last block is a full block. This is provided for
392             compatibility with Crypt::Rijndael only and can only be used
393             with messages that are a multiple of the Rijndael blocksize
394             of 16 bytes.
395
396          null: text only
397             pads with as many "00" necessary to fill the block. If the last
398             block is a full block and blocksize is 8, a block of
399             "0000000000000000" will be appended.
400
401          space: text only
402             same as "null", but with "20".
403
404          none:
405             no padding added. Useful for special-purpose applications where
406             you wish to add custom padding to the message.
407
408       Both the standard and oneandzeroes paddings are binary safe.  The space
409       and null paddings are recommended only for text data.  Which type of
410       padding you use depends on whether you wish to communicate with an
411       external (non Crypt::CBC library).  If this is the case, use whatever
412       padding method is compatible.
413
414       You can also pass in a custom padding function.  To do this, create a
415       function that takes the arguments:
416
417          $padded_block = function($block,$blocksize,$direction);
418
419       where $block is the current block of data, $blocksize is the size to
420       pad it to, $direction is "e" for encrypting and "d" for decrypting, and
421       $padded_block is the result after padding or depadding.
422
423       When encrypting, the function should always return a string of
424       <blocksize> length, and when decrypting, can expect the string coming
425       in to always be that length. See _standard_padding(), _space_padding(),
426       _null_padding(), or _oneandzeroes_padding() in the source for examples.
427
428       Standard and oneandzeroes padding are recommended, as both space and
429       null padding can potentially truncate more characters than they should.
430

EXAMPLES

432       Two examples, des.pl and idea.pl can be found in the eg/ subdirectory
433       of the Crypt-CBC distribution.  These implement command-line DES and
434       IDEA encryption algorithms.
435

LIMITATIONS

437       The encryption and decryption process is about a tenth the speed of the
438       equivalent SSLeay programs (compiled C).  This could be improved by
439       implementing this module in C.  It may also be worthwhile to optimize
440       the DES and IDEA block algorithms further.
441

BUGS

443       Please report them.
444

AUTHOR

446       Lincoln Stein, lstein@cshl.org
447
448       This module is distributed under the ARTISTIC LICENSE using the same
449       terms as Perl itself.
450

SEE ALSO

452       perl(1), Crypt::DES(3), Crypt::IDEA(3), rfc2898 (PKCS#5)
453
454
455
456perl v5.28.0                      2013-07-30                            CBC(3)
Impressum