#!/usr/bin/perl

# Marc Brette (Marc.Brette@sxb.bsf.alcatel.fr)
# Thu, 18 Jun 1998 16:18:57 +0200

# Perl file to extract certificates from netscape database cert7.db
#
# It requires :
# * perl5
# * Berkeley DB database format support
#
# it takes the cert7.db file and split it into pairs of files
# name_n, file_n (where n is a number)
# the name_n file contains the DER encoded certificate subject DN
# the file_n file contains the DER encoded certificate
#
# Perl file to extract certificates from netscape database cert7.db
#
# It requires :
# * perl5
# * Berkeley DB database format support
#
# it takes the cert7.db file and split it into pairs of files
# name_n, file_n (where n is a number)
# the name_n file containing the DER encoded certificate subject DN
# the file_n file containing the whole DER encoded certificate
#
# Warning : there is user certificates CA as well as server certificate CA
# so you must pick up the one you want out of these files.
#
# The resulting certificate can be incorporated into the database with
# the CertStore utility.

use DB_File ;
# use DB_File ;
use vars qw( %h $k $v ) ;

tie %h, "DB_File", "cert7.db", O_RDONLY, 0640, $DB_HASH
or die "Cannot open file 'cert7.db': $!\n";
$i = 0 ;
# print the contents of the file
while (($k, $v) = each %h)
{
@Val = unpack("nn", $v) ;

if (@Val[1] == 1) {
open(OUTPUT, ">name_$i") ; select(OUTPUT) ;
print "$k" ;
close(OUTPUT);

@Val = unpack("x9nn", $k) ;
print "Cert size=", @Val[0] ;
print "\n" ;
print "Cert name size=", @Val[1];
print "\n" ;

open(OUTPUT, ">cert_$i") ; select(OUTPUT) ;
print unpack("x13 a@Val[0]", $v) ;
close(OUTPUT);
}
$i++ ;
}

untie %h ;
