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

Generate RSA Key and Sign a String

See more RSA Examples

Demonstrates how to generate a new RSA public/private key pair and use it to generate a signature for a string. The (binary) digital signature is returned as a hexidecimalized string.

Chilkat Dart Downloads

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

void main() {
  // This example assumes the Chilkat API to have been previously unlocked.
  // See Global Unlock Sample for sample code.

  final rsa = CkRsa();

  // Generate a 2048-bit RSA key.
  final privKey = CkPrivateKey();
  rsa.genKey(2048, privKey);

  rsa.usePrivateKey(privKey);

  // Return the signature in hex.
  rsa.encodingMode = 'hex';

  final strData = 'This is the string to be signed.';

  // Sign the SHA256 hash of the string.
  final hexSig = rsa.signStringENC(strData, 'sha256');

  print(hexSig);

  // Now verify the signature:
  final pubKey = CkPublicKey();
  privKey.toPublicKey(pubKey);
  rsa.usePublicKey(pubKey);

  try {
    rsa.verifyStringENC(strData, 'sha256', hexSig);
    print('Signature verified!');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
  }

  // Try it with an invalid signature:
  try {
    rsa.verifyStringENC(strData, 'sha256', 'not a valid sig');
    print('Signature verified!');
  } on ChilkatException {
    print('Signature validation failed!');
  }

  // Try it with invalid data:
  try {
    rsa.verifyStringENC('Not the original data', 'sha256', hexSig);
    print('Signature verified!');
  } on ChilkatException {
    print('Signature validation failed!');
  }
}