Lua Requires Chilkat v9.5.0.85+
Lua
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.Chilkat Lua Downloads
local chilkat = require("chilkat")
-- 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.
local privKey = chilkat.PrivateKey.new()
local success = privKey:load_encrypted_pem_file("qa_data/ecc/secp256r1-key-pkcs8-secret.pem", "secret")
if not success then
print(privKey.last_error_text)
return
end
-- Load some data to be signed.
local bd = chilkat.BinData.new()
success = bd:load_file("qa_data/hamlet.xml")
if not success then
print("Failed to load file to be hashed.")
return
end
local ecdsa = chilkat.Ecc.new()
local prng = chilkat.Prng.new()
-- Sign the sha256 hash of the data. Return the ECDSA signature in the base64 encoding.
print("ECDSA signing the sha256 hash of the data...")
local sig = ecdsa:sign_bd(bd, "sha256", "base64", privKey, prng)
print("sig = " .. sig)
-- 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.
local pubKey = chilkat.PublicKey.new()
success = pubKey:load_from_file("qa_data/ecc/secp256r1-pub.pem")
if not success then
print(pubKey.last_error_text)
return
end
local ecc2 = chilkat.Ecc.new()
local result = ecc2:verify_bd(bd, "sha256", sig, "base64", pubKey)
if result ~= 1 then
print(ecc2.last_error_text)
return
end
print("Verified!")
-- ----------------------------------------------------------------------------------------
-- Let's do the same thing, but with sha384 hashing...
print("--------------------------------------------")
print("ECDSA signing the sha384 hash of the data...")
sig = ecdsa:sign_bd(bd, "sha384", "base64", privKey, prng)
print("sig = " .. sig)
result = ecc2:verify_bd(bd, "sha384", sig, "base64", pubKey)
if result ~= 1 then
print(ecc2.last_error_text)
return
end
print("Verified!")