public void _01_BasicInitTokenAndPinTest() { using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11Library); ITokenInfo tokenInfo = slot.GetTokenInfo(); // Check if token needs to be initialized if (!tokenInfo.TokenFlags.TokenInitialized) { // Initialize token and SO (security officer) pin slot.InitToken(Settings.SecurityOfficerPin, Settings.ApplicationName); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as SO (security officer) session.Login(CKU.CKU_SO, Settings.SecurityOfficerPin); // Initialize user pin session.InitPin(Settings.NormalUserPin); session.Logout(); } } } }
public void _01_GetAttributeValueTest() { using (IPkcs11 pkcs11 = Settings.Factories.Pkcs11Factory.CreatePkcs11(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Create object IObjectHandle objectHandle = Helpers.CreateDataObject(session); // Prepare list of empty attributes we want to read List <CKA> attributes = new List <CKA>(); attributes.Add(CKA.CKA_LABEL); attributes.Add(CKA.CKA_VALUE); // Get value of specified attributes List <IObjectAttribute> objectAttributes = session.GetAttributeValue(objectHandle, attributes); // Do something interesting with attribute value Assert.IsTrue(objectAttributes[0].GetValueAsString() == Settings.ApplicationName); session.DestroyObject(objectHandle); session.Logout(); } } }
/// <summary></summary> private void AddKeysToToken(ISlot Slot, PgpToken Token) { byte[] abExponent, abId, abModulus; bool isEncrypt, isVerify; ulong vKeyType; PgpKeyFlags.nFlags eKeyFlags; ISlotInfo SlotInfo; List <IObjectAttribute> ltAttributes, ltSearchTemplate; List <IObjectHandle> ltPublicKeys; if (Slot != null) { SlotInfo = Slot.GetSlotInfo(); using (ISession Session = Slot.OpenSession(SessionType.ReadOnly)) { ltSearchTemplate = new List <IObjectAttribute> { Session.Factories.ObjectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_PUBLIC_KEY) }; ltPublicKeys = Session.FindAllObjects(ltSearchTemplate); foreach (IObjectHandle PublicKey in ltPublicKeys) { ltAttributes = Session.GetAttributeValue(PublicKey, new List <CKA> { CKA.CKA_ENCRYPT, CKA.CKA_ID, CKA.CKA_KEY_TYPE, CKA.CKA_MODULUS, CKA.CKA_PUBLIC_EXPONENT, CKA.CKA_VERIFY }); isEncrypt = ltAttributes[0].GetValueAsBool(); abId = ltAttributes[1].GetValueAsByteArray(); vKeyType = ltAttributes[2].GetValueAsUlong(); abModulus = ltAttributes[3].GetValueAsByteArray(); abExponent = ltAttributes[4].GetValueAsByteArray(); isVerify = ltAttributes[5].GetValueAsBool(); if ((CKK)vKeyType == CKK.CKK_RSA) { if (!isEncrypt && isVerify) { eKeyFlags = PgpKeyFlags.nFlags.Certify | PgpKeyFlags.nFlags.Sign; } else if (isEncrypt && !isVerify) { eKeyFlags = PgpKeyFlags.nFlags.Encrypt; } else if (isEncrypt && isVerify) { eKeyFlags = PgpKeyFlags.nFlags.Authenticate; } else { eKeyFlags = PgpKeyFlags.nFlags.None; } Token.AddPublicKey(SlotInfo, abId, eKeyFlags, abModulus, abExponent); } } } } }
public void _03_DigestKeyTest() { using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11Library); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate symetric key IObjectHandle generatedKey = Helpers.GenerateKey(session); // Specify digesting mechanism IMechanism mechanism = Settings.Factories.MechanismFactory.Create(CKM.CKM_SHA_1); // Digest key byte[] digest = session.DigestKey(mechanism, generatedKey); // Do something interesting with digest value Assert.IsNotNull(digest); session.DestroyObject(generatedKey); session.Logout(); } } }
public void _02_DigestMultiPartTest() { using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11Library); // Open RO session using (ISession session = slot.OpenSession(SessionType.ReadOnly)) { // Specify digesting mechanism IMechanism mechanism = Settings.Factories.MechanismFactory.Create(CKM.CKM_SHA_1); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); byte[] digest = null; // Multipart digesting can be used i.e. for digesting of streamed data using (MemoryStream inputStream = new MemoryStream(sourceData)) { // Digest data digest = session.Digest(mechanism, inputStream); } // Do something interesting with digest value Assert.IsTrue(ConvertUtils.BytesToBase64String(digest) == "e1AsOh9IyGCa4hLN+2Od7jlnP14="); } } }
public void _01_CreateDestroyObjectTest() { using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11Library); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Prepare attribute template of new data object List <IObjectAttribute> objectAttributes = new List <IObjectAttribute>(); objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_DATA)); objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.Create(CKA.CKA_TOKEN, true)); objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.Create(CKA.CKA_APPLICATION, Settings.ApplicationName)); objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.Create(CKA.CKA_LABEL, Settings.ApplicationName)); objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.Create(CKA.CKA_VALUE, "Data object content")); // Create object IObjectHandle objectHandle = session.CreateObject(objectAttributes); // Do something interesting with new object // Destroy object session.DestroyObject(objectHandle); session.Logout(); } } }
public void _02_CopyObjectTest() { using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11Library); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Create object that can be copied IObjectHandle objectHandle = Helpers.CreateDataObject(session); // Copy object IObjectHandle copiedObjectHandle = session.CopyObject(objectHandle, null); // Do something interesting with new object session.DestroyObject(copiedObjectHandle); session.DestroyObject(objectHandle); session.Logout(); } } }
public void _01_GetFunctionStatusTest() { using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11Library); // Open RO (read-only) session using (ISession session = slot.OpenSession(SessionType.ReadOnly)) { // Legacy functions should always return CKR_FUNCTION_NOT_PARALLEL try { session.GetFunctionStatus(); } catch (Pkcs11Exception ex) { if (ex.RV != CKR.CKR_FUNCTION_NOT_PARALLEL) { throw; } } } } }
public void _03_GetObjectSizeTest() { using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11Library); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Create object IObjectHandle objectHandle = Helpers.CreateDataObject(session); // Determine object size ulong objectSize = session.GetObjectSize(objectHandle); // Do something interesting with object size Assert.IsTrue(objectSize > 0); session.DestroyObject(objectHandle); session.Logout(); } } }
public void _02_FindAllObjectsTest() { using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11Library); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Let's create two objects so we can find something IObjectHandle objectHandle1 = Helpers.CreateDataObject(session); IObjectHandle objectHandle2 = Helpers.CreateDataObject(session); // Prepare attribute template that defines search criteria List <IObjectAttribute> objectAttributes = new List <IObjectAttribute>(); objectAttributes.Add(session.Factories.ObjectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_DATA)); objectAttributes.Add(session.Factories.ObjectAttributeFactory.Create(CKA.CKA_TOKEN, true)); // Find all objects that match provided attributes List <IObjectHandle> foundObjects = session.FindAllObjects(objectAttributes); // Do something interesting with found objects Assert.IsTrue(foundObjects.Count >= 2); session.DestroyObject(objectHandle2); session.DestroyObject(objectHandle1); session.Logout(); } } }
public void _03_SetAttributeValueTest() { using (IPkcs11 pkcs11 = Settings.Factories.Pkcs11Factory.CreatePkcs11(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Create object IObjectHandle objectHandle = Helpers.CreateDataObject(session); // Prepare list of attributes we want to set List <IObjectAttribute> objectAttributes = new List <IObjectAttribute>(); objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_LABEL, Settings.ApplicationName + "_2")); objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_VALUE, "New data object content")); // Set attributes session.SetAttributeValue(objectHandle, objectAttributes); // Do something interesting with modified object session.DestroyObject(objectHandle); session.Logout(); } } }
public void _HL_20_01_EncryptAndDecrypt_Gost28147_89_ECB_Test() { using (var pkcs11 = Settings.Factories.RutokenPkcs11LibraryFactory.LoadRutokenPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate symetric key IObjectHandle generatedKey = Helpers.GenerateGost28147_89Key(session); var mechanism = Settings.Factories.MechanismFactory.Create(CKM.CKM_GOST28147_ECB); byte[] sourceData = TestData.Encrypt_Gost28147_89_ECB_SourceData; // Encrypt data byte[] encryptedData = session.Encrypt(mechanism, generatedKey, sourceData); // Decrypt data byte[] decryptedData = session.Decrypt(mechanism, generatedKey, encryptedData); Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData)); session.DestroyObject(generatedKey); session.Logout(); } } }
public void _01_GenerateKeyTest() { using (IPkcs11 pkcs11 = Settings.Factories.Pkcs11Factory.CreatePkcs11(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Prepare attribute template of new key List <IObjectAttribute> objectAttributes = new List <IObjectAttribute>(); objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY)); objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3)); objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_ENCRYPT, true)); objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_DECRYPT, true)); // Specify key generation mechanism IMechanism mechanism = Settings.Factories.MechanismFactory.CreateMechanism(CKM.CKM_DES3_KEY_GEN); // Generate key IObjectHandle objectHandle = session.GenerateKey(mechanism, objectAttributes); // Do something interesting with generated key // Destroy object session.DestroyObject(objectHandle); session.Logout(); } } }
public void _02_GenerateKeyPairTest() { using (IPkcs11 pkcs11 = Settings.Factories.Pkcs11Factory.CreatePkcs11(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // The CKA_ID attribute is intended as a means of distinguishing multiple key pairs held by the same subject byte[] ckaId = session.GenerateRandom(20); // Prepare attribute template of new public key List <IObjectAttribute> publicKeyAttributes = new List <IObjectAttribute>(); publicKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_TOKEN, true)); publicKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_PRIVATE, false)); publicKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_LABEL, Settings.ApplicationName)); publicKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_ID, ckaId)); publicKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_ENCRYPT, true)); publicKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_VERIFY, true)); publicKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_VERIFY_RECOVER, true)); publicKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_WRAP, true)); publicKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_MODULUS_BITS, 1024)); publicKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_PUBLIC_EXPONENT, new byte[] { 0x01, 0x00, 0x01 })); // Prepare attribute template of new private key List <IObjectAttribute> privateKeyAttributes = new List <IObjectAttribute>(); privateKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_TOKEN, true)); privateKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_PRIVATE, true)); privateKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_LABEL, Settings.ApplicationName)); privateKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_ID, ckaId)); privateKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_SENSITIVE, true)); privateKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_DECRYPT, true)); privateKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_SIGN, true)); privateKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_SIGN_RECOVER, true)); privateKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_UNWRAP, true)); // Specify key generation mechanism IMechanism mechanism = Settings.Factories.MechanismFactory.CreateMechanism(CKM.CKM_RSA_PKCS_KEY_PAIR_GEN); // Generate key pair IObjectHandle publicKeyHandle = null; IObjectHandle privateKeyHandle = null; session.GenerateKeyPair(mechanism, publicKeyAttributes, privateKeyAttributes, out publicKeyHandle, out privateKeyHandle); // Do something interesting with generated key pair // Destroy keys session.DestroyObject(privateKeyHandle); session.DestroyObject(publicKeyHandle); session.Logout(); } } }
public void _02_EncryptAndDecryptMultiPartTest() { using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11Library); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate symetric key IObjectHandle generatedKey = Helpers.GenerateKey(session); // Generate random initialization vector byte[] iv = session.GenerateRandom(8); // Specify encryption mechanism with initialization vector as parameter IMechanism mechanism = session.Factories.MechanismFactory.Create(CKM.CKM_DES3_CBC, iv); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password"); byte[] encryptedData = null; byte[] decryptedData = null; // Multipart encryption can be used i.e. for encryption of streamed data using (MemoryStream inputStream = new MemoryStream(sourceData), outputStream = new MemoryStream()) { // Encrypt data // Note that in real world application we would rather use bigger read buffer i.e. 4096 session.Encrypt(mechanism, generatedKey, inputStream, outputStream, 8); // Read whole output stream to the byte array so we can compare results more easily encryptedData = outputStream.ToArray(); } // Do something interesting with encrypted data // Multipart decryption can be used i.e. for decryption of streamed data using (MemoryStream inputStream = new MemoryStream(encryptedData), outputStream = new MemoryStream()) { // Decrypt data // Note that in real world application we would rather use bigger read buffer i.e. 4096 session.Decrypt(mechanism, generatedKey, inputStream, outputStream, 8); // Read whole output stream to the byte array so we can compare results more easily decryptedData = outputStream.ToArray(); } // Do something interesting with decrypted data Assert.IsTrue(ConvertUtils.BytesToBase64String(sourceData) == ConvertUtils.BytesToBase64String(decryptedData)); session.DestroyObject(generatedKey); session.Logout(); } } }
public void _01_BasicSignEncryptAndDecryptVerifyTest() { using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11Library); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate asymetric key pair IObjectHandle publicKey = null; IObjectHandle privateKey = null; Helpers.GenerateKeyPair(session, out publicKey, out privateKey); // Specify signing mechanism IMechanism signingMechanism = session.Factories.MechanismFactory.Create(CKM.CKM_SHA1_RSA_PKCS); // Generate symetric key IObjectHandle secretKey = Helpers.GenerateKey(session); // Generate random initialization vector byte[] iv = session.GenerateRandom(8); // Specify encryption mechanism with initialization vector as parameter IMechanism encryptionMechanism = session.Factories.MechanismFactory.Create(CKM.CKM_DES3_CBC, iv); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Passw0rd"); // Sign and encrypt data byte[] signature = null; byte[] encryptedData = null; session.SignEncrypt(signingMechanism, privateKey, encryptionMechanism, secretKey, sourceData, out signature, out encryptedData); // Do something interesting with signature and encrypted data // Decrypt data and verify signature of data byte[] decryptedData = null; bool isValid = false; session.DecryptVerify(signingMechanism, publicKey, encryptionMechanism, secretKey, encryptedData, signature, out decryptedData, out isValid); // Do something interesting with decrypted data and verification result Assert.IsTrue(ConvertUtils.BytesToBase64String(sourceData) == ConvertUtils.BytesToBase64String(decryptedData)); Assert.IsTrue(isValid); session.DestroyObject(privateKey); session.DestroyObject(publicKey); session.DestroyObject(secretKey); session.Logout(); } } }
public void _02_SignAndVerifyMultiPartTest() { using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11Library); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate key pair IObjectHandle publicKey = null; IObjectHandle privateKey = null; Helpers.GenerateKeyPair(session, out publicKey, out privateKey); // Specify signing mechanism IMechanism mechanism = session.Factories.MechanismFactory.Create(CKM.CKM_SHA1_RSA_PKCS); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); byte[] signature = null; bool isValid = false; // Multipart signing can be used i.e. for signing of streamed data using (MemoryStream inputStream = new MemoryStream(sourceData)) { // Sign data // Note that in real world application we would rather use bigger read buffer i.e. 4096 signature = session.Sign(mechanism, privateKey, inputStream, 8); } // Do something interesting with signature // Multipart verification can be used i.e. for signature verification of streamed data using (MemoryStream inputStream = new MemoryStream(sourceData)) { // Verify signature // Note that in real world application we would rather use bigger read buffer i.e. 4096 session.Verify(mechanism, publicKey, inputStream, signature, out isValid, 8); } // Do something interesting with verification result Assert.IsTrue(isValid); session.DestroyObject(privateKey); session.DestroyObject(publicKey); session.Logout(); } } }
public void _01_BasicWrapAndUnwrapKeyTest() { using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11Library); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate asymetric key pair IObjectHandle publicKey = null; IObjectHandle privateKey = null; Helpers.GenerateKeyPair(session, out publicKey, out privateKey); // Generate symetric key IObjectHandle secretKey = Helpers.GenerateKey(session); // Specify wrapping mechanism IMechanism mechanism = session.Factories.MechanismFactory.Create(CKM.CKM_RSA_PKCS); // Wrap key byte[] wrappedKey = session.WrapKey(mechanism, publicKey, secretKey); // Do something interesting with wrapped key Assert.IsNotNull(wrappedKey); // Define attributes for unwrapped key List <IObjectAttribute> objectAttributes = new List <IObjectAttribute>(); objectAttributes.Add(session.Factories.ObjectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY)); objectAttributes.Add(session.Factories.ObjectAttributeFactory.Create(CKA.CKA_KEY_TYPE, CKK.CKK_DES3)); objectAttributes.Add(session.Factories.ObjectAttributeFactory.Create(CKA.CKA_ENCRYPT, true)); objectAttributes.Add(session.Factories.ObjectAttributeFactory.Create(CKA.CKA_DECRYPT, true)); objectAttributes.Add(session.Factories.ObjectAttributeFactory.Create(CKA.CKA_DERIVE, true)); objectAttributes.Add(session.Factories.ObjectAttributeFactory.Create(CKA.CKA_EXTRACTABLE, true)); // Unwrap key IObjectHandle unwrappedKey = session.UnwrapKey(mechanism, privateKey, wrappedKey, objectAttributes); // Do something interesting with unwrapped key Assert.IsTrue(unwrappedKey.ObjectId != CK.CK_INVALID_HANDLE); session.DestroyObject(privateKey); session.DestroyObject(publicKey); session.DestroyObject(secretKey); session.Logout(); } } }
public ActionResult GetAllCerts() { Pkcs11InteropFactories factories = new Pkcs11InteropFactories(); using (IPkcs11Library pkcs11Library = factories.Pkcs11LibraryFactory.LoadPkcs11Library(factories, DllLibPath, AppType.MultiThreaded)) { ISlot slot = pkcs11Library.GetSlotList(SlotsType.WithTokenPresent).FirstOrDefault(); if (slot is null) { return(Ok("No slots found")); } ITokenInfo tokenInfo = slot.GetTokenInfo(); ISlotInfo slotInfo = slot.GetSlotInfo(); using (var session = slot.OpenSession(SessionType.ReadWrite)) { session.Login(CKU.CKU_USER, Encoding.UTF8.GetBytes(TokenPin)); var certificateSearchAttributes = new List <IObjectAttribute>() { session.Factories.ObjectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_CERTIFICATE), session.Factories.ObjectAttributeFactory.Create(CKA.CKA_TOKEN, true), session.Factories.ObjectAttributeFactory.Create(CKA.CKA_CERTIFICATE_TYPE, CKC.CKC_X_509) }; IObjectHandle certificate = session.FindAllObjects(certificateSearchAttributes).FirstOrDefault(); var certificateValue = session.GetAttributeValue(certificate, new List <CKA> { CKA.CKA_VALUE }); var xcert = new X509Certificate2(certificateValue[0].GetValueAsByteArray()); return(Ok( new { xcert.Thumbprint, xcert.Subject, xcert.IssuerName, hasKeyNull = xcert.PrivateKey is null }));
public void _06_ReadWriteSessionTest() { using (IPkcs11 pkcs11 = Settings.Factories.Pkcs11Factory.CreatePkcs11(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11); // Open RW (read-write) session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Do something interesting in RW session } } }
private static void InitializeToken(ISlot slot, string label, string soPin, string userPin) { if (slot.GetTokenInfo().TokenFlags.TokenInitialized) { throw new Exception("Token already initialized"); } slot.InitToken(soPin, label); using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { session.Login(CKU.CKU_SO, soPin); session.InitPin(userPin); } }
public void _05_ReadOnlySessionTest() { using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11Library); // Open RO (read-only) session using (ISession session = slot.OpenSession(SessionType.ReadOnly)) { // Do something interesting in RO session } } }
public void _02_UsingSessionTest() { using (IPkcs11 pkcs11 = Settings.Factories.Pkcs11Factory.CreatePkcs11(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11); // Session class can be used in using statement which defines a scope // at the end of which the session will be closed automatically. using (ISession session = slot.OpenSession(SessionType.ReadOnly)) { // Do something interesting in RO session } } }
public void _01_BasicDigestEncryptAndDecryptDigestTest() { using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11Library); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate symetric key IObjectHandle generatedKey = Helpers.GenerateKey(session); // Generate random initialization vector byte[] iv = session.GenerateRandom(8); // Specify encryption mechanism with initialization vector as parameter IMechanism encryptionMechanism = session.Factories.MechanismFactory.Create(CKM.CKM_DES3_CBC, iv); // Specify digesting mechanism IMechanism digestingMechanism = session.Factories.MechanismFactory.Create(CKM.CKM_SHA_1); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password"); // Encrypt and digest data byte[] digest1 = null; byte[] encryptedData = null; session.DigestEncrypt(digestingMechanism, encryptionMechanism, generatedKey, sourceData, out digest1, out encryptedData); // Do something interesting with encrypted data and digest // Decrypt and digest data byte[] digest2 = null; byte[] decryptedData = null; session.DecryptDigest(digestingMechanism, encryptionMechanism, generatedKey, encryptedData, out digest2, out decryptedData); // Do something interesting with decrypted data and digest Assert.IsTrue(ConvertUtils.BytesToBase64String(sourceData) == ConvertUtils.BytesToBase64String(decryptedData)); Assert.IsTrue(ConvertUtils.BytesToBase64String(digest1) == ConvertUtils.BytesToBase64String(digest2)); session.DestroyObject(generatedKey); session.Logout(); } } }
public void _03_EncryptAndDecryptSinglePartOaepTest() { using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11Library); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate key pair IObjectHandle publicKey = null; IObjectHandle privateKey = null; Helpers.GenerateKeyPair(session, out publicKey, out privateKey); // Specify mechanism parameters ICkRsaPkcsOaepParams mechanismParams = session.Factories.MechanismParamsFactory.CreateCkRsaPkcsOaepParams( ConvertUtils.UInt64FromCKM(CKM.CKM_SHA_1), ConvertUtils.UInt64FromCKG(CKG.CKG_MGF1_SHA1), ConvertUtils.UInt64FromUInt32(CKZ.CKZ_DATA_SPECIFIED), null ); // Specify encryption mechanism with parameters IMechanism mechanism = session.Factories.MechanismFactory.Create(CKM.CKM_RSA_PKCS_OAEP, mechanismParams); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); // Encrypt data byte[] encryptedData = session.Encrypt(mechanism, publicKey, sourceData); // Do something interesting with encrypted data // Decrypt data byte[] decryptedData = session.Decrypt(mechanism, privateKey, encryptedData); // Do something interesting with decrypted data Assert.IsTrue(ConvertUtils.BytesToBase64String(sourceData) == ConvertUtils.BytesToBase64String(decryptedData)); session.DestroyObject(privateKey); session.DestroyObject(publicKey); session.Logout(); } } }
public void _03_CloseSessionViaSlotTest() { using (IPkcs11 pkcs11 = Settings.Factories.Pkcs11Factory.CreatePkcs11(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11); // Open RO (read-only) session ISession session = slot.OpenSession(SessionType.ReadOnly); // Do something interesting in RO session // Alternatively session can be closed with CloseSession method of Slot class. slot.CloseSession(session); } }
public void _01_BasicSessionTest() { using (IPkcs11 pkcs11 = Settings.Factories.Pkcs11Factory.CreatePkcs11(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11); // Open RO (read-only) session ISession session = slot.OpenSession(SessionType.ReadOnly); // Do something interesting in RO session // Close session session.CloseSession(); } }
public void _04_CloseAllSessionsTest() { using (IPkcs11 pkcs11 = Settings.Factories.Pkcs11Factory.CreatePkcs11(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11); // Open RO (read-only) session ISession session = slot.OpenSession(SessionType.ReadOnly); // Do something interesting in RO session Assert.IsNotNull(session); // All sessions can be closed with CloseAllSessions method of Slot class. slot.CloseAllSessions(); } }
public void _02_GenerateRandomTest() { using (IPkcs11 pkcs11 = Settings.Factories.Pkcs11Factory.CreatePkcs11(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11); // Open RO (read-only) session using (ISession session = slot.OpenSession(SessionType.ReadOnly)) { // Get random or pseudo-random data byte[] randomData = session.GenerateRandom(256); // Do something interesting with random data Assert.IsTrue(randomData.Length == 256); } } }
public void _01_SeedRandomTest() { using (IPkcs11 pkcs11 = Settings.Factories.Pkcs11Factory.CreatePkcs11(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11); // Open RO (read-only) session using (ISession session = slot.OpenSession(SessionType.ReadOnly)) { // Mix additional seed material into the token's random number generator byte[] seed = ConvertUtils.Utf8StringToBytes("Additional seed material"); session.SeedRandom(seed); // Do something interesting with random number generator } } }