Initial Commit

This commit is contained in:
Riley Schneider
2025-12-03 16:38:10 +01:00
parent c5e26bf594
commit b732d8d4b5
17680 changed files with 5977495 additions and 2 deletions

View File

@@ -0,0 +1,143 @@
package Crypt::OpenSSL::AES;
# Copyright (C) 2006 DelTel, Inc.
#
# This library is free software; you can redistribute it and/or modify
# it under the same terms as Perl itself, either Perl version 5.8.5 or,
# at your option, any later version of Perl 5 you may have available.
use 5.006002;
use strict;
use warnings;
require Exporter;
our @ISA = qw(Exporter);
# Items to export into callers namespace by default. Note: do not export
# names by default without a very good reason. Use EXPORT_OK instead.
# Do not simply export all your public functions/methods/constants.
# This allows declaration use Crypt::OpenSSL::AES ':all';
# If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
# will save memory.
our %EXPORT_TAGS = ( 'all' => [ qw(
) ] );
our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
our @EXPORT = qw(
);
our $VERSION = '0.05';
require XSLoader;
XSLoader::load('Crypt::OpenSSL::AES', $VERSION);
# Preloaded methods go here.
1;
__END__
=head1 NAME
Crypt::OpenSSL::AES - A Perl wrapper around OpenSSL's AES library
=head1 SYNOPSIS
use Crypt::OpenSSL::AES;
my $cipher = new Crypt::OpenSSL::AES($key);
$encrypted = $cipher->encrypt($plaintext)
$decrypted = $cipher->decrypt($encrypted)
=head1 DESCRIPTION
This module implements a wrapper around OpenSSL. Specifically, it
wraps the methods related to the US Government's Advanced
Encryption Standard (the Rijndael algorithm).
This module is compatible with Crypt::CBC (and likely other modules
that utilize a block cipher to make a stream cipher).
This module is an alternative to the implementation provided by
Crypt::Rijndael which implements AES itself. In contrast, this module
is simply a wrapper around the OpenSSL library.
=over 4
=item $cipher->encrypt($data)
Encrypt data. The size of C<$data> must be exactly C<blocksize> in
length (16 bytes), otherwise this function will croak.
You should use Crypt::CBC or something similar to encrypt/decrypt data
of arbitrary lengths.
=item $cipher->decrypt($data)
Decrypts C<$data>. The size of C<$data> must be exactly C<blocksize> in
length (16 bytes), otherwise this function will croak.
You should use Crypt::CBC or something similar to encrypt/decrypt data
of arbitrary lengths.
=item keysize
This method is used by Crypt::CBC to verify the key length.
This module actually supports key lengths of 16, 24, and 32 bytes,
but this method always returns 32 for Crypt::CBC's sake.
=item blocksize
This method is used by Crypt::CBC to check the block size.
The blocksize for AES is always 16 bytes.
=back
=head2 USE WITH CRYPT::CBC
use Crypt::CBC
$cipher = Crypt::CBC->new(
-key => $key,
-cipher => "Crypt::OpenSSL::AES"
);
$encrypted = $cipher->encrypt($plaintext)
$decrypted = $cipher->decrypt($encrypted)
=head1 SEE ALSO
L<Crypt::CBC>
http://www.openssl.org/
http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
http://www.csrc.nist.gov/encryption/aes/
=head1 BUGS
Need more (and better) test cases.
=head1 AUTHOR
Tolga Tarhan, E<lt>cpan at ttar dot orgE<gt>
The US Government's Advanced Encryption Standard is the Rijndael
Algorithm and was developed by Vincent Rijmen and Joan Daemen.
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2006 DelTel, Inc.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.5 or,
at your option, any later version of Perl 5 you may have available.
=cut

View File

