Sample code for 30+ languages & platforms
Tcl

Yubikey RSA Encrypt/Decrypt

See more RSA Examples

Demonstrates how to do RSA decryption using a private key stored on a Yubikey (or other USB token or smartcard).

Note: RSA encryption uses the public key, which is freely exportable and does not need to occur on the token/smartcard.

Chilkat Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

# This example assumes you have a certificate with private key on the Yubikey token.
# When doing simple RSA encryption/decryption, we don't actually need the certificate,
# but we'll be using the private key associated with the certificate.
# 
# The sensitive/secret material that needs to be kept private is the private key.
# The certificate itself and the public key can be freely shared.
# 

# We're going to encrypt and decrypt 32-bytes of data.
set bd [new_CkBinData]

set success [CkBinData_AppendEncoded $bd "000102030405060708090A0B0C0D0E0F" "hex"]
set success [CkBinData_AppendEncoded $bd "000102030405060708090A0B0C0D0E0F" "hex"]

# Let's get the desired cert.
# For this example, a self-signed certificate with a 2048-bit RSA key was generated in slot 9A.
set cert [new_CkCert]

# Force Chilkat to use PKCS11 over ScMinidriver (if on Windows) and Apple Keychain (if on MacOS)
CkCert_put_UncommonOptions $cert "NoScMinidriver,NoAppleKeychain"

CkCert_put_SmartCardPin $cert "123456"

set success [CkCert_LoadFromSmartcard $cert "cn=chilkat_test_2048"]
if {$success == 0} then {
    puts [CkCert_lastErrorText $cert]
    delete_CkBinData $bd
    delete_CkCert $cert
    exit
}

# RSA encrypt using the public key.
set rsa [new_CkRsa]

# Provide the RSA object with the certificate on the Yubkey.
set success [CkRsa_SetX509Cert $rsa $cert 1]
if {$success == 0} then {
    puts [CkRsa_lastErrorText $rsa]
    delete_CkBinData $bd
    delete_CkCert $cert
    delete_CkRsa $rsa
    exit
}

# RSA encrypt using the public key.
set usePrivateKey 0
set success [CkRsa_EncryptBd $rsa $bd $usePrivateKey]
if {$success == 0} then {
    puts [CkRsa_lastErrorText $rsa]
    delete_CkBinData $bd
    delete_CkCert $cert
    delete_CkRsa $rsa
    exit
}

puts "RSA Encrypted Output in Hex:"
puts [CkBinData_getEncoded $bd hex]

# Now let's decrypt, using the private key on the Yubikey.
set usePrivateKey 1
set success [CkRsa_DecryptBd $rsa $bd $usePrivateKey]
if {$success == 0} then {
    puts [CkRsa_lastErrorText $rsa]
    delete_CkBinData $bd
    delete_CkCert $cert
    delete_CkRsa $rsa
    exit
}

puts "RSA Decrypted Output in Hex:"
puts [CkBinData_getEncoded $bd hex]

delete_CkBinData $bd
delete_CkCert $cert
delete_CkRsa $rsa