Sample code for 30+ languages & platforms
Lua Requires Chilkat v9.5.0.97+

Create ECSDA Signature using Raw r and s Format (not ASN.1)

See more ECC Examples

Demonstrates how to create an ECDSA signature using the raw r/s format.

ECDSA signatures have two equal sized parts, r and s. There are two common formats for encoding the signature:

(a) Concatenating the raw byte array of r and s
(b) Encoding both into a structured ASN.1 / DER sequence.

This example demonstrates how to create a signature that is a byte array of r and s concatenated.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

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

-- To create an ECDSA signature, the data first needs to be hashed.  Then the hash
-- is signed.

local sb = chilkat.StringBuilder.new()
sb:append("The quick brown fox jumps over the lazy dog")
local hash = sb:get_hash("sha256", "base64", "utf-8")

-- Load the ECDSA key to be used for signing.
local privKey = chilkat.PrivateKey.new()
local success = privKey:load_pem_file("qa_data/ecc/secp256r1-key-pkcs8.pem")
if not success then
    print(privKey.last_error_text)
    return
end

local prng = chilkat.Prng.new()
local ecdsa = chilkat.Ecc.new()

-- Produce a signature that is not ASN.1, but is instead the concatenation
-- of the raw r and s signature parts.
ecdsa.asn_format = false

local ecdsaSigBase64 = ecdsa:sign_hash_enc(hash, "base64", privKey, prng)
if not ecdsa.last_method_success then
    print(ecdsa.last_error_text)
    return
end

print("ECDSA signature = " .. ecdsaSigBase64)

-- -----------------------------------------------------------
-- Now let's verify the signature using the public key.

local pubKey = chilkat.PublicKey.new()
success = pubKey:load_from_file("qa_data/ecc/secp256r1-pubkey.pem")
if not success then
    print(pubKey.last_error_text)
    return
end

-- Note: When verifying, Chilkat will auto-detect the format for both kinds of ECDSA signatures (ASN.1 or binary r+s)
local result = ecdsa:verify_hash_enc(hash, ecdsaSigBase64, "base64", pubKey)
if result == 1 then
    print("Signature is valid.")
    return
end

if result == 0 then
    print("Signature is invalid.")
    return
end

if result < 0 then
    print(ecdsa.last_error_text)
    print("The VerifyHashENC method call failed.")
    return
end