|
| 1 | +// Copyright 2024 Contributors to the Parsec project. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | +use cryptoki::context::{CInitializeArgs, Pkcs11}; |
| 4 | +use cryptoki::mechanism::Mechanism; |
| 5 | +use cryptoki::object::Attribute; |
| 6 | +use cryptoki::session::UserType; |
| 7 | +use cryptoki::types::AuthPin; |
| 8 | +use std::env; |
| 9 | + |
| 10 | +// The default user pin |
| 11 | +pub static USER_PIN: &str = "fedcba"; |
| 12 | +// The default SO pin |
| 13 | +pub static SO_PIN: &str = "abcdef"; |
| 14 | + |
| 15 | +fn main() -> testresult::TestResult { |
| 16 | + // initialize a new Pkcs11 object using the module from the env variable |
| 17 | + let pkcs11 = Pkcs11::new( |
| 18 | + env::var("PKCS11_SOFTHSM2_MODULE") |
| 19 | + .unwrap_or_else(|_| "/usr/local/lib/softhsm/libsofthsm2.so".to_string()), |
| 20 | + )?; |
| 21 | + |
| 22 | + pkcs11.initialize(CInitializeArgs::OsThreads)?; |
| 23 | + |
| 24 | + let slot = pkcs11.get_slots_with_token()?[0]; |
| 25 | + |
| 26 | + // initialize a test token |
| 27 | + let so_pin = AuthPin::new("abcdef".into()); |
| 28 | + pkcs11.init_token(slot, &so_pin, "Test Token")?; |
| 29 | + |
| 30 | + let user_pin = AuthPin::new("fedcba".into()); |
| 31 | + |
| 32 | + // initialize user PIN |
| 33 | + { |
| 34 | + let session = pkcs11.open_rw_session(slot)?; |
| 35 | + session.login(UserType::So, Some(&so_pin))?; |
| 36 | + session.init_pin(&user_pin)?; |
| 37 | + } |
| 38 | + |
| 39 | + // login as a user, the token has to be already initialized |
| 40 | + let session = pkcs11.open_rw_session(slot)?; |
| 41 | + session.login(UserType::User, Some(&user_pin))?; |
| 42 | + |
| 43 | + // template of the public key |
| 44 | + let pub_key_template = vec![ |
| 45 | + Attribute::Token(true), |
| 46 | + Attribute::Private(false), |
| 47 | + Attribute::PublicExponent(vec![0x01, 0x00, 0x01]), |
| 48 | + Attribute::ModulusBits(1024.into()), |
| 49 | + ]; |
| 50 | + |
| 51 | + let priv_key_template = vec![Attribute::Token(true)]; |
| 52 | + |
| 53 | + // generate an RSA key according to passed templates |
| 54 | + let (_public, _private) = session.generate_key_pair( |
| 55 | + &Mechanism::RsaPkcsKeyPairGen, |
| 56 | + &pub_key_template, |
| 57 | + &priv_key_template, |
| 58 | + )?; |
| 59 | + Ok(()) |
| 60 | +} |
0 commit comments