Sample code for 30+ languages & platforms
Tcl

Get the Public Key from a Private Key

See more Private Key Examples

Demonstrates the Chilkat PrivateKey.ToPublicKey method, which extracts the public portion of the loaded private key into an independent PublicKey object. The only argument is the PublicKey that receives the copy.

Note: The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.

Background: A key pair's public half is derived from the private half, and this is how you obtain it — the public key you distribute for others to verify signatures or encrypt to you, while the private key stays secret. The resulting PublicKey is an independent copy, so exporting or sharing it never risks exposing the private material. From there, export it as PEM, JWK, or XML as needed.

Chilkat Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

#  Load a private key to export.
set privKey [new_CkPrivateKey]

set success [CkPrivateKey_LoadPemFile $privKey "qa_data/private.pem"]
if {$success == 0} then {
    puts [CkPrivateKey_lastErrorText $privKey]
    delete_CkPrivateKey $privKey
    exit
}

#  Extract the public portion of the private key into an independent PublicKey object.  The
#  PublicKey is a separate copy, unaffected by later changes to the PrivateKey.
set pubKey [new_CkPublicKey]

set success [CkPrivateKey_ToPublicKey $privKey $pubKey]
if {$success == 0} then {
    puts [CkPrivateKey_lastErrorText $privKey]
    delete_CkPrivateKey $privKey
    delete_CkPublicKey $pubKey
    exit
}

#  The PublicKey can now be exported or shared -- for example as PEM.  The argument prefers the
#  traditional PKCS #1 PEM when a traditional representation exists.
set preferPkcs1 1
set pubPem [CkPublicKey_getPem $pubKey $preferPkcs1]
if {[CkPublicKey_get_LastMethodSuccess $pubKey] == 0} then {
    puts [CkPublicKey_lastErrorText $pubKey]
    delete_CkPrivateKey $privKey
    delete_CkPublicKey $pubKey
    exit
}

puts "$pubPem"

delete_CkPrivateKey $privKey
delete_CkPublicKey $pubKey