@@ -0,0 +1,423 @@
package Crypt::OpenSSL::Bignum;
use 5.005;
use strict;
use Carp;
use vars qw( $VERSION @ISA );
use base qw(DynaLoader);
$VERSION = '0.09';
bootstrap Crypt::OpenSSL::Bignum $VERSION;
1;
__END__
=head1 NAME
Crypt::OpenSSL::Bignum - OpenSSL's multiprecision integer arithmetic
=head1 SYNOPSIS
use Crypt::OpenSSL::Bignum;
my $bn = Crypt::OpenSSL::Bignum->new_from_decimal( "1000" );
# or
my $bn = Crypt::OpenSSL::Bignum->new_from_word( 1000 );
# or
my $bn = Crypt::OpenSSL::Bignum->new_from_hex("3e8"); # no leading 0x
# or
my $bn = Crypt::OpenSSL::Bignum->new_from_bin(pack( "C*", 3, 232 ))
use Crypt::OpenSSL::Bignum::CTX;
sub print_factorial
{
my( $n ) = @_;
my $fac = Crypt::OpenSSL::Bignum->one();
my $ctx = Crypt::OpenSSL::Bignum::CTX->new();
foreach my $i (1 .. $n)
{
$fac->mul( Crypt::OpenSSL::Bignum->new_from_word( $i ), $ctx, $fac );
}
print "$n factorial is ", $fac->to_decimal(), "\n";
}
=head1 DESCRIPTION
Crypt::OpenSSL::Bignum provides access to OpenSSL multiprecision
integer arithmetic libraries. Presently, many though not all of the
arithmetic operations that OpenSSL provides are exposed to perl. In
addition, this module can be used to provide access to bignum values
produced by other OpenSSL modules, such as key parameters from
Crypt::OpenSSL::RSA.
I<NOTE>: Many of the methods in this package can croak, so use eval, or
Error.pm's try/catch mechanism to capture errors.
=head1 Constructors
=over
=item new_from_decimal
my $bn = Crypt::OpenSSL::Bignum->new_from_decimal($decimal_string);
Create a new Crypt::OpenSSL::Bignum object whose value is specified by
the given decimal representation.
=item new_from_hex
my $bn = Crypt::OpenSSL::Bignum->new_from_hex($hex_string); #no leading '0x'
Create a new Crypt::OpenSSL::Bignum object whose value is specified by
the given hexidecimal representation.
=item new_from_word
my $bn = Crypt::OpenSSL::Bignum->new_from_word($unsigned_integer);
Create a new Crypt::OpenSSL::Bignum object whose value will be the
word given. Note that numbers represented by objects created using
this method are necessarily between 0 and 2^32 - 1.
=item new_from_bin
my $bn = Crypt::OpenSSL::Bignum->new_from_bin($bin_buffer);
Create a new Crypt::OpenSSL::Bignum object whose value is specified by
the given packed binary string (created by L</to_bin>). Note that objects
created using this method are necessarily nonnegative.
=item new
my $bn = Crypt::OpenSSL::Bignum->new;
Returns a new Crypt::OpenSSL::Bignum object representing 0
=item zero
my $bn = Crypt::OpenSSL::Bignum->zero;
Returns a new Crypt::OpenSSL::Bignum object representing 0 (same as new)
=item one
my $bn = Crypt::OpenSSL::Bignum->one;
Returns a new Crypt::OpenSSL::Bignum object representing 1
=item rand
my $bn = Crypt::OpenSSL::Bignum->rand($bits, $top, $bottom)
# $bits, $top, $bottom are integers
generates a cryptographically strong pseudo-random number of bits bits in
length and stores it in rnd. If top is -1, the most significant bit of the
random number can be zero. If top is 0, it is set to 1, and if top is 1, the
two most significant bits of the number will be set to 1, so that the product
of two such random numbers will always have 2*bits length. If bottom is true,
the number will be odd.
=item pseudo_rand
my $bn = Crypt::OpenSSL::Bignum->pseudo_rand($bits, $top, $bottom)
# $bits, $top, $bottom are integers
does the same, but pseudo-random numbers generated by this function are not
necessarily unpredictable. They can be used for non-cryptographic purposes and
for certain purposes in cryptographic protocols, but usually not for key
generation etc.
=item rand_range
my $bn = Crypt::OpenSSL::Bignum->rand_range($bn_range)
generates a cryptographically strong pseudo-random number rnd in the range 0
<lt>= rnd < range. BN_pseudo_rand_range() does the same, but is based on
BN_pseudo_rand(), and hence numbers generated by it are not necessarily
unpredictable.
=item bless_pointer
my $bn = Crypt::OpenSSL::Bignum->bless_pointer($BIGNUM_ptr)
Given a pointer to a OpenSSL BIGNUM object in memory, construct and
return Crypt::OpenSSL::Bignum object around this. Note that the
underlying BIGNUM object will be destroyed (via BN_clear_free(3ssl))
when the returned Crypt::OpenSSL::Bignum object is no longer
referenced, so the pointer passed to this method should only be
referenced via the returned perl object after calling bless_pointer.
This method is intended only for use by XSUB writers writing code that
interfaces with OpenSSL library methods, and who wish to be able to
return a BIGNUM structure to perl as a Crypt::OpenSSL::Bignum object.
=back
=head1 Instance Methods
=over
=item to_decimal
my $decimal_string = $self->to_decimal;
Return a decimal string representation of this object.
=item to_hex
my $hex_string = $self->to_hex;
Return a hexidecimal string representation of this object.
=item to_bin
my $bin_buffer = $self->to_bin;
Return a packed binary string representation of this object. Note
that sign is ignored, so that to bin called on a
Crypt::OpenSSL::Bignum object representing a negative number returns
the same value as it would called on an object representing that
number's absolute value.
=item get_word
my $unsigned_int = $self->get_word;
Return a scalar integer representation of this object, if it can be
represented as an unsigned long.
=item is_zero
my $bool = $self->is_zero;
Returns true of this object represents 0.
=item is_one
my $bool = $self->is_one;
Returns true of this object represents 1.
=item is_odd
my $bool = $self->is_odd;
Returns true of this object represents an odd number.
=item add
my $new_bn_object = $self->add($bn_b); # $new_bn_object = $self + $bn_b
# or
$self->add($bn_b, $result_bn); # $result_bn = $self + $bn_b
This method returns the sum of this object and the first argument. If
only one argument is passed, a new Crypt::OpenSSL::Bignum object is
created for the return value; otherwise, the value of second argument
is set to the result and returned.
=item sub
my $new_bn_object = $self->sub($bn_b); # $new_bn_object = $self - $bn_b
# or
$self->sub($bn_b, $result_bn); # $result_bn = $self - $bn_b
This method returns the difference of this object and the first
argument. If only one argument is passed, a new
Crypt::OpenSSL::Bignum object is created for the return value;
otherwise, the value of second argument is set to the result and
returned.
=item mul
my $new_bn_object = $self->mul($bn_b, $ctx); # $new_bn_object = $self * $bn_b
# or
$self->mul($bn_b, $ctx, $result_bn); # $result_bn = $self * $bn_b
This method returns the product of this object and the first argument,
using the second argument, a Crypt::OpenSSL::Bignum::CTX object, as a
scratchpad. If only two arguments are passed, a new
Crypt::OpenSSL::Bignum object is created for the return value;
otherwise, the value of third argument is set to the result and
returned.
=item div
my ($quotient, $remainder) = $self->div($bn_b, $ctx);
# or
$self->div($bn_b, $ctx, $quotient, $remainder);
This method returns a list consisting of quotient and the remainder
obtained by dividing this object by the first argument, using the
second argument, a Crypt::OpenSSL::Bignum::CTX object, as a
scratchpad. If only two arguments are passed, new
Crypt::OpenSSL::Bignum objects are created for both return values. If
a third argument is passed, otherwise, the value of third argument is
set to the quotient. If a fourth argument is passed, the value of the
fourth argument is set to the remainder.
=item mod
my $remainder = $self->mod($bn_b, $ctx);
# or
$self->mod($bn_b, $ctx, $remainder);
This method returns the remainder obtained by dividing this object by
the first argument, a Crypt::OpenSSL::Bignum::CTX object, as a
scratchpad. Crypt::OpenSSL::Bignum object is created for the return
value. If a third argument is passed, the value of third argument is
set to the remainder.
=item sqr
my $new_bn_object = $self->sqr($ctx);
# new object is created $self is not modified
This method returns the square (C<$self ** 2>) of Crypt::OpenSSL::Bignum object.
=item exp
my $new_bn_object = $self->exp($bn_exp, $ctx);
# new object is created $self is not modified
This method returns the product of this object exponentiated by the
first argument (Crypt::OpenSSL::Bignum object), using the second argument, a
Crypt::OpenSSL::Bignum::CTX object, as a scratchpad.
=item mod_exp
my $new_bn_object = $self->exp_mod($bn_exp, $bn_mod, $ctx);
# new object is created $self is not modified
This method returns the product of this object exponentiated by the
first argument (Crypt::OpenSSL::Bignum object), modulo the second
argument (also Crypt::OpenSSL::Bignum object), using the third argument,
a Crypt::OpenSSL::Bignum::CTX object, as a scratchpad.
=item mod_mul
my $new_bn_object = $self->mod_mul($bn_b, $bn_mod, $ctx);
# new object is created $self is not modified
This method returns C<($self * $bn_b) % $bn_mod>, using the third argument,
a Crypt::OpenSSL::Bignum::CTX object, as a scratchpad.
=item mod_inverse
my $new_bn_object = $self->mod_inverse($bn_n, $ctx);
# new object is created $self is not modified
Computes the inverse of C<$self> modulo C<$bn_n> and returns the result in
a new Crypt::OpenSSL::Bignum object, using the second argument,
a Crypt::OpenSSL::Bignum::CTX object, as a scratchpad.
=item gcd
my $new_bn_object = $self->gcd($bn_b, $ctx);
# new object is created $self is not modified
Computes the greatest common divisor of C<$self> and C<$bn_b> and returns the result in
a new Crypt::OpenSSL::Bignum object, using the second argument,
a Crypt::OpenSSL::Bignum::CTX object, as a scratchpad.
=item cmp
my $result = $self->cmp($bn_b);
#returns:
# -1 if self < bn_b
# 0 if self == bn_b
# 1 if self > bn_b
Comparison of values C<$self> and C<$bn_b> (Crypt::OpenSSL::Bignum objects).
=item ucmp
my $result = $self->ucmp($bn_b);
#returns:
# -1 if |self| < |bn_b|
# 0 if |self| == |bn_b|
# 1 if |self| > |bn_b|
Comparison using the absolute values of C<$self> and C<$bn_b> (Crypt::OpenSSL::Bignum objects).
=item equals
my $result = $self->equals($bn_b);
#returns:
# 1 if self == bn_b
# 0 otherwise
=item num_bits
my $bits = $self->num_bits;
Returns the number of significant bits in a word. If we take 0x00000432 as an
example, it returns 11, not 16, not 32. Basically, except for a zero, it
returns C<floor(log2(w)) + 1>.
=item num_bytes
my $bytes = $self->num_bytes;
Returns the size of binary represenatation in bytes.
=item rshift
my $new_bn_object = $self->rshift($n);
# new object is created $self is not modified
Shifts a right by C<$n> (integer) bits and places the result into a newly created Crypt::OpenSSL::Bignum object.
=item lshift
my $new_bn_object = $self->lshift($n);
# new object is created $self is not modified
Shifts a left by C<$n> (integer) bits and places the result into a newly created Crypt::OpenSSL::Bignum object.
=item swap
my $bn_a = Crypt::OpenSSL::Bignum->new_from_decimal("1234567890001");
my $bn_b = Crypt::OpenSSL::Bignum->new_from_decimal("1234567890002");
$bn_a->swap($bn_b);
# or
$bn_b->swap($bn_a);
Exchanges the values of two Crypt::OpenSSL::Bignum objects.
=item copy
my $new_bn_object = $self->copy;
Returns a copy of this object.
=item pointer_copy
my $cloned_BIGNUM_ptr = $self->pointer_copy($BIGNUM_ptr);
This method is intended only for use by XSUB writers wanting to have
access to the underlying BIGNUM structure referenced by a
Crypt::OpenSSL::Bignum perl object so that they can pass them to other
routines in the OpenSSL library. It returns a perl scalar whose IV
can be cast to a BIGNUM* value. This can then be passed to an XSUB
which can work with the BIGNUM directly. Note that the BIGNUM object
pointed to will be a copy of the BIGNUM object wrapped by the
instance; it is thus the responsibility of the client to free space
allocated by this BIGNUM object if and when it is done with it. See
also bless_pointer.
=back
=head1 AUTHOR
Ian Robertson, iroberts@cpan.org
=head1 SEE ALSO
L<https://www.openssl.org/docs/crypto/bn.html>
=cut

