PureBasic
PureBasic
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 PureBasic Downloads
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"
bd.i = CkBinData::ckCreate()
If bd.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
CkBinData::ckAppendEncoded(bd,originalData,"hex")
; If successful, the contents of bd are replaced with the RSA signature.
success = CkRsa::ckSignRawBd(rsa,bd)
If success = 0
Debug CkRsa::ckLastErrorText(rsa)
CkPrivateKey::ckDispose(privKey)
CkRsa::ckDispose(rsa)
CkBinData::ckDispose(bd)
ProcedureReturn
EndIf
; Show the RSA signature in base64
Debug CkBinData::ckGetEncoded(bd,"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 and extract the original data.
rsa2.i = CkRsa::ckCreate()
If rsa2.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
CkRsa::ckUsePublicKey(rsa2,pubKey)
bVerified.i = CkRsa::ckVerifyRawBd(rsa2,bd)
Debug "signature verified: " + Str(bVerified)
; Show the original data:
Debug "original data: " + CkBinData::ckGetEncoded(bd,"hex")
CkPrivateKey::ckDispose(privKey)
CkRsa::ckDispose(rsa)
CkBinData::ckDispose(bd)
CkPublicKey::ckDispose(pubKey)
CkRsa::ckDispose(rsa2)
ProcedureReturn
EndProcedure