Sample code for 30+ languages & platforms
PureBasic

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

PureBasic
IncludeFile "CkPublicKey.pb"
IncludeFile "CkPrivateKey.pb"
IncludeFile "CkRsa.pb"

Procedure ChilkatExample()

    success.i = 0

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

    rsa.i = CkRsa::ckCreate()
    If rsa.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ; Generate a 2048-bit RSA key.
    privKey.i = CkPrivateKey::ckCreate()
    If privKey.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkRsa::ckGenKey(rsa,2048,privKey)

    CkRsa::ckUsePrivateKey(rsa,privKey)

    ; Return the signature in hex.
    CkRsa::setCkEncodingMode(rsa, "hex")

    strData.s = "This is the string to be signed."

    ; Sign the SHA256 hash of the string.
    hexSig.s = CkRsa::ckSignStringENC(rsa,strData,"sha256")

    Debug hexSig

    ; Now verify the signature:
    pubKey.i = CkPublicKey::ckCreate()
    If pubKey.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkPrivateKey::ckToPublicKey(privKey,pubKey)
    CkRsa::ckUsePublicKey(rsa,pubKey)

    success = CkRsa::ckVerifyStringENC(rsa,strData,"sha256",hexSig)
    If success = 1
        Debug "Signature verified!"
    Else
        Debug CkRsa::ckLastErrorText(rsa)
    EndIf

    ; Try it with an invalid signature:
    success = CkRsa::ckVerifyStringENC(rsa,strData,"sha256","not a valid sig")
    If success = 1
        Debug "Signature verified!"
    Else
        Debug "Signature validation failed!"
    EndIf

    ; Try it with invalid data:
    success = CkRsa::ckVerifyStringENC(rsa,"Not the original data","sha256",hexSig)
    If success = 1
        Debug "Signature verified!"
    Else
        Debug "Signature validation failed!"
    EndIf



    CkRsa::ckDispose(rsa)
    CkPrivateKey::ckDispose(privKey)
    CkPublicKey::ckDispose(pubKey)


    ProcedureReturn
EndProcedure