View File

@@ -0,0 +1,41 @@
package Crypt::OpenSSL::Bignum::CTX;
use 5.005;
use strict;
use Carp;
use Crypt::OpenSSL::Bignum;
use vars qw( @ISA );
require DynaLoader;
use base qw(DynaLoader);
bootstrap Crypt::OpenSSL::Bignum $Crypt::OpenSSL::Bignum::VERSION;
1;
__END__
# Below is stub documentation for your module. You better edit it!
=head1 NAME
Crypt::OpenSSL::Bignum::CTX - Perl interface to the OpenSSL BN_CTX structure.
=head1 SYNOPSIS
use Crypt::OpenSSL::Bignum::CTX;
my $bn_ctx = Crypt::OpenSSL::Bignum::CTX->new();
=head1 DESCRIPTION
See the man page for Crypt::OpenSSL::Bignum.
=head1 AUTHOR
Ian Robertson, iroberts@cpan.org
=head1 SEE ALSO
L<perl>, L<Crypt::OpenSSL::Bignum>, L<BN_CTX_new(3ssl)>
=cut

View File

@@ -0,0 +1,196 @@
package Crypt::OpenSSL::DSA;
use strict;
use warnings;
require DynaLoader;
use vars qw(@ISA $VERSION);
@ISA = qw(DynaLoader);
$VERSION = '0.19';
bootstrap Crypt::OpenSSL::DSA $VERSION;
sub read_pub_key_str {
my ($class, $key_str) = @_;
$class->_load_key(0, $key_str);
}
sub read_priv_key_str {
my ($class, $key_str) = @_;
$class->_load_key(1, $key_str);
}
1;
__END__
=head1 NAME
Crypt::OpenSSL::DSA - Digital Signature Algorithm using OpenSSL
=head1 SYNOPSIS
use Crypt::OpenSSL::DSA;
# generate keys and write out to PEM files
my $dsa = Crypt::OpenSSL::DSA->generate_parameters( 512 );
$dsa->generate_key;
$dsa->write_pub_key( $filename );
$dsa->write_priv_key( $filename );
# using keys from PEM files
my $dsa_priv = Crypt::OpenSSL::DSA->read_priv_key( $filename );
my $sig = $dsa_priv->sign($message);
my $dsa_pub = Crypt::OpenSSL::DSA->read_pub_key( $filename );
my $valid = $dsa_pub->verify($message, $sig);
# using keys from PEM strings
my $dsa_priv = Crypt::OpenSSL::DSA->read_priv_key_str( $key_string );
my $sig = $dsa_priv->sign($message);
my $dsa_pub = Crypt::OpenSSL::DSA->read_pub_key_str( $key_string );
my $valid = $dsa_pub->verify($message, $sig);
=head1 DESCRIPTION
Crypt::OpenSSL::DSA implements the DSA
(Digital Signature Algorithm) signature verification system.
It is a thin XS wrapper to the DSA functions contained in the
OpenSSL crypto library, located at http://www.openssl.org
=head1 CLASS METHODS
=over 4
=item $dsa = Crypt::OpenSSL::DSA->generate_parameters( $bits, $seed );
Returns a new DSA object and generates the p, q and g
parameters necessary to generate keys.
bits is the length of the prime to be generated; the DSS allows a maximum of 1024 bits.
=item $dsa = Crypt::OpenSSL::DSA->read_params( $filename );
Reads in a parameter PEM file and returns a new DSA object with the p, q and g
parameters necessary to generate keys.
=item $dsa = Crypt::OpenSSL::DSA->read_pub_key( $filename );
Reads in a public key PEM file and returns a new DSA object that can be used
to verify DSA signatures.
=item $dsa = Crypt::OpenSSL::DSA->read_priv_key( $filename );
Reads in a private key PEM file and returns a new DSA object that can be used
to sign messages.
=item $dsa = Crypt::OpenSSL::DSA->read_pub_key_str( $key_string );
Reads in a public key PEM string and returns a new DSA object that can be used
to verify DSA signatures.
The string should include the -----BEGIN...----- and -----END...----- lines.
=item $dsa = Crypt::OpenSSL::DSA->read_priv_key_str( $key_string );
Reads in a private key PEM string and returns a new DSA object that can be used
to sign messages.
The string should include the -----BEGIN...----- and -----END...----- lines.
=back
=head1 OBJECT METHODS
=over 4
=item $dsa->generate_key;
Generates private and public keys, assuming that $dsa is the return
value of generate_parameters.
=item $sig = $dsa->sign( $message );
Signs $message, returning the signature. Note that $meesage cannot exceed
20 characters in length.
$dsa is the signer's private key.
=item $sig_obj = $dsa->do_sign( $message );
Similar to C<sign>, but returns a L<Crypt::OpenSSL::DSA::Signature> object.
=item $valid = $dsa->verify( $message, $sig );
Verifies that the $sig signature for $message is valid.
$dsa is the signer's public key.
Note: it croaks if the underlying library call returns error (-1).
=item $valid = $dsa->do_verify( $message, $sig_obj );
Similar to C<verify>, but uses a L<Crypt::OpenSSL::DSA::Signature> object.
Note: it croaks if the underlying library call returns error (-1).
=item $dsa->write_params( $filename );
Writes the parameters into a PEM file.
=item $dsa->write_pub_key( $filename );
Writes the public key into a PEM file.
=item $dsa->write_priv_key( $filename );
Writes the private key into a PEM file.
=item $p = $dsa->get_p, $dsa->set_p($p)
Gets/sets the prime number in binary format.
=item $q = $dsa->get_q, $dsa->set_q($q)
Gets/sets the subprime number (q | p-1) in binary format.
=item $g = $dsa->get_g, $dsa->set_g($g)
Gets/sets the generator of subgroup in binary format.
=item $pub_key = $dsa->get_pub_key, $dsa->set_pub_key($pub_key)
Gets/sets the public key (y = g^x) in binary format.
=item $priv_key = $dsa->get_priv_key, $dsa->set_priv_key($priv_key)
Gets/sets the private key in binary format.
=back
=head1 NOTES
L<Crpyt::DSA> is a more mature Perl DSA module, but can be difficult to
install, because of the L<Math::Pari> requirement.
Comments, suggestions, and patches welcome.
=head1 AUTHOR
T.J. Mather, E<lt>tjmather@maxmind.comE<gt>
=head1 COPYRIGHT
Copyright (c) 2002 T.J. Mather. Crypt::OpenSSL::DSA is free software;
you may redistribute it and/or modify it under the same terms as Perl itself.
Paid support is available directly from the author of this package.
Please see L<http://www.maxmind.com/app/opensourceservices> for more details.
=head1 SEE ALSO
L<Crypt::OpenSSL::DSA::Signature>
L<Crypt::DSA>, L<Crypt::OpenSSL::RSA>
L<Net::DNS::SEC>
=cut

