SYNOPSIS

  use Crypt::CBC;
  $cipher = Crypt::CBC->new( -key    => 'my secret key',
                             -cipher => 'Blowfish'
                            );

  $ciphertext = $cipher->encrypt("This data is hush hush");
  $plaintext  = $cipher->decrypt($ciphertext);

  $cipher->start('encrypting');
  open(F,"./BIG_FILE");
  while (read(F,$buffer,1024)) {
      print $cipher->crypt($buffer);
  }
  print $cipher->finish;

  # do-it-yourself mode -- specify key, initialization vector yourself
  $key    = Crypt::CBC->random_bytes(8);  # assuming a 8-byte block cipher
  $iv     = Crypt::CBC->random_bytes(8);
  $cipher = Crypt::CBC->new(-literal_key => 1,
                            -key         => $key,
                            -iv          => $iv,
                            -header      => 'none');

  $ciphertext = $cipher->encrypt("This data is hush hush");
  $plaintext  = $cipher->decrypt($ciphertext);

  # RANDOMIV-compatible mode
  $cipher = Crypt::CBC->new(-key         => 'Super Secret!'
                            -header      => 'randomiv');

DESCRIPTION

This module is a Perl-only implementation of the cryptographic cipher block chaining mode (\s-1CBC\s0). In combination with a block cipher such as \s-1DES\s0 or \s-1IDEA\s0, you can encrypt and decrypt messages of arbitrarily long length. The encrypted messages are compatible with the encryption format used by the OpenSSL package.

To use this module, you will first create a Crypt::CBC cipher object with new(). At the time of cipher creation, you specify an encryption key to use and, optionally, a block encryption algorithm. You will then call the start() method to initialize the encryption or decryption process, crypt() to encrypt or decrypt one or more blocks of data, and lastly finish(), to pad and encrypt the final block. For your convenience, you can call the encrypt() and decrypt() methods to operate on a whole data value at once.

\fInew()\fP

$cipher = Crypt::CBC->new( -key => 'my secret key', -cipher => 'Blowfish', );

# or (for compatibility with versions prior to 2.13) $cipher = Crypt::CBC->new( { key => 'my secret key', cipher => 'Blowfish' } );

# or (for compatibility with versions prior to 2.0) $cipher = new Crypt::CBC('my secret key' => 'Blowfish');

The new() method creates a new Crypt::CBC object. It accepts a list of -argument => value pairs selected from the following list:

Argument Description -------- -----------

-key The encryption/decryption key (required)

-cipher The cipher algorithm (defaults to Crypt::DES), or a preexisting cipher object.

-salt Enables OpenSSL-compatibility. If equal to a value of "1" then causes a random salt to be generated and used to derive the encryption key and IV. Other true values are taken to be the literal salt.

-iv The initialization vector (IV)

-header What type of header to prepend to ciphertext. One of 'salt' -- use OpenSSL-compatible salted header 'randomiv' -- Randomiv-compatible "RandomIV" header 'none' -- prepend no header at all

-padding The padding method, one of "standard" (default), "space", "oneandzeroes", "rijndael_compat", "null", or "none" (default "standard").

-literal_key If true, the key provided by "key" is used directly for encryption/decryption. Otherwise the actual key used will be a hash of the provided key. (default false)

-pcbc Whether to use the PCBC chaining algorithm rather than the standard CBC algorithm (default false).

-keysize Force the cipher keysize to the indicated number of bytes.

-blocksize Force the cipher blocksize to the indicated number of bytes.

-insecure_legacy_decrypt Allow decryption of data encrypted using the "RandomIV" header produced by pre-2.17 versions of Crypt::CBC.

-add_header [deprecated; use -header instread] Whether to add the salt and IV to the header of the output cipher text.

-regenerate_key [deprecated; use literal_key instead] Whether to use a hash of the provided key to generate the actual encryption key (default true)

-prepend_iv [deprecated; use add_header instead] Whether to prepend the IV to the beginning of the encrypted stream (default true)

Crypt::CBC requires three pieces of information to do its job. First it needs the name of the block cipher algorithm that will encrypt or decrypt the data in blocks of fixed length known as the cipher's \*(L"blocksize.\*(R" Second, it needs an encryption/decryption key to pass to the block cipher. Third, it needs an initialization vector (\s-1IV\s0) that will be used to propagate information from one encrypted block to the next. Both the key and the \s-1IV\s0 must be exactly the same length as the chosen cipher's blocksize.

