Crypt-X509

 view release on metacpan or  search on metacpan

lib/Crypt/X509.pm  view on Meta::CPAN

);

=head1 NAME

Crypt::X509 - Parse a X.509 certificate

=head1 SYNOPSIS

 use Crypt::X509;

 $decoded = Crypt::X509->new( cert => $cert );

 $subject_email	= $decoded->subject_email;
 print "do not use after: ".gmtime($decoded->not_after)." GMT\n";

=head1 REQUIRES

Convert::ASN1

=head1 DESCRIPTION

B<Crypt::X509> parses X.509 certificates. Methods are provided for accessing most
certificate elements.

It is based on the generic ASN.1 module by Graham Barr, on the F<x509decode>
example by Norbert Klasen and contributions on the perl-ldap-dev-Mailinglist
by Chriss Ridd.

=head1 CONSTRUCTOR

=head2 new ( OPTIONS )

Creates and returns a parsed X.509 certificate hash, containing the parsed
contents. The data is organised as specified in RFC 2459.
By default only the first ASN.1 Layer is decoded. Nested decoding
is done automagically through the data access methods.

=over 4

=item cert =E<gt> $certificate

A variable containing the DER formatted certificate to be parsed
(eg. as stored in C<usercertificate;binary> attribute in an
LDAP-directory).

=back

  use Crypt::X509;
  use Data::Dumper;

  $decoded= Crypt::X509->new(cert => $cert);

  print Dumper($decoded);

=cut back

sub new {
    my ( $class, %args ) = @_;
    if ( !defined($parser) || $parser->error ) {
        $parser = _init();
    }
    my $self = $parser->decode( $args{'cert'} );
    $self->{"_error"} = $parser->error;

lib/Crypt/X509.pm  view on Meta::CPAN

}

=head1 METHODS

=head2 error

Returns the last error from parsing, C<undef> when no error occured.
This error is updated on deeper parsing with the data access methods.


  $decoded= Crypt::X509->new(cert => $cert);
  if ($decoded->error) {
    warn "Error on parsing Certificate:".$decoded->error;
  }

=cut back

sub error {
    my $self = shift;
    return $self->{"_error"};
}

=head1 DATA ACCESS METHODS

lib/Crypt/X509.pm  view on Meta::CPAN

    return "v2" if $v == 1;
    return "v3" if $v == 2;
}

=head2 serial

returns the serial number (integer or Math::BigInt Object, that gets automagic
evaluated in scalar context) from the certificate


  $decoded= Crypt::X509->new(cert => $cert);
  print "Certificate has serial number:".$decoded->serial."\n";

=cut back

sub serial {
    my $self = shift;
    return $self->{tbsCertificate}{serialNumber};
}

=head2 not_before

returns the GMT-timestamp of the certificate's beginning date of validity.
If the Certificate holds this Entry in utcTime, it is guaranteed by the
RFC to been correct.

As utcTime is limited to 32-bit values (like unix-timestamps) newer certificates
hold the timesamps as "generalTime"-entries. B<The contents of "generalTime"-entries
are not well defined in the RFC and
are returned by this module unmodified>, if no utcTime-entry is found.


  $decoded= Crypt::X509->new(cert => $cert);
  if ($decoded->notBefore < time()) {
    warn "Certificate: not yet valid!";
  }

=cut back

