Converting RSA keys to JSON in Perl

徘徊边缘 提交于 2019-12-11 14:02:26

问题


I need to find a way of transferring an RSA public key to a server for my network communication program. I have done some research, and it seems that the easiest way to do this is to convert the public key (which is stored as some kind of hash reference) to a JSON for transmission. However, in my test code I cannot get the key to convert to a JSON. Here is my test program:

use strict;
use warnings;

use Crypt::RSA;
use JSON;

my %hash = ( name => "bob",
             age  => 123,
             hates=> "Perl"
        );

    my $hash_ref = \%hash;
    my $hash_as_json = to_json($hash_ref);

    print $hash_as_json, "\n"; # Works fine for a normal hash

    my $rsa = new Crypt::RSA;

    my ($public, $private) = $rsa->keygen ( 
            Identity  => 'client',
            Size      => 512,  
            Password  => 'password', 
            Verbosity => 1,
        ) or die $rsa->errstr();

    my $key_hash_as_json = to_json($public, {allow_blessed => 1, convert_blessed => 1});
    print $key_hash_as_json, "\n";

Before I found the line {allow_blessed => 1, convert_blessed => 1} I got an error message saying

encountered object 'Crypt::RSA::Key::Public=HASH(0x3117128)', but neither allow_blessed, convert_blessed nor allow_tags settings are enabled (or TO_JSON/FREEZE method missing) at /home/alex/perl5/lib/perl5/JSON.pm line 154.

What does this mean and why did that line fix it?

After adding the code, it just gives null when I try and print the JSON. Why is this happening and how do I fix it?

Alternatively, is there a better way of doing what I am trying here?


回答1:


The most common way of representing an RSA public key as text is the PEM encoding. Unfortunately, Crypt::RSA does not provide any way to convert to or from this format, or indeed any other standard format. Don't use it!

Instead, I'd recommend that you use Crypt::OpenSSL::RSA. Generating a private key and printing its public form with this module is simple:

use Crypt::OpenSSL::RSA;

my $key = Crypt::OpenSSL::RSA->generate_key(512);
print $key->get_public_key_string;

This will output a PEM encoding like the following:

-----BEGIN RSA PUBLIC KEY-----
MEgCQQDd/5F9Rc5vsNuKBrd4gfI4BDgre/sTBKu3yXpk+8NjByKpClsi3IQEGYeG
wmv/q/1ZjflFby1MPxMhXZo/82CbAgMBAAE=
-----END RSA PUBLIC KEY-----



回答2:


Apart from already mentioned PEM there exists JWK format (JSON Web Key). Have a look at Crypt::PK::RSA (my module) which supports generating, importing and exporting RSA keys in both PEM and JWK.



来源:https://stackoverflow.com/questions/35637618/converting-rsa-keys-to-json-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!