Crypt::CBC can derive the key and the \s-1IV\s0 from a passphrase that you provide, or can let you specify the true key and \s-1IV\s0 manually. In addition, you have the option of embedding enough information to regenerate the \s-1IV\s0 in a short header that is emitted at the start of the encrypted stream, or outputting a headerless encryption stream. In the first case, Crypt::CBC will be able to decrypt the stream given just the original key or passphrase. In the second case, you will have to provide the original \s-1IV\s0 as well as the key/passphrase.

The -cipher option specifies which block cipher algorithm to use to encode each section of the message. This argument is optional and will default to the quick-but-not-very-secure \s-1DES\s0 algorithm unless specified otherwise. You may use any compatible block encryption algorithm that you have installed. Currently, this includes Crypt::DES, Crypt::DES_EDE3, Crypt::IDEA, Crypt::Blowfish, Crypt::CAST5 and Crypt::Rijndael. You may refer to them using their full names (\*(L"Crypt::IDEA\*(R") or in abbreviated form (\*(L"\s-1IDEA\s0\*(R").

Instead of passing the name of a cipher class, you may pass an already-created block cipher object. This allows you to take advantage of cipher algorithms that have parameterized new() methods, such as Crypt::Eksblowfish:

my $eksblowfish = Crypt::Eksblowfish->new(8,$salt,$key); my $cbc = Crypt::CBC->new(-cipher=>$eksblowfish);

The -key argument provides either a passphrase to use to generate the encryption key, or the literal value of the block cipher key. If used in passphrase mode (which is the default), -key can be any number of characters; the actual key will be derived by passing the passphrase through a series of \s-1MD5\s0 hash operations. To take full advantage of a given block cipher, the length of the passphrase should be at least equal to the cipher's blocksize. To skip this hashing operation and specify the key directly, pass a true value to the -literal_key option. In this case, you should choose a key of length exactly equal to the cipher's key length. You should also specify the \s-1IV\s0 yourself and a -header mode of 'none'.

If you pass an existing Crypt::* object to new(), then the -key argument is ignored and the module will generate a warning.

The -header argument specifies what type of header, if any, to prepend to the beginning of the encrypted data stream. The header allows Crypt::CBC to regenerate the original \s-1IV\s0 and correctly decrypt the data without your having to provide the same \s-1IV\s0 used to encrypt the data. Valid values for the -header are:

"salt" -- Combine the passphrase with an 8-byte random value to generate both the block cipher key and the IV from the provided passphrase. The salt will be appended to the beginning of the data stream allowing decryption to regenerate both the key and IV given the correct passphrase. This method is compatible with current versions of OpenSSL.

"randomiv" -- Generate the block cipher key from the passphrase, and choose a random 8-byte value to use as the IV. The IV will be prepended to the data stream. This method is compatible with ciphertext produced by versions of the library prior to 2.17, but is incompatible with block ciphers that have non 8-byte block sizes, such as Rijndael. Crypt::CBC will exit with a fatal error if you try to use this header mode with a non 8-byte cipher.

"none" -- Do not generate a header. To decrypt a stream encrypted in this way, you will have to provide the original IV manually.

The \*(L"salt\*(R" header is now the default as of Crypt::CBC version 2.17. In all earlier versions \*(L"randomiv\*(R" was the default.

When using a \*(L"salt\*(R" header, you may specify your own value of the salt, by passing the desired 8-byte salt to the -salt argument. Otherwise, the module will generate a random salt for you. Crypt::CBC will generate a fatal error if you specify a salt value that isn't exactly 8 bytes long. For backward compatibility reasons, passing a value of \*(L"1\*(R" will generate a random salt, the same as if no -salt argument was provided.

The -padding argument controls how the last few bytes of the encrypted stream are dealt with when they not an exact multiple of the cipher block length. The default is \*(L"standard\*(R", the method specified in PKCS#5.

The -pcbc argument, if true, activates a modified chaining mode known as \s-1PCBC\s0. It provides better error propagation characteristics than the default \s-1CBC\s0 encryption and is required for authenticating to Kerberos4 systems (see \s-1RFC\s0 2222).

The -keysize and -blocksize arguments can be used to force the cipher's keysize and/or blocksize. This is only currently useful for the Crypt::Blowfish module, which accepts a variable length keysize. If -keysize is not specified, then Crypt::CBC will use the maximum length Blowfish key size of 56 bytes (448 bits). The Openssl library defaults to 16 byte Blowfish key sizes, so for compatibility with Openssl you may wish to set -keysize=>16. There are currently no Crypt::* modules that have variable block sizes, but an option to change the block size is provided just in case.

For compatibility with earlier versions of this module, you can provide new() with a hashref containing key/value pairs. The key names are the same as the arguments described earlier, but without the initial hyphen. You may also call new() with one or two positional arguments, in which case the first argument is taken to be the key and the second to be the optional block cipher algorithm.

\s-1IMPORTANT\s0 \s-1NOTE:\s0 Versions of this module prior to 2.17 were incorrectly using 8-byte IVs when generating the \*(L"randomiv\*(R" style of header, even when the chosen cipher's blocksize was greater than 8 bytes. This primarily affects the Rijndael algorithm. Such encrypted data streams were not secure. From versions 2.17 onward, Crypt::CBC will refuse to encrypt or decrypt using the \*(L"randomiv\*(R" header and non-8 byte block ciphers. To decrypt legacy data encrypted with earlier versions of the module, you can override the check using the -insecure_legacy_decrypt option. It is not possible to override encryption. Please use the default \*(L"salt\*(R" header style, or no headers at all.

\fIstart()\fP

$cipher->start('encrypting'); $cipher->start('decrypting');

The start() method prepares the cipher for a series of encryption or decryption steps, resetting the internal state of the cipher if necessary. You must provide a string indicating whether you wish to encrypt or decrypt. \*(L"E\*(R" or any word that begins with an \*(L"e\*(R" indicates encryption. \*(L"D\*(R" or any word that begins with a \*(L"d\*(R" indicates decryption.

\fIcrypt()\fP

$ciphertext = $cipher->crypt($plaintext);

After calling start(), you should call crypt() as many times as necessary to encrypt the desired data.

\fIfinish()\fP

$ciphertext = $cipher->finish();

The \s-1CBC\s0 algorithm must buffer data blocks internally until they are even multiples of the encryption algorithm's blocksize (typically 8 bytes). After the last call to crypt() you should call finish(). This flushes the internal buffer and returns any leftover ciphertext.

In a typical application you will read the plaintext from a file or input stream and write the result to standard output in a loop that might look like this:

$cipher = new Crypt::CBC('hey jude!'); $cipher->start('encrypting'); print $cipher->crypt($_) while <>; print $cipher->finish();

\fIencrypt()\fP

$ciphertext = $cipher->encrypt($plaintext)

This convenience function runs the entire sequence of start(), crypt() and finish() for you, processing the provided plaintext and returning the corresponding ciphertext.

\fIdecrypt()\fP

$plaintext = $cipher->decrypt($ciphertext)

This convenience function runs the entire sequence of start(), crypt() and finish() for you, processing the provided ciphertext and returning the corresponding plaintext.

\fIencrypt_hex()\fP, \fIdecrypt_hex()\fP

$ciphertext = $cipher->encrypt_hex($plaintext) $plaintext = $cipher->decrypt_hex($ciphertext)

These are convenience functions that operate on ciphertext in a hexadecimal representation. encrypt_hex($plaintext) is exactly equivalent to unpack('H*',encrypt($plaintext)). These functions can be useful if, for example, you wish to place the encrypted in an email message.

\fIget_initialization_vector()\fP

$iv = $cipher->get_initialization_vector()

This function will return the \s-1IV\s0 used in encryption and or decryption. The \s-1IV\s0 is not guaranteed to be set when encrypting until start() is called, and when decrypting until crypt() is called the first time. Unless the \s-1IV\s0 was manually specified in the new() call, the \s-1IV\s0 will change with every complete encryption operation.

\fIset_initialization_vector()\fP

$cipher->set_initialization_vector('76543210')

This function sets the \s-1IV\s0 used in encryption and/or decryption. This function may be useful if the \s-1IV\s0 is not contained within the ciphertext string being decrypted, or if a particular \s-1IV\s0 is desired for encryption. Note that the \s-1IV\s0 must match the chosen cipher's blocksize bytes in length.

\fIiv()\fP

$iv = $cipher->iv(); $cipher->iv($new_iv);

As above, but using a single method call.

\fIkey()\fP

$key = $cipher->key(); $cipher->key($new_key);

Get or set the block cipher key used for encryption/decryption. When encrypting, the key is not guaranteed to exist until start() is called, and when decrypting, the key is not guaranteed to exist until after the first call to crypt(). The key must match the length required by the underlying block cipher.

When salted headers are used, the block cipher key will change after each complete sequence of encryption operations.

\fIsalt()\fP

$salt = $cipher->salt(); $cipher->salt($new_salt);

Get or set the salt used for deriving the encryption key and \s-1IV\s0 when in OpenSSL compatibility mode.

\fIpassphrase()\fP

$passphrase = $cipher->passphrase(); $cipher->passphrase($new_passphrase);

This gets or sets the value of the key passed to new() when literal_key is false. Return $numbytes worth of random data. On systems that support the \*(L"/dev/urandom\*(R" device file, this data will be read from the device. Otherwise, it will be generated by repeated calls to the Perl rand() function.

\fIcipher()\fP, \fIpadding()\fP, \fIkeysize()\fP, \fIblocksize()\fP, \fIpcbc()\fP

These read-only methods return the identity of the chosen block cipher algorithm, padding method, key and block size of the chosen block cipher, and whether \s-1PCBC\s0 chaining is in effect.

Padding methods

Use the 'padding' option to change the padding method.

When the last block of plaintext is shorter than the block size, it must be padded. Padding methods include: \*(L"standard\*(R" (i.e., PKCS#5), \*(L"oneandzeroes\*(R", \*(L"space\*(R", \*(L"rijndael_compat\*(R", \*(L"null\*(R", and \*(L"none\*(R".

standard: (default) Binary safe pads with the number of bytes that should be truncated. So, if blocksize is 8, then "0A0B0C" will be padded with "05", resulting in "0A0B0C0505050505". If the final block is a full block of 8 bytes, then a whole block of "0808080808080808" is appended.

oneandzeroes: Binary safe pads with "80" followed by as many "00" necessary to fill the block. If the last block is a full block and blocksize is 8, a block of "8000000000000000" will be appended.

rijndael_compat: Binary safe, with caveats similar to oneandzeroes, except that no padding is performed if the last block is a full block. This is provided for compatibility with Crypt::Rijndael only and can only be used with messages that are a multiple of the Rijndael blocksize of 16 bytes.

null: text only pads with as many "00" necessary to fill the block. If the last block is a full block and blocksize is 8, a block of "0000000000000000" will be appended.

space: text only same as "null", but with "20".

none: no padding added. Useful for special-purpose applications where you wish to add custom padding to the message.

Both the standard and oneandzeroes paddings are binary safe. The space and null paddings are recommended only for text data. Which type of padding you use depends on whether you wish to communicate with an external (non Crypt::CBC library). If this is the case, use whatever padding method is compatible.

You can also pass in a custom padding function. To do this, create a function that takes the arguments:

$padded_block = function($block,$blocksize,$direction);

where $block is the current block of data, $blocksize is the size to pad it to, $direction is \*(L"e\*(R" for encrypting and \*(L"d\*(R" for decrypting, and $padded_block is the result after padding or depadding.

When encrypting, the function should always return a string of <blocksize> length, and when decrypting, can expect the string coming in to always be that length. See _standard_padding(), _space_padding(), _null_padding(), or _oneandzeroes_padding() in the source for examples.

Standard and oneandzeroes padding are recommended, as both space and null padding can potentially truncate more characters than they should.

EXAMPLES

Two examples, des.pl and idea.pl can be found in the eg/ subdirectory of the Crypt-CBC distribution. These implement command-line \s-1DES\s0 and \s-1IDEA\s0 encryption algorithms.

LIMITATIONS

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

BUGS

Please report them.

AUTHOR

Lincoln Stein, [email protected]

This module is distributed under the \s-1ARTISTIC\s0 \s-1LICENSE\s0 using the same terms as Perl itself.

RELATED TO Crypt::CBC…

perl\|(1), Crypt::DES\|(3), Crypt::IDEA\|(3), rfc2898 (PKCS#5)