View File

@@ -0,0 +1,62 @@
=head1 NAME
Crypt::OpenSSL::DSA::Signature - Digital Signature Object
=head1 SYNOPSIS
use Crypt::OpenSSL::DSA;
my $dsa_priv = Crypt::OpenSSL::DSA->read_priv_key( $filename );
my $sig_obj = $dsa_priv->do_sign($message);
my $dsa_pub = Crypt::OpenSSL::DSA->read_pub_key( $filename );
my $valid = $dsa_pub->do_verify($message, $sig_obj);
my $r = $sig_obj->get_r;
my $s = $sig_obj->get_s;
my $sig_obj2 = Crypt::OpenSSL::DSA::Signature->new();
$sig_obj2->set_r($r);
$sig_obj2->set_s($s);
my $valid = $dsa_pub->do_verify($message, $sig_obj2);
=head1 CLASS METHODS
=over
=item $sig_obj = Crypt::OpenSSL::DSA::Signature->new();
Create a new DSA Signature Object. You will need to
call set_r and set_s after you create this.
=back
=head1 OBJECT METHODS
=over
=item $r = $sig_obj->get_r;
Gets first member of signature pair.
=item $s = $sig_obj->get_s;
Gets second member of signature pair.
=item $r = $sig_obj->set_r;
Sets first member of signature pair.
=item $s = $sig_obj->set_s;
Sets second member of signature pair.
=back
=head1 AUTHOR
T.J. Mather, E<lt>tjmather@maxmind.comE<gt>
=head1 SEE ALSO
L<Crypt::OpenSSL::DSA>
=cut

View File

