TclPKCS11

Artifact [cc7cb624cf]
Login

Artifact [cc7cb624cf]

Artifact cc7cb624cf0287689ccb0858997ed1d204b9718c250011794a4935e4da045194:


#! /usr/bin/env tclsh

lappend auto_path [file join [pwd] work lib]
lappend auto_path [file join [pwd] lib]

set pkcs11_module "/usr/local/lib/libcackey.so"
set pkcs11_module /home/rkeene/devel/cackey/libcackey.so
set pkcs11_module /home/rkeene/devel/saml-idp/archive/gcp-pkcs11.so

if {0} {
	set env(PKCS11SPY) $pkcs11_module
	set env(PKCS11SPY_OUTPUT) /dev/stderr
	set pkcs11_module /usr/lib/x86_64-linux-gnu/pkcs11/pkcs11-spy.so
}

load ./tclpkcs11.so Tclpkcs11

set handle [pki::pkcs11::loadmodule $pkcs11_module]
puts "Handle: $handle"

set slots [pki::pkcs11::listslots $handle]
puts "Slots: $slots"

foreach slotinfo $slots {
	set slotid [lindex $slotinfo 0]
	set slotlabel [lindex $slotinfo 1]
	set slotflags [lindex $slotinfo 2]

	if {[lsearch -exact $slotflags TOKEN_PRESENT] != -1} {
		if {![info exists token_slotid]} {
			set token_slotlabel $slotlabel
			set token_slotid $slotid
		}
	}
}

if {![info exists token_slotid]} {
	puts stderr "Found no slots with tokens, aborting."

	exit 1
}

set pubKeys [pki::pkcs11::listkeys $handle $token_slotid]
puts "Found [llength $pubKeys] keys"

set orig "TestMsg"
foreach keyinfo_list $pubKeys {
	unset -nocomplain keyinfo
	array set keyinfo $keyinfo_list
	puts "Key: $keyinfo(pkcs11_label)"

	set signature [pki::sign $orig $keyinfo_list sha256]
	set verify [pki::verify $signature $orig $keyinfo_list]

	puts "Signature valid: $verify"
}

set certs [pki::pkcs11::listcerts $handle $token_slotid]
puts "Found [llength $certs] certificates"

set orig "TestMsg"
foreach certinfo_list $certs {
	unset -nocomplain certinfo
	array set certinfo $certinfo_list
	puts "Cert: $certinfo(pkcs11_label) / $certinfo(subject)"

	set cipher [pki::encrypt -binary -pub -- $orig $certinfo_list]

	if {[catch {
		set plain  [pki::decrypt -binary -priv -- $cipher $certinfo_list]
	} err]} {
		if {$err == "PKCS11_ERROR USER_NOT_LOGGED_IN" || $err == "PKCS11_ERROR MAYBE_LOGIN"} {
			# Login and try it again...
			puts -nonewline " *** ENTER PIN: "
			flush stdout

			gets stdin password
			pki::pkcs11::login $handle $token_slotid $password

			set plain  [pki::decrypt -binary -priv -- $cipher $certinfo_list]
		} else {
			puts stderr "$::errorInfo"

			break
		}
	}

	if {$plain != $orig} {
		puts "Decryption error!  Expected \"$orig\", got \"$plain\""

		break
	}

	set cipher [pki::encrypt -binary -priv -- $orig $certinfo_list]
	set plain  [pki::decrypt -binary -pub -- $cipher $certinfo_list]

	set sig    [pki::sign $orig $certinfo_list]
	set verify [pki::verify $sig $orig $certinfo_list]

	if {!$verify} {
		puts "Signature verification error!"

		break
	}

	puts "OK"
}

pki::pkcs11::unloadmodule $handle