Tcl
Tcl
RSA Signature/Verify with .key and .cer
See more RSA Examples
Demonstrates how to use a .key file (private key) and digital certificate (.cer, public key) to create and verify an RSA signature.Chilkat Tcl Downloads
load ./chilkat.dll
set success 0
# This example assumes the Chilkat API to have been previously unlocked.
# See Global Unlock Sample for sample code.
set privKey [new_CkPrivateKey]
# Load the private key from an RSA .key file:
set success [CkPrivateKey_LoadPemFile $privKey "privateKey.key"]
if {$success == 0} then {
puts [CkPrivateKey_lastErrorText $privKey]
delete_CkPrivateKey $privKey
exit
}
set rsa [new_CkRsa]
# Import the private key into the RSA component:
set success [CkRsa_UsePrivateKey $rsa $privKey]
if {$success == 0} then {
puts [CkRsa_lastErrorText $rsa]
delete_CkPrivateKey $privKey
delete_CkRsa $rsa
exit
}
# Create the signature as a hex string:
CkRsa_put_EncodingMode $rsa "hex"
set strData "This is the string to be signed."
# Sign the string using the sha256 hash algorithm.
# Other valid choices are "md2", "sha1", "sha384",
# "sha512", and "md5".
set hexSig [CkRsa_signStringENC $rsa $strData "sha256"]
puts "$hexSig"
# Load a digital certificate from a .cer file:
set cert [new_CkCert]
set success [CkCert_LoadFromFile $cert "myCert.cer"]
if {$success == 0} then {
puts [CkCert_lastErrorText $cert]
delete_CkPrivateKey $privKey
delete_CkRsa $rsa
delete_CkCert $cert
exit
}
set pubKey [new_CkPublicKey]
CkCert_GetPublicKey $cert $pubKey
# Now verify using a new instance of the RSA object:
set rsa2 [new_CkRsa]
# Import the public key into the RSA object:
set success [CkRsa_UsePublicKey $rsa2 $pubKey]
if {$success == 0} then {
puts [CkRsa_lastErrorText $rsa2]
delete_CkPrivateKey $privKey
delete_CkRsa $rsa
delete_CkCert $cert
delete_CkPublicKey $pubKey
delete_CkRsa $rsa2
exit
}
# The signature is a hex string, so make sure the EncodingMode is correct:
CkRsa_put_EncodingMode $rsa2 "hex"
# Verify the signature:
set success [CkRsa_VerifyStringENC $rsa2 $strData "sha256" $hexSig]
if {$success == 0} then {
puts [CkRsa_lastErrorText $rsa2]
delete_CkPrivateKey $privKey
delete_CkRsa $rsa
delete_CkCert $cert
delete_CkPublicKey $pubKey
delete_CkRsa $rsa2
exit
}
puts "Success."
delete_CkPrivateKey $privKey
delete_CkRsa $rsa
delete_CkCert $cert
delete_CkPublicKey $pubKey
delete_CkRsa $rsa2