sub not_before {
    my $self = shift;
    if ( $self->{tbsCertificate}{validity}{notBefore}{utcTime} ) {
        return $self->{tbsCertificate}{validity}{notBefore}{utcTime};
    } elsif ( $self->{tbsCertificate}{validity}{notBefore}{generalTime} ) {

lib/Crypt/X509.pm  view on Meta::CPAN

returns the GMT-timestamp of the certificate's ending date of validity.
If the Certificate holds this Entry in utcTime, it is guaranteed by the
RFC to been correct.

As utcTime is limited to 32-bit values (like unix-timestamps) newer certificates
hold the timesamps as "generalTime"-entries. B<The contents of "generalTime"-entries
are not well defined in the RFC and
are returned by this module unmodified>, if no utcTime-entry is found.


  $decoded= Crypt::X509->new(cert => $cert);
  print "Certificate expires on ".gmtime($decoded->not_after)." GMT\n";

=cut back

sub not_after {
    my $self = shift;
    if ( $self->{tbsCertificate}{validity}{notAfter}{utcTime} ) {
        return $self->{tbsCertificate}{validity}{notAfter}{utcTime};
    } elsif ( $self->{tbsCertificate}{validity}{notAfter}{generalTime} ) {
        return $self->{tbsCertificate}{validity}{notAfter}{generalTime};
    } else {

lib/Crypt/X509.pm  view on Meta::CPAN


sub pubkey_algorithm {
    my $self = shift;
    return $self->{tbsCertificate}{subjectPublicKeyInfo}{algorithm}{algorithm};
}

=head2 PubKeyAlg

returns the subject public key encryption algorithm (e.g. 'RSA') as string.

  $decoded= Crypt::X509->new(cert => $cert);
  print "Certificate public key is encrypted with:".$decoded->PubKeyAlg."\n";

  Example Output: Certificate public key is encrypted with: RSA

=cut back

sub PubKeyAlg {
    my $self = shift;
    return $oid2enchash{ $self->{tbsCertificate}{subjectPublicKeyInfo}{algorithm}{algorithm} }->{'enc'};
}

lib/Crypt/X509.pm  view on Meta::CPAN

          return $values;
        } else {
          return undef;
        }
}

=head2 sig_algorithm

Returns the certificate's signature algorithm as OID string

  $decoded= Crypt::X509->new(cert => $cert);
  print "Certificate signature is encrypted with:".$decoded->sig_algorithm."\n";>

  Example Output: Certificate signature is encrypted with: 1.2.840.113549.1.1.5

=cut back

sub sig_algorithm {
    my $self = shift;
    return $self->{tbsCertificate}{signature}{algorithm};
}

=head2 SigEncAlg

returns the signature encryption algorithm (e.g. 'RSA') as string.

  $decoded= Crypt::X509->new(cert => $cert);
  print "Certificate signature is encrypted with:".$decoded->SigEncAlg."\n";

  Example Output: Certificate signature is encrypted with: RSA

=cut back

sub SigEncAlg {
    my $self = shift;
    return $oid2enchash{ $self->{'signatureAlgorithm'}->{'algorithm'} }->{'enc'};
}

=head2 SigHashAlg

returns the signature hashing algorithm (e.g. 'SHA1') as string.

  $decoded= Crypt::X509->new(cert => $cert);
  print "Certificate signature is hashed with:".$decoded->SigHashAlg."\n";

  Example Output: Certificate signature is encrypted with: SHA1

=cut back

sub SigHashAlg {
    my $self = shift;
    return $oid2enchash{ $self->{'signatureAlgorithm'}->{'algorithm'} }->{'hash'};
}
#########################################################################
# accessors - subject
#########################################################################

=head2 Subject

returns a pointer to an array of strings containing subject nameparts of the
certificate. Attributenames for the most common Attributes are translated
from the OID-Numbers, unknown numbers are output verbatim.

  $decoded= Convert::ASN1::X509->new($cert);
  print "DN for this Certificate is:".join(',',@{$decoded->Subject})."\n";

=cut back

sub Subject {
    my $self = shift;
    my ( $i, $type );
    my $subjrdn = $self->{'tbsCertificate'}->{'subject'}->{'rdnSequence'};
    $self->{'tbsCertificate'}->{'subject'}->{'dn'} = [];
    my $subjdn = $self->{'tbsCertificate'}->{'subject'}->{'dn'};
    foreach my $subj ( @{$subjrdn} ) {

lib/Crypt/X509.pm  view on Meta::CPAN

#########################################################################
# accessors - issuer
#########################################################################

=head2 Issuer

returns a pointer to an array of strings building the DN of the certificate
issuer (= the DN of the CA). Attributenames for the most common Attributes
are translated from the OID-Numbers, unknown numbers are output verbatim.

  $decoded= Crypt::X509->new($cert);
  print "Certificate was issued by:".join(',',@{$decoded->Issuer})."\n";

=cut back
sub Issuer {
    my $self = shift;
    my ( $i, $type );
    my $issuerdn = $self->{'tbsCertificate'}->{'issuer'}->{'rdnSequence'};
    $self->{'tbsCertificate'}->{'issuer'}->{'dn'} = [];
    my $issuedn = $self->{'tbsCertificate'}->{'issuer'}->{'dn'};
    foreach my $issue ( @{$issuerdn} ) {
        foreach my $i ( @{$issue} ) {

lib/Crypt/X509.pm  view on Meta::CPAN

#########################################################################

=head2 KeyUsage

returns a pointer to an array of strings describing the valid Usages
for this certificate. C<undef> is returned, when the extension is not set in the
certificate.

If the extension is marked critical, this is also reported.

  $decoded= Crypt::X509->new(cert => $cert);
  print "Allowed usages for this Certificate are:\n".join("\n",@{$decoded->KeyUsage})."\n";

  Example Output:
  Allowed usages for this Certificate are:
  critical
  digitalSignature
  keyEncipherment
  dataEncipherment

=cut back
sub KeyUsage {

lib/Crypt/X509.pm  view on Meta::CPAN

}

=head2 ExtKeyUsage

returns a pointer to an array of ExtKeyUsage strings (or OIDs for unknown OIDs) or
C<undef> if the extension is not filled. OIDs of the following ExtKeyUsages are known:
serverAuth, clientAuth, codeSigning, emailProtection, timeStamping, OCSPSigning

If the extension is marked critical, this is also reported.

  $decoded= Crypt::X509->new($cert);
  print "ExtKeyUsage extension of this Certificates is: ", join(", ", @{$decoded->ExtKeyUsage}), "\n";

  Example Output: ExtKeyUsage extension of this Certificates is: critical, serverAuth

=cut back
our %oid2extkeyusage = (
      '1.3.6.1.5.5.7.3.1' => 'serverAuth',
      '1.3.6.1.5.5.7.3.2' => 'clientAuth',
      '1.3.6.1.5.5.7.3.3' => 'codeSigning',
      '1.3.6.1.5.5.7.3.4' => 'emailProtection',
      '1.3.6.1.5.5.7.3.8' => 'timeStamping',

lib/Crypt/X509.pm  view on Meta::CPAN

}

=head2 SubjectAltName

returns a pointer to an array of strings containing alternative Subjectnames or
C<undef> if the extension is not filled. Usually this Extension holds the e-Mail
address for person-certificates or DNS-Names for server certificates.

It also pre-pends the field type (ie rfc822Name) to the returned value.

  $decoded= Crypt::X509->new($cert);
  print "E-Mail or Hostnames in this Certificates is/are:", join(", ", @{$decoded->SubjectAltName}), "\n";

  Example Output: E-Mail or Hostnames in this Certificates is/are: rfc822Name=user@server.com

=cut back

sub SubjectAltName {
    my $self = shift;
    my $ext;
    my $exts = $self->{'tbsCertificate'}->{'extensions'};
    if ( !defined $exts ) { return undef; }

lib/Crypt/X509.pm  view on Meta::CPAN

        }
    }
    return undef;
}

=head2 DecodedSubjectAltNames

Returns a pointer to an array of strings containing all the alternative subject name
extensions.

Each such extension is represented as a decoded ASN.1 value, i.e. a pointer to a list
of pointers to objects, each object having a single key with the type of the alternative
name and a value specific to that type.

Example return value:

  [
    [
      {
        'directoryName' => {
          'rdnSequence' => [

lib/Crypt/X509.pm  view on Meta::CPAN

    return undef;
}

=head2 authorityCertIssuer

returns a pointer to an array of strings building the DN of the Authority Cert
Issuer. Attributenames for the most common Attributes
are translated from the OID-Numbers, unknown numbers are output verbatim.
undef if the extension is not set in the certificate.

  $decoded= Crypt::X509->new($cert);
  print "Certificate was authorised by:".join(',',@{$decoded->authorityCertIssuer})."\n";

=cut back

sub authorityCertIssuer {
    my $self = shift;
    my ( $i, $type );
    my $rdn = _AuthorityKeyIdentifier($self);
    if ( !defined($rdn) ) {
        return (undef);    # we do not have that extension
    } else {

lib/Crypt/X509.pm  view on Meta::CPAN

            return $CertPolicies;
        }
    }
    return undef;
}

=head2 EntrustVersionInfo

Returns the EntrustVersion as a string

    print "Entrust Version: ", $decoded->EntrustVersion, "\n";

    Example Output: Entrust Version: V7.0

=cut back

# EntrustVersion (another extension)
sub EntrustVersion {
    my $self = shift;
    my $extension;
    my $extensions = $self->{'tbsCertificate'}->{'extensions'};

lib/Crypt/X509.pm  view on Meta::CPAN

            # $entrust->{'entrustInfoFlags'}
        }
    }
    return undef;
}

=head2 SubjectDirectoryAttributes

Returns the SubjectDirectoryAttributes as an array of key = value pairs, to include a data type

    print "Subject Directory Attributes: ", join( ', ' , @{ $decoded->SubjectDirectoryAttributes } ), "\n";

    Example Output: Subject Directory Attributes: 1.2.840.113533.7.68.29 = 7 (integer)

=cut back

# SubjectDirectoryAttributes (another extension)
sub SubjectDirectoryAttributes {
    my $self = shift;
    my $extension;
    my $attributes = [];

lib/Crypt/X509.pm  view on Meta::CPAN

        }
    }
    return undef;
}

=head2 SubjectInfoAccess

Returns the SubjectInfoAccess as an array of hashes with key=value pairs.

        print "Subject Info Access: ";
        if ( defined $decoded->SubjectInfoAccess ) {
            my %SIA = $decoded->SubjectInfoAccess;
            for my $key ( keys %SIA ) {
                print "\n\t$key: \n\t";
                print join( "\n\t" , @{ $SIA{$key} } ), "\n";
            }
        } else { print "\n" }

    Example Output:
        Subject Info Access:
            1.3.6.1.5.5.7.48.5:
            uniformResourceIdentifier = http://pki.treas.gov/root_sia.p7c

lib/Crypt/X509.pm  view on Meta::CPAN

    return undef;
}


=head2 PGPExtension

Returns the creation timestamp of the corresponding OpenPGP key.
(see http://www.imc.org/ietf-openpgp/mail-archive/msg05320.html)

        print "PGPExtension: ";
        if ( defined $decoded->PGPExtension ) {
            my $creationtime = $decoded->PGPExtension;
            printf "\n\tcorresponding OpenPGP Creation Time: ", $creationtime, "\n";
                }

    Example Output:
        PGPExtension:
                    whatever

=cut back

# PGPExtension (another extension)



( run in 0.331 second using v1.01-cache-2.11-cpan-26ccb49234f )