Sample code for 30+ languages & platforms
Xbase++

ECDSA Sign and Verify Data using Different Hash Algorithms

See more ECC Examples

Demonstrates how to create ECDSA signatures on data using different hash algorithms.

Note: This example requires Chilkat v9.5.0.85 or greater because the SignBd and VerifyBd methods were added in v9.5.0.85.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oPrivKey
LOCAL oBd
LOCAL oEcdsa
LOCAL oPrng
LOCAL cSig
LOCAL oPubKey
LOCAL oEcc2
LOCAL nResult

nSuccess := 0

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

//  First load an ECDSA private key to be used for signing.
oPrivKey := CreateObject("Chilkat.PrivateKey")
nSuccess := oPrivKey:LoadEncryptedPemFile("qa_data/ecc/secp256r1-key-pkcs8-secret.pem", "secret")
IF (nSuccess == 0)
    ? oPrivKey:LastErrorText
    oPrivKey:destroy()
    RETURN
ENDIF

//  Load some data to be signed.
oBd := CreateObject("Chilkat.BinData")
nSuccess := oBd:LoadFile("qa_data/hamlet.xml")
IF (nSuccess == 0)
    ? "Failed to load file to be hashed."
    oPrivKey:destroy()
    oBd:destroy()
    RETURN
ENDIF

oEcdsa := CreateObject("Chilkat.Ecc")
oPrng := CreateObject("Chilkat.Prng")

//  Sign the sha256 hash of the data.  Return the ECDSA signature in the base64 encoding.
? "ECDSA signing the sha256 hash of the data..."
cSig := oEcdsa:SignBd(oBd, "sha256", "base64", oPrivKey, oPrng)
? "sig = " + cSig

//  Verify the signature against the original data.
//  (We must use the same hash algorithm that was used when signing.)

//  Load the public key that corresponds to the private key used for signing.
oPubKey := CreateObject("Chilkat.PublicKey")
nSuccess := oPubKey:LoadFromFile("qa_data/ecc/secp256r1-pub.pem")
IF (nSuccess == 0)
    ? oPubKey:LastErrorText
    oPrivKey:destroy()
    oBd:destroy()
    oEcdsa:destroy()
    oPrng:destroy()
    oPubKey:destroy()
    RETURN
ENDIF

oEcc2 := CreateObject("Chilkat.Ecc")
nResult := oEcc2:VerifyBd(oBd, "sha256", cSig, "base64", oPubKey)
IF (nResult != 1)
    ? oEcc2:LastErrorText
    oPrivKey:destroy()
    oBd:destroy()
    oEcdsa:destroy()
    oPrng:destroy()
    oPubKey:destroy()
    oEcc2:destroy()
    RETURN
ENDIF

? "Verified!"

//  ----------------------------------------------------------------------------------------
//  Let's do the same thing, but with sha384 hashing...

? "--------------------------------------------"
? "ECDSA signing the sha384 hash of the data..."

cSig := oEcdsa:SignBd(oBd, "sha384", "base64", oPrivKey, oPrng)
? "sig = " + cSig

nResult := oEcc2:VerifyBd(oBd, "sha384", cSig, "base64", oPubKey)
IF (nResult != 1)
    ? oEcc2:LastErrorText
    oPrivKey:destroy()
    oBd:destroy()
    oEcdsa:destroy()
    oPrng:destroy()
    oPubKey:destroy()
    oEcc2:destroy()
    RETURN
ENDIF

? "Verified!"

oPrivKey:destroy()
oBd:destroy()
oEcdsa:destroy()
oPrng:destroy()
oPubKey:destroy()
oEcc2:destroy()