Sample code for 30+ languages & platforms
PureBasic

RSA Hash Binary Data and Sign (and Verify)

See more RSA Examples

Demonstrates how to sign the hash of binary data. Also demonstrates how to verify the RSA signature.

Chilkat PureBasic Downloads

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

Procedure ChilkatExample()

    success.i = 0

    ; 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.
    privKey.i = CkPrivateKey::ckCreate()
    If privKey.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkPrivateKey::ckLoadEncryptedPemFile(privKey,"qa_data/pem/rsa_passwd.pem","passwd")
    If success = 0
        Debug CkPrivateKey::ckLastErrorText(privKey)
        CkPrivateKey::ckDispose(privKey)
        ProcedureReturn
    EndIf

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

    CkRsa::ckUsePrivateKey(rsa,privKey)

    ; We have some binary data (in hex) to sign
    originalData.s = "0102030405060708090A"
    bdData.i = CkBinData::ckCreate()
    If bdData.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkBinData::ckAppendEncoded(bdData,originalData,"hex")

    ; Hash (SHA-256) and sign the hash:
    bdSignature.i = CkBinData::ckCreate()
    If bdSignature.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkRsa::ckSignBd(rsa,bdData,"sha256",bdSignature)
    If success = 0
        Debug CkRsa::ckLastErrorText(rsa)
        CkPrivateKey::ckDispose(privKey)
        CkRsa::ckDispose(rsa)
        CkBinData::ckDispose(bdData)
        CkBinData::ckDispose(bdSignature)
        ProcedureReturn
    EndIf

    ; Show the RSA signature in base64
    Debug CkBinData::ckGetEncoded(bdSignature,"base64")

    ; ------------------------------------------
    ; Get the public key from the private key
    pubKey.i = CkPublicKey::ckCreate()
    If pubKey.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkPrivateKey::ckToPublicKey(privKey,pubKey)

    ; Verify the signature..
    rsa2.i = CkRsa::ckCreate()
    If rsa2.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkRsa::ckUsePublicKey(rsa2,pubKey)

    bVerified.i = CkRsa::ckVerifyBd(rsa2,bdData,"sha256",bdSignature)
    Debug "signature verified: " + Str(bVerified)


    CkPrivateKey::ckDispose(privKey)
    CkRsa::ckDispose(rsa)
    CkBinData::ckDispose(bdData)
    CkBinData::ckDispose(bdSignature)
    CkPublicKey::ckDispose(pubKey)
    CkRsa::ckDispose(rsa2)


    ProcedureReturn
EndProcedure