Sample code for 30+ languages & platforms
Perl Requires Chilkat v11.0.0+

RSA Sign Binary Data and Verify (Recover the Original Data)

See more RSA Examples

Demonstrates how to RSA sign binary data and then verify/recover the original data.

Chilkat Perl Downloads

Perl
use strict;
use warnings;
use Chilkat2;

# This example requires the Chilkat API to have been previously unlocked.
# See Global Unlock Sample for sample code.

# Load an RSA private key for signing.
my $privKey = Chilkat2::PrivateKey->new;
my $success = $privKey->LoadEncryptedPemFile('qa_data/pem/rsa_passwd.pem', 'passwd');
if (!$success) {
    print $privKey->LastErrorText, "\n";
    exit;
}

my $rsa = Chilkat2::Rsa->new;
$rsa->UsePrivateKey($privKey);

# We have some binary data (in hex) to sign
my $originalData = '0102030405060708090A';
my $bd = Chilkat2::BinData->new;
$bd->AppendEncoded($originalData, 'hex');

# If successful, the contents of bd are replaced with the RSA signature.
$success = $rsa->SignRawBd($bd);
if (!$success) {
    print $rsa->LastErrorText, "\n";
    exit;
}

# Show the RSA signature in base64
print $bd->GetEncoded('base64'), "\n";

# ------------------------------------------
# Get the public key from the private key
my $pubKey = Chilkat2::PublicKey->new;
$privKey->ToPublicKey($pubKey);

# Verify the signature and extract the original data.
my $rsa2 = Chilkat2::Rsa->new;
$rsa2->UsePublicKey($pubKey);

my $bVerified = $rsa2->VerifyRawBd($bd);
print 'signature verified: ', ($bVerified ? 1 : 0), "\n";

# Show the original data:
print 'original data: ', $bd->GetEncoded('hex'), "\n";