Tcl
Tcl
RSA Sign with PKCS8 Encrypted Key
See more RSA Examples
Demonstrates how to load a private key from an encrypted PKCS8 file and create an RSA digital signature (and then verify it).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 PEM file:
set success [CkPrivateKey_LoadAnyFormatFile $privKey "raul_privateKey.key" "a0123456789"]
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
}
# This example will sign a string, and receive the signature
# in a hex-encoded string. Therefore, set the encoding mode
# to "hex":
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 sha1, sha384, sha512 and others.
set hexSig [CkRsa_signStringENC $rsa $strData "sha256"]
if {[CkRsa_get_LastMethodSuccess $rsa] == 0} then {
puts [CkRsa_lastErrorText $rsa]
delete_CkPrivateKey $privKey
delete_CkRsa $rsa
exit
}
puts "$hexSig"
# Now verify with the public key.
# This example shows how to use the public key from
# a digital certificate (.cer file)
set cert [new_CkCert]
set success [CkCert_LoadFromFile $cert "raul_publicKey.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
set rsa2 [new_CkRsa]
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
}
# Verify the signature against the original data:
CkRsa_put_EncodingMode $rsa2 "hex"
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 "Signature verified!"
# Verify with incorrect data:
set success [CkRsa_VerifyStringENC $rsa2 "something else" "sha256" $hexSig]
if {$success != 1} then {
puts "Signature not verified! (which was expected in this case)"
} else {
puts "Hmmm... that's not right..."
}
delete_CkPrivateKey $privKey
delete_CkRsa $rsa
delete_CkCert $cert
delete_CkPublicKey $pubKey
delete_CkRsa $rsa2