Perl-加密:: OpenSSL :: RSA-> new_public_key“错误:无法识别的密钥格式”

时间:2019-01-28 22:56:05

标签: perl encryption openssl rsa

我正在尝试根据使用OpenSSL RSA(2048)生成的私钥然后使用由我们具有API的组生成的公钥为Http请求调用生成令牌。令牌字符串的一侧使用公钥加密,另一侧使用私钥加密。私钥加密适用于以下代码,但调用Crypt::OpenSSL::RSA->new_public_key(public key string)失败,并出现“错误:无法识别的密钥格式”问题。我不确定该密钥出了什么问题,但是鉴于另一个可以正常工作(并且据说是使用相同的OpenSSL unix工具生成的),这似乎很奇怪。

任何帮助将不胜感激。

谢谢, 戴夫

use strict;

use Time::HiRes qw( gettimeofday );
use Crypt::OpenSSL::RSA;
use Crypt::OpenSSL::X509;
use Crypt::OpenSSL::Random;
use MIME::Base64;
use DateTime;


my $sysTime=undef;
my $sTime=undef;
my $sAPIToken;

my $EDMPrivateKey=qq~
-----BEGIN PRIVATE KEY-----
<private key base 64>
-----END PRIVATE KEY-----
~;

my $DMPublicKey=qq~
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsftmdt4aAZ7B1F7wVjIz0RSO6w1bIX/4
<rest of public key>
-----END PUBLIC KEY-----
~;

sub setTime() {
    my $ms;
    my $ms2;
    my $microSec;
    my $tz;
    ($sysTime,$microSec) = gettimeofday();
#    $sysTime=gettimeofday();
    $ms=sprintf("%.*s",3,$microSec);
    $ms2=$microSec-($ms*1000);
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime($sysTime);

    $sTime=sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%03d-%04d",
                                   $year+1900,$mon+1,$mday,$hour,$min,$sec,$ms,$tz);
    $sysTime=$sysTime*1000+$ms;
}

sub setTimeNew() {
    my $ms;
    my $ms2;
    my $microSec;
    ($sysTime,$microSec) = gettimeofday();
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime($sysTime);
    $ms=sprintf("%.*s",3,$microSec);
    $ms2=$microSec-($ms*1000);

    my $dt=DateTime->new(
      year       => $year+1900,
      month      => $mon+1,
      day        => $yday,
      hour       => $hour,
      minute     => $min,
      second     => $sec,
      nanosecond => $microSec*1000
    );
    $sysTime=$sysTime*1000+$ms;
    $sTime=$dt->strftime("%C%y-%m-%dT%H:%M:%S.%3N%z");
}


sub main() {
    my $sTokenPt1;
    my $sTokenPt2;
    my $sPubStr;

    my $rsaPublic  = Crypt::OpenSSL::RSA->new_public_key($DMPublicKey);
    $rsaPublic->use_sha1_hash();

    setTimeNew();

    $sTokenPt1 = encode_base64($rsaPrivate->encrypt($sysTime));
    $sTokenPt2 = encode_base64($rsaPublic->encrypt($sTime));

    printf "%d\n%s\n",$sysTime,$sTime;
    $sAPIToken = sprintf("%s,%s",$sTokenPt1,$sTokenPt2);
    printf "%d\n%s\nTTOKEN=%s\n",$sysTime,$sTime,$sAPIToken;


}
eval {
    main();
};

if ($@) {
    printf "Error : %s\n",$@;
}

0 个答案:

没有答案