Crypt-PKCS11-Easy

Wrapper around Crypt::PKCS11 to make using a HSM not suck


Keywords
cryptoki, encryption, hsm, perl, perl-module, perl5, pkcs11, signing
License
Artistic-1.0-Perl

Documentation

Build Status Coverage Status Kwalitee status GitHub issues GitHub tag Cpan license Cpan version

SYNOPSIS

use Crypt::PKCS11::Easy;
use IO::Prompter;

my $file = '/file/to/sign';

my $hsm = Crypt::PKCS11::Easy->new(
    module => 'libCryptoki2_64',
    key    => 'MySigningKey',
    slot   => '0',
    pin    => sub { prompt 'Enter PIN: ', -echo=>'*' },
);

my $base64_signature = $hsm->sign_and_encode(file => $file);
my $binary_signature = $hsm->decode_signature(data => $base64_signature);

$hsm->verify(file => $data_file, sig => $binary_signature)
  or die "VERIFICATION FAILED\n";

DESCRIPTION

This module is an OO wrapper around Crypt::PKCS11, designed primarily to make using a HSM as simple as possible.

Signing a file with Crypt::PKCS11

use IO::Prompter;
use Crypt::PKCS11;
use Crypt::PKCS11::Attributes;

my $pkcs11 = Crypt::PKCS11->new;
$pkcs11->load('/usr/safenet/lunaclient/lib/libCryptoki2_64.so');
$pkcs11->Initialize;
# assuming there is only one slot
my @slot_ids = $pkcs11->GetSlotList(1);
my $slot_id = shift @slot_ids;

my $session = $pkcs11->OpenSession($slot_id, CKF_SERIAL_SESSION)
    or die "Error" . $pkcs11->errstr;

$session->Login(CKU_USER, sub { prompt 'Enter PIN: ', -echo=>'*' } )
    or die "Failed to login: " . $session->errstr;

my $object_template = Crypt::PKCS11::Attributes->new->push(
    Crypt::PKCS11::Attribute::Label->new->set('MySigningKey'),
    Crypt::PKCS11::Attribute::Sign->new->set(1),
);
$session->FindObjectsInit($object_template);
my $objects = $session->FindObjects(1);
my $key = shift @$objects;

my $sign_mech = Crypt::PKCS11::CK_MECHANISM->new;
$sign_mech->set_mechanism(CKM_SHA1_RSA_PKCS);

$session->SignInit($sign_mech, $key)
    or die "Failed to set init signing: " . $session->errstr;

my $sig = $session->Sign('SIGN ME')
    or die "Failed to sign: " . $session->errstr;

Signing a file with Crypt::PKCS11::Easy

use Crypt::PKCS11::Easy;
use IO::Prompter;

my $hsm = Crypt::PKCS11::Easy->new(
    module => 'libCryptoki2_64',
    key    => 'MySigningKey',
    slot   => '0',
    pin    => sub { prompt 'Enter PIN: ', -echo=>'*' },
);

my $sig = $hsm->sign(data => 'SIGN ME');

To make that conciseness possible a Crypt::PKCS11::Object can only be used for one function, e.g. signing OR verifying, and cannot be set to use a different key or a different token after instantiation. A new object should be created for each function.

SEE ALSO