Sample code for 30+ languages & platforms
DataFlex

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 DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoRsa
    Variant vPrivKey
    Handle hoPrivKey
    String sStrData
    String sHexSig
    Variant vPubKey
    Handle hoPubKey
    String sTemp1

    Move False To iSuccess

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

    Get Create (RefClass(cComChilkatRsa)) To hoRsa
    If (Not(IsComObjectCreated(hoRsa))) Begin
        Send CreateComObject of hoRsa
    End

    // Generate a 2048-bit RSA key.
    Get Create (RefClass(cComChilkatPrivateKey)) To hoPrivKey
    If (Not(IsComObjectCreated(hoPrivKey))) Begin
        Send CreateComObject of hoPrivKey
    End
    Get pvComObject of hoPrivKey to vPrivKey
    Get ComGenKey Of hoRsa 2048 vPrivKey To iSuccess

    Get pvComObject of hoPrivKey to vPrivKey
    Get ComUsePrivateKey Of hoRsa vPrivKey To iSuccess

    // Return the signature in hex.
    Set ComEncodingMode Of hoRsa To "hex"

    Move "This is the string to be signed." To sStrData

    // Sign the SHA256 hash of the string.
    Get ComSignStringENC Of hoRsa sStrData "sha256" To sHexSig

    Showln sHexSig

    // Now verify the signature:
    Get Create (RefClass(cComChilkatPublicKey)) To hoPubKey
    If (Not(IsComObjectCreated(hoPubKey))) Begin
        Send CreateComObject of hoPubKey
    End
    Get pvComObject of hoPubKey to vPubKey
    Get ComToPublicKey Of hoPrivKey vPubKey To iSuccess
    Get pvComObject of hoPubKey to vPubKey
    Get ComUsePublicKey Of hoRsa vPubKey To iSuccess

    Get ComVerifyStringENC Of hoRsa sStrData "sha256" sHexSig To iSuccess
    If (iSuccess = True) Begin
        Showln "Signature verified!"
    End
    Else Begin
        Get ComLastErrorText Of hoRsa To sTemp1
        Showln sTemp1
    End

    // Try it with an invalid signature:
    Get ComVerifyStringENC Of hoRsa sStrData "sha256" "not a valid sig" To iSuccess
    If (iSuccess = True) Begin
        Showln "Signature verified!"
    End
    Else Begin
        Showln "Signature validation failed!"
    End

    // Try it with invalid data:
    Get ComVerifyStringENC Of hoRsa "Not the original data" "sha256" sHexSig To iSuccess
    If (iSuccess = True) Begin
        Showln "Signature verified!"
    End
    Else Begin
        Showln "Signature validation failed!"
    End



End_Procedure