@@ -0,0 +1,259 @@
package Crypt::OpenSSL::Guess;
use 5.008001;
use strict;
use warnings;
our $VERSION = "0.11";
use File::Spec;
use Config;
use Symbol qw(gensym);
use Exporter 'import';
our @EXPORT = qw(openssl_inc_paths openssl_lib_paths find_openssl_prefix find_openssl_exec openssl_version);
sub openssl_inc_paths {
my $prefix = find_openssl_prefix();
my $exec = find_openssl_exec($prefix);
return '' unless -x $exec;
my @inc_paths;
for ("$prefix/include", "$prefix/inc32", '/usr/kerberos/include') {
push @inc_paths, $_ if -f "$_/openssl/ssl.h";
}
return join ' ', map { "-I$_" } @inc_paths;
}
sub openssl_lib_paths {
my $prefix = find_openssl_prefix();
my $exec = find_openssl_exec($prefix);
return '' unless -x $exec;
my @lib_paths;
for ($prefix, "$prefix/lib64", "$prefix/lib", "$prefix/out32dll") {
push @lib_paths, $_ if -d $_;
}
if ($^O eq 'MSWin32') {
push @lib_paths, "$prefix/lib/VC" if -d "$prefix/lib/VC";
my $found = 0;
my @pairs = ();
# Library names depend on the compiler
@pairs = (['eay32','ssl32'],['crypto.dll','ssl.dll'],['crypto','ssl']) if $Config{cc} =~ /gcc/;
@pairs = (['libeay32','ssleay32'],['libeay32MD','ssleay32MD'],['libeay32MT','ssleay32MT']) if $Config{cc} =~ /cl/;
for my $dir (@lib_paths) {
for my $p (@pairs) {
$found = 1 if ($Config{cc} =~ /gcc/ && -f "$dir/lib$p->[0].a" && -f "$dir/lib$p->[1].a");
$found = 1 if ($Config{cc} =~ /cl/ && -f "$dir/$p->[0].lib" && -f "$dir/p->[1].lib");
if ($found) {
@lib_paths = ($dir);
last;
}
}
}
}
elsif ($^O eq 'VMS') {
if (-r 'sslroot:[000000]openssl.cnf') { # openssl.org source install
@lib_paths = ('SSLLIB');
}
elsif (-r 'ssl$root:[000000]openssl.cnf') { # HP install
@lib_paths = ('SYS$SHARE');
}
}
return join ' ', map { "-L$_" } @lib_paths;
}
my $other_try = 0;
my @nopath;
sub check_no_path { # On OS/2 it would be typically on default paths
my $p;
if (not($other_try++) and $] >= 5.008001) {
use ExtUtils::MM;
my $mm = MM->new();
my ($list) = $mm->ext("-lssl");
return unless $list =~ /-lssl\b/;
for $p (split /\Q$Config{path_sep}/, $ENV{PATH}) {
@nopath = ("$p/openssl$Config{_exe}", # exe name
'.') # dummy lib path
if -x "$p/openssl$Config{_exe}"
}
}
@nopath;
}
sub find_openssl_prefix {
my ($dir) = @_;
if (defined $ENV{OPENSSL_PREFIX}) {
return $ENV{OPENSSL_PREFIX};
}
my @guesses = (
'/home/linuxbrew/.linuxbrew/opt/openssl/bin/openssl' => '/home/linuxbrew/.linuxbrew/opt/openssl', # LinuxBrew openssl
'/usr/local/opt/openssl/bin/openssl' => '/usr/local/opt/openssl', # OSX homebrew openssl
'/usr/local/bin/openssl' => '/usr/local', # OSX homebrew openssl
'/opt/local/bin/openssl' => '/opt/local', # Macports openssl
'/usr/bin/openssl' => '/usr',
'/usr/sbin/openssl' => '/usr',
'/opt/ssl/bin/openssl' => '/opt/ssl',
'/opt/ssl/sbin/openssl' => '/opt/ssl',
'/usr/local/ssl/bin/openssl' => '/usr/local/ssl',
'/usr/local/openssl/bin/openssl' => '/usr/local/openssl',
'/apps/openssl/std/bin/openssl' => '/apps/openssl/std',
'/usr/sfw/bin/openssl' => '/usr/sfw', # Open Solaris
'C:\OpenSSL\bin\openssl.exe' => 'C:\OpenSSL',
'C:\OpenSSL-Win32\bin\openssl.exe' => 'C:\OpenSSL-Win32',
$Config{prefix} . '\bin\openssl.exe' => $Config{prefix}, # strawberry perl
$Config{prefix} . '\..\c\bin\openssl.exe' => $Config{prefix} . '\..\c', # strawberry perl
'/sslexe/openssl.exe' => '/sslroot', # VMS, openssl.org
'/ssl$exe/openssl.exe' => '/ssl$root', # VMS, HP install
);
while (my $k = shift @guesses
and my $v = shift @guesses) {
if ( -x $k ) {
return $v;
}
}
(undef, $dir) = check_no_path()
and return $dir;
return;
}
sub find_openssl_exec {
my ($prefix) = @_;
my $exe_path;
for my $subdir (qw( bin sbin out32dll ia64_exe alpha_exe )) {
my $path = File::Spec->catfile($prefix, $subdir, "openssl$Config{_exe}");
if ( -x $path ) {
return $path;
}
}
($prefix) = check_no_path()
and return $prefix;
return;
}
sub openssl_version {
my ($major, $minor, $letter);
my $prefix = find_openssl_prefix();
my $exec = find_openssl_exec($prefix);
return unless -x $exec;
{
my $pipe = gensym();
open($pipe, qq{"$exec" version |})
or die "Could not execute $exec";
my $output = <$pipe>;
chomp $output;
close $pipe;
if ( ($major, $minor, $letter) = $output =~ /^OpenSSL\s+(\d+\.\d+)\.(\d+)([a-z]?)/ ) {
} elsif ( ($major, $minor) = $output =~ /^LibreSSL\s+(\d+\.\d+)\.(\d+)/ ) {
} else {
die <<EOM
*** OpenSSL version test failed
(`$output' has been returned)
Either you have bogus OpenSSL or a new version has changed the version
number format. Please inform the authors!
EOM
}
}
return ($major, $minor, $letter);
}
1;
__END__
=encoding utf-8
=head1 NAME
Crypt::OpenSSL::Guess - Guess OpenSSL include path
=head1 SYNOPSIS
use ExtUtils::MakerMaker;
use Crypt::OpenSSL::Guess;
WriteMakefile(
# ...
LIBS => ['-lssl -lcrypto ' . openssl_lib_paths()],
INC => openssl_inc_paths(), # guess include path or get from $ENV{OPENSSL_PREFIX}
);
=head1 DESCRIPTION
Crypt::OpenSSL::Guess provides helpers to guess OpenSSL include path on any platforms.
Often MacOS's homebrew OpenSSL cause a problem on installation due to include path is not added.
Some CPAN module provides to modify include path with configure-args, but L<Carton> or L<Module::CPANfile>
is not supported to pass configure-args to each modules. Crypt::OpenSSL::* modules should use it on your L<Makefile.PL>.
This module resolves the include path by L<Net::SSLeay>'s workaround.
Original code is taken from C<inc/Module/Install/PRIVATE/Net/SSLeay.pm> by L<Net::SSLeay>.
=head1 FUNCTIONS
=over 4
=item openssl_inc_paths()
This functions returns include paths in the format passed to CC. If OpenSSL could not find, then empty string is returned.
openssl_inc_paths(); # on MacOS: "-I/usr/local/opt/openssl/include"
=item openssl_lib_paths()
This functions returns library paths in the format passed to CC. If OpenSSL could not find, then empty string is returned.
openssl_lib_paths(); # on MacOS: "-L/usr/local/opt/openssl -L/usr/local/opt/openssl/lib"
=item find_openssl_prefix([$dir])
This function returns OpenSSL's prefix. If set C<OPENSSL_PREFIX> environment variable, you can overwrite the return value.
find_openssl_prefix(); # on MacOS: "/usr/local/opt/openssl"
=item find_openssl_exec($prefix)
This functions returns OpenSSL's executable path.
find_openssl_exec(); # on MacOS: "/usr/local/opt/openssl/bin/openssl"
=item ($major, $minor, $letter) = openssl_version()
This functions returns OpenSSL's version as major, minor, letter.
openssl_version(); # ("1.0", "2", "n")
=back
=head1 SEE ALSO
L<Net::SSLeay>
=head1 LICENSE
Copyright (C) Takumi Akiyama.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 AUTHOR
Takumi Akiyama E<lt>t.akiym@gmail.comE<gt>
=cut

View File

@@ -0,0 +1,328 @@
package Crypt::OpenSSL::RSA;
use strict;
use warnings;
use Carp; # Removing carp will break the XS code.
our $VERSION = '0.31';
our $AUTOLOAD;
use AutoLoader 'AUTOLOAD';
use XSLoader;
XSLoader::load 'Crypt::OpenSSL::RSA', $VERSION;
BEGIN {
eval { require Crypt::OpenSSL::Bignum };
} ## no critic qw(RequireCheckingReturnValueOfEval);
1;
__END__
=head1 NAME
Crypt::OpenSSL::RSA - RSA encoding and decoding, using the openSSL libraries
=head1 SYNOPSIS
use Crypt::OpenSSL::Random;
use Crypt::OpenSSL::RSA;
# not necessary if we have /dev/random:
Crypt::OpenSSL::Random::random_seed($good_entropy);
Crypt::OpenSSL::RSA->import_random_seed();
$rsa_pub = Crypt::OpenSSL::RSA->new_public_key($key_string);
$rsa_pub->use_sslv23_padding(); # use_pkcs1_oaep_padding is the default
$ciphertext = $rsa->encrypt($plaintext);
$rsa_priv = Crypt::OpenSSL::RSA->new_private_key($key_string);
$plaintext = $rsa->encrypt($ciphertext);
$rsa = Crypt::OpenSSL::RSA->generate_key(1024); # or
$rsa = Crypt::OpenSSL::RSA->generate_key(1024, $prime);
print "private key is:\n", $rsa->get_private_key_string();
print "public key (in PKCS1 format) is:\n",
$rsa->get_public_key_string();
print "public key (in X509 format) is:\n",
$rsa->get_public_key_x509_string();
$rsa_priv->use_md5_hash(); # insecure. use_sha256_hash or use_sha1_hash are the default
$signature = $rsa_priv->sign($plaintext);
print "Signed correctly\n" if ($rsa->verify($plaintext, $signature));
=head1 DESCRIPTION
C<Crypt::OpenSSL::RSA> provides the ability to RSA encrypt strings which are
somewhat shorter than the block size of a key. It also allows for decryption,
signatures and signature verification.
I<NOTE>: Many of the methods in this package can croak, so use C<eval>, or
Error.pm's try/catch mechanism to capture errors. Also, while some
methods from earlier versions of this package return true on success,
this (never documented) behavior is no longer the case.
=head1 Class Methods
=over
=item new_public_key
Create a new C<Crypt::OpenSSL::RSA> object by loading a public key in
from a string containing Base64/DER-encoding of either the PKCS1 or
X.509 representation of the key. The string should include the
C<-----BEGIN...-----> and C<-----END...-----> lines.
The padding is set to PKCS1_OAEP, but can be changed with the
C<use_xxx_padding> methods.
=cut
sub new_public_key {
my ( $proto, $p_key_string ) = @_;
if ( $p_key_string =~ /^-----BEGIN RSA PUBLIC KEY-----/ ) {
return $proto->_new_public_key_pkcs1($p_key_string);
}
elsif ( $p_key_string =~ /^-----BEGIN PUBLIC KEY-----/ ) {
return $proto->_new_public_key_x509($p_key_string);
}
else {
croak "unrecognized key format";
}
}
=item new_private_key
Create a new C<Crypt::OpenSSL::RSA> object by loading a private key in
from an string containing the Base64/DER encoding of the PKCS1
representation of the key. The string should include the
C<-----BEGIN...-----> and C<-----END...-----> lines. The padding is set to
PKCS1_OAEP, but can be changed with C<use_xxx_padding>.
=item generate_key
Create a new C<Crypt::OpenSSL::RSA> object by constructing a
private/public key pair. The first (mandatory) argument is the key
size, while the second optional argument specifies the public exponent
(the default public exponent is 65537). The padding is set to
C<PKCS1_OAEP>, but can be changed with use_xxx_padding methods.
=item new_key_from_parameters
Given L<Crypt::OpenSSL::Bignum> objects for n, e, and optionally d, p,
and q, where p and q are the prime factors of n, e is the public
exponent and d is the private exponent, create a new
Crypt::OpenSSL::RSA object using these values. If p and q are
provided and d is undef, d is computed. Note that while p and q are
not necessary for a private key, their presence will speed up
computation.
=cut
sub new_key_from_parameters {
my ( $proto, $n, $e, $d, $p, $q ) = @_;
return $proto->_new_key_from_parameters( map { $_ ? $_->pointer_copy() : 0 } $n, $e, $d, $p, $q );
}
=item import_random_seed
Import a random seed from L<Crypt::OpenSSL::Random>, since the OpenSSL
libraries won't allow sharing of random structures across perl XS
modules.
=cut
sub import_random_seed {
until ( _random_status() ) {
_random_seed( Crypt::OpenSSL::Random::random_bytes(20) );
}
}
=back
=head1 Instance Methods
=over
=item DESTROY
Clean up after ourselves. In particular, erase and free the memory
occupied by the RSA key structure.
=item get_public_key_string
Return the Base64/DER-encoded PKCS1 representation of the public
key. This string has
header and footer lines:
-----BEGIN RSA PUBLIC KEY------
-----END RSA PUBLIC KEY------
=item get_public_key_x509_string
Return the Base64/DER-encoded representation of the "subject
public key", suitable for use in X509 certificates. This string has
header and footer lines:
-----BEGIN PUBLIC KEY------
-----END PUBLIC KEY------
and is the format that is produced by running C<openssl rsa -pubout>.
=item get_private_key_string
Return the Base64/DER-encoded PKCS1 representation of the private
key. This string has
header and footer lines:
-----BEGIN RSA PRIVATE KEY------
-----END RSA PRIVATE KEY------
=item encrypt
Encrypt a binary "string" using the public (portion of the) key.
=item decrypt
Decrypt a binary "string". Croaks if the key is public only.
=item private_encrypt
Encrypt a binary "string" using the private key. Croaks if the key is
public only.
=item public_decrypt
Decrypt a binary "string" using the public (portion of the) key.
=item sign
Sign a string using the secret (portion of the) key.
=item verify
Check the signature on a text.
=item use_no_padding
Use raw RSA encryption. This mode should only be used to implement
cryptographically sound padding modes in the application code.
Encrypting user data directly with RSA is insecure.
=item use_pkcs1_padding
Use PKCS #1 v1.5 padding. This currently is the most widely used mode
of padding.
=item use_pkcs1_oaep_padding
Use C<EME-OAEP> padding as defined in PKCS #1 v2.0 with SHA-1, MGF1 and
an empty encoding parameter. This mode of padding is recommended for
all new applications. It is the default mode used by
C<Crypt::OpenSSL::RSA>.
=item use_sslv23_padding
Use C<PKCS #1 v1.5> padding with an SSL-specific modification that
denotes that the server is SSL3 capable.
=item use_md5_hash
Use the RFC 1321 MD5 hashing algorithm by Ron Rivest when signing and
verifying messages.
Note that this is considered B<insecure>.
=item use_sha1_hash
Use the RFC 3174 Secure Hashing Algorithm (FIPS 180-1) when signing
and verifying messages. This is the default, when use_sha256_hash is
not available.
=item use_sha224_hash, use_sha256_hash, use_sha384_hash, use_sha512_hash
These FIPS 180-2 hash algorithms, for use when signing and verifying
messages, are only available with newer openssl versions (>= 0.9.8).
use_sha256_hash is the default hash mode when available.
=item use_ripemd160_hash
Dobbertin, Bosselaers and Preneel's RIPEMD hashing algorithm when
signing and verifying messages.
=item use_whirlpool_hash
Vincent Rijmen und Paulo S. L. M. Barreto ISO/IEC 10118-3:2004
WHIRLPOOL hashing algorithm when signing and verifying messages.
=item size
Returns the size, in bytes, of the key. All encrypted text will be of
this size, and depending on the padding mode used, the length of
the text to be encrypted should be:
=over
=item pkcs1_oaep_padding
at most 42 bytes less than this size.
=item pkcs1_padding or sslv23_padding
at most 11 bytes less than this size.
=item no_padding
exactly this size.
=back
=item check_key
This function validates the RSA key, returning a true value if the key
is valid, and a false value otherwise. Croaks if the key is public only.
=item get_key_parameters
Return C<Crypt::OpenSSL::Bignum> objects representing the values of C<n>,
C<e>, C<d>, C<p>, C<q>, C<d mod (p-1)>, C<d mod (q-1)>, and C<1/q mod p>,
where C<p> and C<q> are the prime factors of C<n>, C<e> is the public
exponent and C<d> is the private exponent. Some of these values may return
as C<undef>; only C<n> and C<e> will be defined for a public key. The
C<Crypt::OpenSSL::Bignum> module must be installed for this to work.
=item is_private
Return true if this is a private key, and false if it is private only.
=cut
sub get_key_parameters {
return map { $_ ? Crypt::OpenSSL::Bignum->bless_pointer($_) : undef } shift->_get_key_parameters();
}
=back
=head1 BUGS
There is a small memory leak when generating new keys of more than 512 bits.
=head1 AUTHOR
Ian Robertson, C<iroberts@cpan.org>. For support, please email
C<perl-openssl-users@lists.sourceforge.net>.
=head1 ACKNOWLEDGEMENTS
=head1 LICENSE
Copyright (c) 2001-2011 Ian Robertson. Crypt::OpenSSL::RSA is free
software; you may redistribute it and/or modify it under the same
terms as Perl itself.
=head1 SEE ALSO
L<perl(1)>, L<Crypt::OpenSSL::Random(3)>, L<Crypt::OpenSSL::Bignum(3)>,
L<rsa(3)>, L<RSA_new(3)>, L<RSA_public_encrypt(3)>, L<RSA_size(3)>,
L<RSA_generate_key(3)>, L<RSA_check_key(3)>
=cut

View File

@@ -0,0 +1,110 @@
package Crypt::OpenSSL::Random;
use strict;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
use XSLoader;
require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw( random_bytes random_pseudo_bytes random_seed
random_egd random_status );
$VERSION = '0.15';
XSLoader::load( __PACKAGE__, $VERSION );
1;
__END__
=head1 NAME
Crypt::OpenSSL::Random - OpenSSL/LibreSSL pseudo-random number generator access
=head1 SYNOPSIS
use Crypt::OpenSSL::Random;
Crypt::OpenSSL::Random::random_seed($good_random_data);
Crypt::OpenSSL::Random::random_egd("/tmp/entropy");
Crypt::OpenSSL::Random::random_status() or
die "Unable to sufficiently seed the random number generator".
my $ten_good_random_bytes = Crypt::OpenSSL::Random::random_bytes(10);
my $ten_ok_random_bytes = Crypt::OpenSSL::Random::random_pseudo_bytes(10);
=head1 DESCRIPTION
C<Crypt::OpenSSL::Random> provides the ability to seed and query the
B<OpenSSL> and B<LibreSSL> library's pseudo-random number generators.
Note: On B<LibreSSL> C<random_egd()> is not defined.
=head2 EXPORT
None by default.
=head1 Static Methods
=over
=item random_bytes (IV num_bytes)
This function, returns a specified number of cryptographically strong
pseudo-random bytes from the PRNG. If the PRNG has not been seeded
with enough randomness to ensure an unpredictable byte sequence, then
a false value is returned.
=item random_pseudo_bytes (IV num_bytes)
This function, is similar to C<random_bytes>, but the resulting
sequence of bytes are not necessarily unpredictable. They can be used
for non-cryptographic purposes and for certain purposes in
cryptographic protocols, but usually not for key generation etc.
=item random_seed (PV random_bytes_string)
This function seeds the PRNG with a supplied string of bytes. It
returns true if the PRNG has sufficient seeding. Note: calling this
function with non-random bytes is of limited value at best!
=item random_egd (PV egd_string)
This function seeds the PRNG with data from the specified entropy
gathering daemon. Returns the number of bytes read from the daemon on
success, or C<-1> if not enough bytes were read, or if the connection to
the daemon failed.
C<libressl> considers this function insecure, so with libressl this
function does not exist.
=item random_status ()
This function returns true if the PRNG has sufficient seeding.
=back
=head1 BUGS
Because of the internal workings of OpenSSL's random library, the
pseudo-random number generator (PRNG) accessed by
Crypt::OpenSSL::Random will be different than the one accessed by any
other perl module. Hence, to use a module such as
Crypt::OpenSSL::Random, you will need to seed the PRNG used there from
one used here. This class is still advantageous, however, as it
centralizes other methods, such as C<random_egd>, in one place.
=head1 AUTHOR
Ian Robertson, C<iroberts@cpan.com>
Now maintained by Reini Urban, C<rurban@cpan.org>
=head1 LICENSE
This module is available under the same licences as perl, the Artistic
license and the GPL.
=head1 SEE ALSO
perl(1), rand(3), RAND_add(3), RAND_egd(3), RAND_bytes(3).
=cut

View File

@@ -0,0 +1,443 @@
package Crypt::OpenSSL::X509;
use strict;
use Exporter;
use base qw(Exporter);
our $VERSION = '1.902';
our @EXPORT_OK = qw(
FORMAT_UNDEF FORMAT_ASN1 FORMAT_TEXT FORMAT_PEM
FORMAT_PKCS12 FORMAT_SMIME FORMAT_ENGINE FORMAT_IISSGC OPENSSL_VERSION_NUMBER
);
sub Crypt::OpenSSL::X509::has_extension_oid {
my $x509 = shift;
my $oid = shift;
if (not $Crypt::OpenSSL::X509::exts_by_oid) {
$Crypt::OpenSSL::X509::exts_by_oid = $x509->extensions_by_oid;
}
return $$Crypt::OpenSSL::X509::exts_by_oid{$oid} ? 1 : 0;
}
sub Crypt::OpenSSL::X509::Extension::is_critical {
my $ext = shift;
my $crit = $ext->critical();
return $crit ? 1 : 0;
}
# return a hash for the values of keyUsage or nsCertType
sub Crypt::OpenSSL::X509::Extension::hash_bit_string {
my $ext = shift;
my @bits = split(//, $ext->bit_string);
my $len = @bits;
my %bit_str_hash = ();
if ($len == 9) { # bits for keyUsage
%bit_str_hash = (
'Digital Signature' => $bits[0],
'Non Repudiation' => $bits[1],
'Key Encipherment' => $bits[2],
'Data Encipherment' => $bits[3],
'Key Agreement' => $bits[4],
'Certificate Sign' => $bits[5],
'CRL Sign' => $bits[6],
'Encipher Only' => $bits[7],
'Decipher Only' => $bits[8],);
} elsif ($len == 8) { #bits for nsCertType
%bit_str_hash = (
'SSL Client' => $bits[0],
'SSL Server' => $bits[1],
'S/MIME' => $bits[2],
'Object Signing' => $bits[3],
'Unused' => $bits[4],
'SSL CA' => $bits[5],
'S/MIME CA' => $bits[6],
'Object Signing CA' => $bits[7],);
}
return %bit_str_hash;
}
sub Crypt::OpenSSL::X509::Extension::extKeyUsage {
my $ext = shift;
my @vals = split(/ /, $ext->extendedKeyUsage);
return @vals;
}
sub Crypt::OpenSSL::X509::is_selfsigned {
my $x509 = shift;
return $x509->subject eq $x509->issuer;
}
use XSLoader;
XSLoader::load 'Crypt::OpenSSL::X509', $VERSION;
END {
__PACKAGE__->__X509_cleanup;
}
1;
__END__
=head1 NAME
Crypt::OpenSSL::X509 - Perl extension to OpenSSL's X509 API.
=head1 SYNOPSIS
use Crypt::OpenSSL::X509;
my $x509 = Crypt::OpenSSL::X509->new_from_file('cert.pem');
print $x509->pubkey() . "\n";
print $x509->subject() . "\n";
print $x509->hash() . "\n";
print $x509->email() . "\n";
print $x509->issuer() . "\n";
print $x509->issuer_hash() . "\n";
print $x509->notBefore() . "\n";
print $x509->notAfter() . "\n";
print $x509->modulus() . "\n";
print $x509->exponent() . "\n";
print $x509->fingerprint_md5() . "\n";
print $x509->fingerprint_sha256() . "\n";
print $x509->as_string() . "\n";
my $x509 = Crypt::OpenSSL::X509->new_from_string(
$der_encoded_data, Crypt::OpenSSL::X509::FORMAT_ASN1
);
# given a time offset of $seconds, will the certificate be valid?
if ($x509->checkend($seconds)) {
# cert is expired at $seconds offset
} else {
# cert is ok at $seconds offset
}
my $exts = $x509->extensions_by_oid();
foreach my $oid (keys %$exts) {
my $ext = $$exts{$oid};
print $oid, " ", $ext->object()->name(), ": ", $ext->value(), "\n";
}
=head1 ABSTRACT
Crypt::OpenSSL::X509 - Perl extension to OpenSSL's X509 API.
=head1 DESCRIPTION
This implement a large majority of OpenSSL's useful X509 API.
The email() method supports both certificates where the
subject is of the form:
"... CN=Firstname lastname/emailAddress=user@domain", and also
certificates where there is a X509v3 Extension of the form
"X509v3 Subject Alternative Name: email=user@domain".
=head2 EXPORT
None by default.
On request:
FORMAT_UNDEF FORMAT_ASN1 FORMAT_TEXT FORMAT_PEM
FORMAT_PKCS12 FORMAT_SMIME FORMAT_ENGINE FORMAT_IISSGC
=head1 FUNCTIONS
=head2 X509 CONSTRUCTORS
=over 4
=item new ( )
Create a new X509 object.
=item new_from_string ( STRING [ FORMAT ] )
=item new_from_file ( FILENAME [ FORMAT ] )
Create a new X509 object from a string or file. C<FORMAT> should be C<FORMAT_ASN1> or C<FORMAT_PEM>.
=back
=head2 X509 ACCESSORS
=over 4
=item subject
Subject name as a string.
=item issuer
Issuer name as a string.
=item issuer_hash
Issuer name hash as a string.
=item serial
Serial number as a string.
=item hash
Alias for subject_hash
=item subject_hash
Subject name hash as a string.
=item notBefore
C<notBefore> time as a string.
=item notAfter
C<notAfter> time as a string.
=item email
Email address as a string.
=item version
Certificate version as a string.
=item sig_alg_name
Signature algorithm name as a string.
=item key_alg_name
Public key algorithm name as a string.
=item curve
Name of the EC curve used in the public key.
=back
=head2 X509 METHODS
=over 4
=item subject_name ( )
=item issuer_name ( )
Return a Name object for the subject or issuer name. Methods for handling Name objects are given below.
=item is_selfsigned ( )
Return Boolean value if subject and issuer name are the same.
=item as_string ( [ FORMAT ] )
Return the certificate as a string in the specified format. C<FORMAT> can be one of C<FORMAT_PEM> (the default) or C<FORMAT_ASN1>.
=item modulus ( )
Return the modulus for an RSA public key as a string of hex digits. For DSA and EC return the public key. Other algorithms are not supported.
=item bit_length ( )
Return the length of the modulus as a number of bits.
=item fingerprint_md5 ( )
=item fingerprint_sha1 ( )
=item fingerprint_sha224 ( )
=item fingerprint_sha256 ( )
=item fingerprint_sha384 ( )
=item fingerprint_sha512 ( )
Return the specified message digest for the certificate.
=item checkend( OFFSET )
Given an offset in seconds, will the certificate be expired? Returns True if the certificate will be expired. False otherwise.
=item pubkey ( )
Return the RSA, DSA, or EC public key.
=item num_extensions ( )
Return the number of extensions in the certificate.
=item extension ( INDEX )
Return the Extension specified by the integer C<INDEX>.
Methods for handling Extension objects are given below.
=item extensions_by_oid ( )
=item extensions_by_name ( )
=item extensions_by_long_name ( )
Return a hash of Extensions indexed by OID or name.
=item has_extension_oid ( OID )
Return true if the certificate has the extension specified by C<OID>.
=back
=head2 X509::Extension METHODS
=over 4
=item critical ( )
Return a value indicating if the extension is critical or not.
FIXME: the value is an ASN.1 BOOLEAN value.
=item object ( )
Return the ObjectID of the extension.
Methods for handling ObjectID objects are given below.
=item value ( )
Return the value of the extension as an asn1parse(1) style hex dump.
=item as_string ( )
Return a human-readable version of the extension as formatted by X509V3_EXT_print. Note that this will return an empty string for OIDs with unknown ASN.1 encodings.
=back
=head2 X509::ObjectID METHODS
=over 4
=item name ( )
Return the long name of the object as a string.
=item oid ( )
Return the numeric dot-separated form of the object identifier as a string.
=back
=head2 X509::Name METHODS
=over 4
=item as_string ( )
Return a string representation of the Name
=item entries ( )
Return an array of Name_Entry objects. Methods for handling Name_Entry objects are given below.
=item has_entry ( TYPE [ LASTPOS ] )
=item has_long_entry ( TYPE [ LASTPOS ] )
=item has_oid_entry ( TYPE [ LASTPOS ] )
Return true if a name has an entry of the specified C<TYPE>. Depending on the function the C<TYPE> may be in the short form (e.g. C<CN>), long form (C<commonName>) or OID (C<2.5.4.3>). If C<LASTPOS> is specified then the search is made from that index rather than from the start.
=item get_index_by_type ( TYPE [ LASTPOS ] )
=item get_index_by_long_type ( TYPE [ LASTPOS ] )
=item get_index_by_oid_type ( TYPE [ LASTPOS ] )
Return the index of an entry of the specified C<TYPE> in a name. Depending on the function the C<TYPE> may be in the short form (e.g. C<CN>), long form (C<commonName>) or OID (C<2.5.4.3>). If C<LASTPOS> is specified then the search is made from that index rather than from the start.
=item get_entry_by_type ( TYPE [ LASTPOS ] )
=item get_entry_by_long_type ( TYPE [ LASTPOS ] )
These methods work similarly to get_index_by_* but return the Name_Entry rather than the index.
=back
=head2 X509::Name_Entry METHODS
=over 4
=item as_string ( [ LONG ] )
Return a string representation of the Name_Entry of the form C<typeName=Value>. If C<LONG> is 1, the long form of the type is used.
=item type ( [ LONG ] )
Return a string representation of the type of the Name_Entry. If C<LONG> is 1, the long form of the type is used.
=item value ( )
Return a string representation of the value of the Name_Entry.
=item is_printableString ( )
=item is_ia5string ( )
=item is_utf8string ( )
=item is_asn1_type ( [ASN1_TYPE] )
Return true if the Name_Entry value is of the specified type. The value of C<ASN1_TYPE> should be as listed in OpenSSL's C<asn1.h>.
=back
=head1 SEE ALSO
OpenSSL(1), Crypt::OpenSSL::RSA, Crypt::OpenSSL::Bignum
=head1 AUTHOR
Dan Sully
=head1 CONTRIBUTORS
=over
=item * Neil Bowers, release 1.8.13
=item * kmx, release 1.8.9
=item * Sebastian Andrzej Siewior
=item * David O'Callaghan, E<lt>david.ocallaghan@cs.tcd.ieE<gt>
=item * Daniel Kahn Gillmor E<lt>dkg@fifthhorseman.netE<gt>
=back
=head1 COPYRIGHT AND LICENSE
Copyright 2004-2019 by Dan Sully
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=cut