0
votes

I'm trying to decrypt an RSA encrypted message using the public key.

Using Crypt::OpenSSL::RSA, I am able to encrypt using either key, but I can only decrypt with the private key. Attempting to decrypt with the public key:

use Crypt::OpenSSL::RSA;
use MIME::Base64;
use File::Slurp;

my $public_key  = 'rsa.pub.pem';
#my $private_key = 'rsa.priv.pem';
my $rsa_public  = Crypt::OpenSSL::RSA->new_public_key(scalar read_file $public_key);
#my $rsa_private = Crypt::OpenSSL::RSA->new_private_key(scalar read_file $private_key);

my $ciphertext_b64 = 'cqyPNNfqYaUeIsM1yAz7IsQ760Bkd4IPaatHnMQtQAMKtYTEUqFHwnSZ4hg2
pkoJM1N5Ejlv6Eqkk/ZaMWl1nTDOxRDj0V6PARQPqz3QF1UGWkSMxMt/DlSn
AtrRXgjvrILbMX5BsV2S5mHcLoCeNVb+jdnX0x0Uu/AAFPsByPRrt1yM1ORo
KcP+0ENvcvJ8yGOxJ2jOEmTFkQM5kjNDIFmLUlt6qODdTGWvYWR2CDduLO4m
qiyAt4yK5K3vwMybAG5ceRGb/kmMSW10EnvbryIdDGVGS8Zvodu3xqtbM1Yo
tdtZRDkcUcOYlUi3VRvSTimatVkJPG8QDlZofrBA0w==';

my $ciphertext = decode_base64($ciphertext_b64);

print $rsa_public->decrypt($ciphertext);
#print $rsa_private->decrypt($ciphertext);

Results in: Public keys cannot decrypt at test.pl line 19.

Incidentally, Ruby seems to have no problem encrypting and decrypting with either key (which is why I'm currently in this situation).

3

3 Answers

4
votes

Did you realize there is a public_decrypt method in Crypt::OpenSSL::RSA?

1
votes
#!/usr/bin/env perl
use strict;
use warnings;
use MIME::Base64;
use Data::Dumper;
use File::Slurp   qw(read_file);
use Crypt::OpenSSL::RSA;
use Convert::PEM;

my $rsa = Crypt::OpenSSL::RSA->generate_key(2048);
my $keyFile = "pri1.pem";
my $pubfile = "pub.pem";

my $string_Key = read_file($keyFile);
my $string_pub = read_file($pubfile);
my $rsa_pub = Crypt::OpenSSL::RSA->new_public_key($string_pub);
my $rsa_priv = Crypt::OpenSSL::RSA->new_private_key($string_Key);
$rsa_pub->use_pkcs1_padding();
my $plaintext = "Hello world";
my $ciphertext = $rsa_pub->encrypt($plaintext);
print encode_base64($ciphertext);

################################################


################################################################3

$rsa_priv->use_pkcs1_padding();
my $decrypttext = $rsa_priv->decrypt($ciphertext);
print "\ndecrypttext:\n", $decrypttext;
0
votes

You should either decrypt with the private key or verify a signature with the public key and use appropriate methods for doing so. It is unclear from your question whether you do encryption or signatures.

If you try to "decrypt an RSA encrypted message" then it is quite unclear what you want to do and what the library you are using is actually doing. The paddings that are used for encryption and digital signatures are different for RSA. Hence if you call the wrong methods then in the best case you get an error message and in the worst case you end up with an insecure scheme.