Crypt-Util
view release on metacpan or search on metacpan
lib/Crypt/Util.pm view on Meta::CPAN
use namespace::clean -except => [qw(meta)];
our %DEFAULT_ACCESSORS = (
mode => { isa => "Str" },
authenticated_mode => { isa => "Str" },
encode => { isa => "Bool" },
encoding => { isa => "Str" },
printable_encoding => { isa => "Str" },
alphanumerical_encoding => { isa => "Str" },
uri_encoding => { isa => "Str" },
digest => { isa => "Str" },
cipher => { isa => "Str" },
mac => { isa => "Str" },
key => { isa => "Str" },
uri_encoding => { isa => "Str" },
printable_encoding => { isa => "Str" },
use_literal_key => { isa => "Bool" },
tamper_proof_unencrypted => { isa => "Bool" },
nonce => { isa => "Str", default => "" },
);
our @DEFAULT_ACCESSORS = keys %DEFAULT_ACCESSORS;
my %export_groups = (
'crypt' => [qw/
encrypt_string decrypt_string
authenticated_encrypt_string
tamper_proof thaw_tamper_proof
cipher_object
/],
digest => [qw/
digest_string verify_hash verify_digest
digest_object
mac_digest_string
verify_mac
/],
encoding => [qw/
encode_string decode_string
encode_string_hex decode_string_hex
encode_string_base64 decode_string_base64 encode_string_base64_wrapped
encode_string_base32 decode_string_base32
encode_string_uri_base64 decode_string_uri_base64
encode_string_uri decode_string_uri
encode_string_alphanumerical decode_string_alphanumerical
encode_string_printable decode_string_printable
encode_string_uri_escape decode_string_uri_escape
/],
params => [ "exported_instance", "disable_fallback", map { "default_$_" } @DEFAULT_ACCESSORS ],
);
my %exports = map { $_ => \&__curry_instance } map { @$_ } values %export_groups;
Sub::Exporter->import( -setup => {
exports => \%exports,
groups => \%export_groups,
collectors => {
defaults => sub { 1 },
},
});
our @KNOWN_AUTHENTICATING_MODES = qw(EAX OCB GCM CWC CCM); # IACBC & IAPM will probably never be implemented
our %KNOWN_AUTHENTICATING_MODES = map { $_ => 1 } @KNOWN_AUTHENTICATING_MODES;
our %FALLBACK_LISTS = (
mode => [qw/CFB CBC Ctr OFB/],
stream_mode => [qw/CFB Ctr OFB/],
block_mode => [qw/CBC/],
authenticated_mode => [qw/EAX GCM CCM/], # OCB/], OCB is patented
cipher => [qw/Rijndael Serpent Twofish RC6 Blowfish RC5/],
#authenticated_cipher => [qw/Phelix SOBER-128 Helix/], # not yet ready
digest => [qw/SHA-1 SHA-256 RIPEMD160 Whirlpool MD5 Haval256/],
mac => [qw/HMAC CMAC/],
encoding => [qw/hex/],
printable_encoding => [qw/base64 hex/],
alphanumerical_encoding => [qw/base32 hex/],
uri_encoding => [qw/uri_base64 base32 hex/],
);
foreach my $fallback ( keys %FALLBACK_LISTS ) {
my @list = @{ $FALLBACK_LISTS{$fallback} };
my $list_method = "fallback_${fallback}_list";
my $list_method_sub = sub { # derefed list accessors
my ( $self, @args ) = @_;
if ( @args ) {
@args = @{ $args[0] } if @args == 1 and (ref($args[0])||'') eq "ARRAY";
$self->{$list_method} = \@args;
}
@{ $self->{$list_method} || \@list };
};
my $type = ( $fallback =~ /(encoding|mode)/ )[0] || $fallback;
my $try = "_try_${type}_fallback";
my $fallback_sub = sub {
my $self = shift;
$self->_find_fallback(
$fallback,
$try,
$self->$list_method,
) || croak "Couldn't load any $fallback";
};
no strict 'refs';
*{ "fallback_$fallback" } = $fallback_sub;
*{ $list_method } = $list_method_sub;
}
foreach my $attr ( @DEFAULT_ACCESSORS ) {
has "default_$attr" => (
is => "rw",
predicate => "has_default_$attr",
clearer => "clear_default_$attr",
( __PACKAGE__->can("fallback_$attr") ? (
lazy_build => 1,
builder => "fallback_$attr",
) : () ),
%{ $DEFAULT_ACCESSORS{$attr} },
);
}
has disable_fallback => (
isa => "Bool",
is => "rw",
);
lib/Crypt/Util.pm view on Meta::CPAN
%params = @args;
}
return ( $self, %params );
}
sub _process_params {
my ( $self, $params, @required ) = @_;
foreach my $param ( @required ) {
next if exists $params->{$param};
$params->{$param} = $self->_process_param( $param );
}
}
sub _process_param {
my ( $self, $param ) = @_;
my $default = "default_$param";
if ( $self->can($default) ) {
return $self->$default;
}
croak "No default value for required parameter '$param'";
}
sub cipher_object {
my ( $self, %params ) = _args @_;
$self->_process_params( \%params, qw/mode/);
my $method = "cipher_object_" . lc(my $mode = delete $params{mode});
croak "mode $mode is unsupported" unless $self->can($method);
$self->$method( %params );
}
sub cipher_object_eax {
my ( $self, %params ) = _args @_;
$self->_process_params( \%params, qw/cipher nonce/ );
require Crypt::EAX;
Crypt::EAX->new(
%params,
cipher => "Crypt::$params{cipher}", # FIXME take a ref, but Crypt::CFB will barf
key => $self->process_key(%params),
nonce => $params{nonce},
);
}
sub cipher_object_cbc {
my ( $self, %params ) = _args @_;
$self->_process_params( \%params, qw/cipher/ );
require Crypt::CBC;
Crypt::CBC->new(
-cipher => $params{cipher},
-key => $self->process_key(%params),
);
}
sub cipher_object_ofb {
my ( $self, %params ) = _args @_;
$self->_process_params( \%params, qw/cipher/ );
require Crypt::OFB;
my $c = Crypt::OFB->new;
$c->padding( Crypt::ECB::PADDING_AUTO() );
$c->key( $self->process_key(%params) );
$c->cipher( $params{cipher} );
return $c;
}
sub cipher_object_cfb {
my ( $self, @args ) = _args @_;
require Crypt::CFB;
$self->_cipher_object_baurem( "Crypt::CFB", @args );
}
sub cipher_object_ctr {
my ( $self, @args ) = _args @_;
require Crypt::Ctr;
$self->_cipher_object_baurem( "Crypt::Ctr", @args );
}
sub _cipher_object_baurem {
my ( $self, $class, %params ) = @_;
my $prefix = "Crypt";
( $prefix, $params{cipher} ) = ( Digest => delete $params{digest} ) if exists $params{encryption_digest};
$self->_process_params( \%params, qw/cipher/ );
$class->new( $self->process_key(%params), join("::", $prefix, $params{cipher}) );
}
use tt;
[% FOR mode IN ["stream", "block", "authenticated"] %]
sub cipher_object_[% mode %] {
my ( $self, @args ) = _args @_;
my $mode = $self->_process_param("[% mode %]_mode");
$self->cipher_object( @args, mode => $mode );
}
[% END %]
no tt;
sub process_nonce {
my ( $self, %params ) = _args @_, 'nonce';
my $nonce = $self->_process_params( \%params, 'nonce' );
lib/Crypt/Util.pm view on Meta::CPAN
Crypt::Util - A lightweight Crypt/Digest convenience API
=head1 SYNOPSIS
use Crypt::Util; # also has a Sub::Exporter to return functions wrapping a default instance
my $util = Crypt::Util->new;
$util->default_key("my secret");
# MAC or cipher+digest based tamper resistent encapsulation
# (uses Storable on $data if necessary)
my $tamper_resistent_string = $util->tamper_proof( $data );
my $verified = $util->thaw_tamper_proof( $untrusted_string, key => "another secret" );
# If the encoding is unspecified, base32 is used
# (hex if base32 is unavailable)
my $encoded = $util->encode_string( $bytes );
my $hash = $util->digest( $bytes, digest => "md5" );
die "baaaad" unless $util->verify_hash(
hash => $hash,
data => $bytes,
digest => "md5",
);
=head1 DESCRIPTION
This module provides an easy, intuitive and forgiving API for wielding
crypto-fu.
The API is designed as a cascade, with rich features built using simpler ones.
this means that the option processing is uniform throughout, and the behaviors
are generally predictable.
Note that L<Crypt::Util> doesn't do any crypto on its own, but delegates the
actual work to the various other crypto modules on the CPAN. L<Crypt::Util>
merely wraps these modules, providing uniform parameters, and building on top
of their polymorphism with higher level features.
=head2 Priorities
=over 4
=item Ease of use
This module is designed to have an easy API to allow easy but responsible
use of the more low level Crypt:: and Digest:: modules on CPAN. Therefore,
patches to improve ease-of-use are very welcome.
=item Pluggability
Dependency hell is avoided using a fallback mechanism that tries to choose an
algorithm based on an overridable list.
For "simple" use install Crypt::Util and your favourite digest, cipher and
cipher mode (CBC, CFB, etc).
To ensure predictable behavior the fallback behavior can be disabled as necessary.
=back
=head2 Interoperability
To ensure that your hashes and strings are compatible with L<Crypt::Util>
deployments on other machines (where different Crypt/Digest modules are
available, etc) you should use C<disable_fallback>.
Then either set the default ciphers, or always explicitly state the cipher.
If you are only encrypting and decrypting with the same installation, and new
cryptographic modules are not being installed, the hashes/ciphertexts should be
compatible without disabling fallback.
=head1 EXPORTED API
B<NOTE>: nothing is exported by default.
L<Crypt::Util> also presents an optional exported api using L<Sub::Exporter>.
Unlike typical exported APIs, there is no class level default instance shared
by all the importers, but instead every importer gets its own instance.
For example:
package A;
use Crypt::Util qw/:all/;
default_key("moose");
my $ciphertext = encrypt_string($plain);
package B;
use Crypt::Util qw/:all/;
default_key("elk");
my $ciphertext = encrypt_string($plain);
In this example every importing package has its own implicit instance, and the
C<default_key> function will in fact not share the value.
You can get the instance using the C<exported_instance> function, which is just
the identity method.
The export tags supported are: C<crypt> (encryption and tamper proofing related
functions), C<digest> (digest and MAC related functions), C<encoding> (various
encoding and decoding functions), and C<params> which give you functions for
handling default values.
=head1 METHODS
=over 4
=item tamper_proof( [ $data ], %params )
=item thaw_tamper_proof( [ $string ], %params )
lib/Crypt/Util.pm view on Meta::CPAN
(note- unlike L<MIME::Base32> this is case insensitive).
=head1 HANDLING OF DEFAULT VALUES
=over 4
=item disable_fallback()
When true only the first item from the fallback list will be tried, and if it
can't be loaded there will be a fatal error.
Enable this to ensure portability.
=back
For every parameter, there are several methods, where PARAMETER is replaced
with the parameter name:
=over 4
=item * default_PARAMETER()
This accessor is available for the user to override the default value.
If set to undef, then C<fallback_PARAMETER> will be consulted instead.
B<ALL> the default values are set to undef unless changed by the user.
=item * fallback_PARAMETER()
Iterates the C<fallback_PARAMETER_list>, choosing the first value that is
usable (it's provider is available).
If C<disable_fallback> is set to a true value, then only the first value in the
fallback list will be tried.
=item * fallback_PARAMETER_list()
An ordered list of values to try and use as fallbacks.
C<fallback_PARAMETER> iterates this list and chooses the first one that works.
=back
Available parameters are as follows:
=over 4
=item * cipher
The fallback list is
C<Rijndael>, C<Serpent>, C<Twofish>, C<RC6>, C<Blowfish> and C<RC5>.
L<Crypt::Rijndael> is the AES winner, the next three are AES finalists, and the
last two are well known and widely used.
=item * mode
The mode in which to use the cipher.
The fallback list is C<CFB>, C<CBC>, C<Ctr>, and C<OFB>.
=item digest
The fallback list is C<SHA-1>, C<SHA-256>, C<RIPEMD160>,
C<Whirlpool>, C<MD5>, and C<Haval256>.
=item * encoding
The fallback list is C<hex> (effectively no fallback).
=item alphanumerical_encoding
The fallback list is C<base32> and C<hex>.
L<MIME::Base32> is required for C<base32> encoding.
=item * uri_encoding
The fallback list is C<uri_base64>.
=item * printable_encoding
The fallback list is C<base64>
=back
=head2 Defaults with no fallbacks
The following parameters have a C<default_> method, as described in the
previous section, but the C<fallback_> methods are not applicable.
=over 4
=item * encode
Whether or not to encode by default (applies to digests and encryptions).
=item * key
The key to use. Useful for when you are repeatedly encrypting.
=item * nonce
The nonce/IV to use for cipher modes that require it.
Defaults to the empty string, but note that some methods will generate a nonce
for you (e.g. C<authenticated_encrypt_string>) if none was provided.
=item * use_literal_key
Whether or not to not hash the key by default. See C<process_key>.
=item * tamper_proof_unencrypted
Whether or not tamper resistent strings are by default unencrypted (just MAC).
=back
=head2 Subclassing
You may safely subclass and override C<default_PARAMETER> and
C<fallback_PARAMETER_list> to provide values from configurations.
=back
=head1 TODO
=over 4
=item *
Crypt::SaltedHash support
=item *
EMAC (maybe, the modules are not OO and require refactoring) message
authentication mode
=item *
Bruce Schneier Fact Database
L<http://geekz.co.uk/lovesraymond/archive/bruce-schneier-facts>.
L<WWW::SchneierFacts>
=item *
Entropy fetching (get N weak/strong bytes, etc) from e.g. OpenSSL bindings,
/dev/*random, and EGD.
=item *
Additional data formats (streams/iterators, filehandles, generalized storable
data/string handling for all methods, not just tamper_proof).
Streams should also be able to used via a simple push api.
=item *
IV/nonce/salt support for the various cipher modes, not just EAX (CBC, CCM, GCM, etc)
=item *
L<Crypt::Rijndael> can do its own cipher modes
=head1 SEE ALSO
L<Digest>, L<Crypt::CBC>, L<Crypt::CFB>,
L<http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation>.
=head1 VERSION CONTROL
This module is maintained using Darcs. You can get the latest version from
L<http://nothingmuch.woobling.org/Crypt-Util/>, and use C<darcs send> to commit
changes.
=head1 AUTHORS
Yuval Kogman, E<lt>nothingmuch@woobling.orgE<gt>
Ann Barcomb
=head1 COPYRIGHT & LICENSE
Copyright 2006-2008 by Yuval Kogman E<lt>nothingmuch@woobling.orgE<gt>, Ann Barcomb
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
=cut
( run in 1.110 second using v1.01-cache-2.11-cpan-e1769b4cff6 )