Sample code for 30+ languages & platforms
Dart 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.

Note: This example uses methods introduced in Chilkat v9.5.0.77.

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  // 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.
  final privKey = CkPrivateKey();
  try {
    privKey.loadEncryptedPemFile('qa_data/pem/rsa_passwd.pem', 'passwd');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  final rsa = CkRsa();
  rsa.usePrivateKey(privKey);

  // We have some binary data (in hex) to sign
  final originalData = '0102030405060708090A';
  final bd = CkBinData();
  bd.appendEncoded(originalData, 'hex');

  // If successful, the contents of bd are replaced with the RSA signature.
  try {
    rsa.signRawBd(bd);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Show the RSA signature in base64
  print(bd.getEncoded('base64'));

  // ------------------------------------------
  // Get the public key from the private key
  final pubKey = CkPublicKey();
  privKey.toPublicKey(pubKey);

  // Verify the signature and extract the original data.
  final rsa2 = CkRsa();
  rsa2.usePublicKey(pubKey);

  var bVerified = true;
  try {
    rsa2.verifyRawBd(bd);
  } on ChilkatException {
    bVerified = false;
  }
  print('signature verified: $bVerified');

  // Show the original data:
  print('original data: ${bd.getEncoded('hex')}');
}