Created
December 1, 2011 21:52
-
-
Save kmaglione/1420165 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use constant SIG_BUFFER => 32768; # SIG_BUFFER > max(length($signature)) | |
sub sig($) { | |
open(RDF, '>', $tmp) or die "Failed to create a temporary file: $!\n"; | |
binmode(RDF, ':raw:utf8'); | |
ser(*RDF, $_[0], '', ' ', 1); | |
close(RDF); | |
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | |
open(SIG, '-|', qq[openssl dgst -sha512 -sign "$pem"]. | |
($pwd? qq[ -passin "$pwd"]: '').qq[ -binary "$tmp"]) | |
or die "Failed to run OpenSSL to generate the signature: $!\n"; | |
binmode(SIG); | |
my $body; | |
my $size = read(SIG, $body, SIG_BUFFER); | |
close(SIG); | |
$? == 0 or die "OpenSSL failed to generate the signature\n"; | |
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | |
if (($size > 0) && ($size < SIG_BUFFER) && ($size == length($body))) { | |
my $asn1 = Convert::ASN1->new(encoding => 'DER'); | |
$asn1->prepare(q< | |
Algorithm ::= SEQUENCE { | |
oid OBJECT IDENTIFIER, | |
opt ANY OPTIONAL | |
} | |
Signature ::= SEQUENCE { | |
alg Algorithm, | |
sig BIT STRING | |
} | |
>); | |
my $data = $asn1->encode(sig => $body, | |
alg => {oid => sha512WithRSAEncryption()}); | |
if (defined($data)) { | |
return encode_base64($data, ''); | |
} else { | |
die "Failed to encode the generated signature: ".$asn1->error."\n"; | |
} | |
} else { | |
die "Failed to obtain the generated signature from OpenSSL\n"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment