11// Copyright 2021 Contributors to the Parsec project.
22// SPDX-License-Identifier: Apache-2.0
3- use cryptoki:: context:: { CInitializeArgs , Pkcs11 } ;
3+ use cryptoki:: context:: { CInitializeArgs , Function , Pkcs11 } ;
4+ use cryptoki:: error:: { Error , RvError } ;
45use cryptoki:: session:: UserType ;
56use cryptoki:: slot:: Slot ;
67use cryptoki:: types:: AuthPin ;
@@ -11,6 +12,20 @@ pub static USER_PIN: &str = "fedcba";
1112// The default SO pin
1213pub static SO_PIN : & str = "abcdef" ;
1314
15+ fn get_token_label ( ) -> Option < String > {
16+ match env:: var ( "TEST_TOKEN_LABEL" ) {
17+ Ok ( s) => Some ( s) ,
18+ Err ( _) => None ,
19+ }
20+ }
21+
22+ fn skip_token_init ( ) -> bool {
23+ match env:: var ( "TEST_SKIP_TOKEN_INIT" ) {
24+ Ok ( s) => s == "1" ,
25+ Err ( _) => false ,
26+ }
27+ }
28+
1429fn get_pkcs11_path ( ) -> String {
1530 env:: var ( "TEST_PKCS11_MODULE" )
1631 . unwrap_or_else ( |_| "/usr/local/lib/softhsm/libsofthsm2.so" . to_string ( ) )
@@ -24,24 +39,41 @@ pub fn get_pkcs11() -> Pkcs11 {
2439 Pkcs11 :: new ( get_pkcs11_path ( ) ) . unwrap ( )
2540}
2641
42+ fn get_slot ( pkcs11 : & Pkcs11 ) -> Slot {
43+ // find a slot, get the first one or one with name specified in the environment variable
44+ let mut slots = pkcs11. get_slots_with_token ( ) . unwrap ( ) ;
45+ match get_token_label ( ) {
46+ None => return slots. remove ( 0 ) ,
47+ Some ( label) => {
48+ for s in slots {
49+ let ti = pkcs11. get_token_info ( s) . unwrap ( ) ;
50+ if ti. label ( ) == label {
51+ return s;
52+ }
53+ }
54+ panic ! ( "No token with Token Label `{label}` found" ) ;
55+ }
56+ } ;
57+ }
58+
2759pub fn init_pins ( ) -> ( Pkcs11 , Slot ) {
2860 let pkcs11 = get_pkcs11 ( ) ;
2961
3062 // initialize the library
3163 pkcs11. initialize ( CInitializeArgs :: OsThreads ) . unwrap ( ) ;
3264
33- // find a slot, get the first one
34- let slot = pkcs11. get_slots_with_token ( ) . unwrap ( ) . remove ( 0 ) ;
35-
36- let so_pin = AuthPin :: new ( SO_PIN . into ( ) ) ;
37- pkcs11. init_token ( slot, & so_pin, "Test Token" ) . unwrap ( ) ;
65+ let slot = get_slot ( & pkcs11) ;
3866
39- {
40- // open a session
41- let session = pkcs11. open_rw_session ( slot) . unwrap ( ) ;
42- // log in the session
43- session. login ( UserType :: So , Some ( & so_pin) ) . unwrap ( ) ;
44- session. init_pin ( & AuthPin :: new ( USER_PIN . into ( ) ) ) . unwrap ( ) ;
67+ if !skip_token_init ( ) {
68+ let so_pin = AuthPin :: new ( SO_PIN . into ( ) ) ;
69+ let res = pkcs11. init_token ( slot, & so_pin, "Test Token" ) ;
70+ {
71+ // open a session
72+ let session = pkcs11. open_rw_session ( slot) . unwrap ( ) ;
73+ // log in the session
74+ session. login ( UserType :: So , Some ( & so_pin) ) . unwrap ( ) ;
75+ session. init_pin ( & AuthPin :: new ( USER_PIN . into ( ) ) ) . unwrap ( ) ;
76+ }
4577 }
4678
4779 ( pkcs11, slot)
0 commit comments