public void _04_ObjectParameterTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) { Assert.Inconclusive("Test cannot be executed on this platform"); } byte[] data = new byte[24]; System.Random rng = new Random(); rng.NextBytes(data); // Specify mechanism parameters CkKeyDerivationStringData parameter = new CkKeyDerivationStringData(data); // Create mechanism with the object as parameter Mechanism mechanism = new Mechanism(CKM.CKM_XOR_BASE_AND_DATA, parameter); Assert.IsTrue(mechanism.Type == (uint)CKM.CKM_XOR_BASE_AND_DATA); // We access private Mechanism member here just for the testing purposes Net.Pkcs11Interop.LowLevelAPI41.CK_MECHANISM ckMechanism = (Net.Pkcs11Interop.LowLevelAPI41.CK_MECHANISM) typeof(Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism); Assert.IsTrue(ckMechanism.Mechanism == (uint)CKM.CKM_XOR_BASE_AND_DATA); Assert.IsTrue(ckMechanism.Parameter != IntPtr.Zero); Assert.IsTrue(ckMechanism.ParameterLen == Net.Pkcs11Interop.Common.UnmanagedMemory.SizeOf(typeof(Net.Pkcs11Interop.LowLevelAPI41.MechanismParams.CK_KEY_DERIVATION_STRING_DATA))); }
public void _01_BasicDeriveKeyTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) { Assert.Inconclusive("Test cannot be executed on this platform"); } using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present Slot slot = Helpers.GetUsableSlot(pkcs11); // Open RW session using (Session session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate symetric key ObjectHandle baseKey = Helpers.GenerateKey(session); // Generate random data needed for key derivation byte[] data = session.GenerateRandom(24); // Specify mechanism parameters CkKeyDerivationStringData mechanismParams = new CkKeyDerivationStringData(data); // Specify derivation mechanism with parameters Mechanism mechanism = new Mechanism(CKM.CKM_XOR_BASE_AND_DATA, mechanismParams); // Derive key ObjectHandle derivedKey = session.DeriveKey(mechanism, baseKey, null); // Do something interesting with derived key Assert.IsTrue(derivedKey.ObjectId != CK.CK_INVALID_HANDLE); session.DestroyObject(baseKey); session.DestroyObject(derivedKey); session.Logout(); } } }
public void _04_ObjectParameterTest() { Helpers.CheckPlatform(); byte[] data = new byte[24]; System.Random rng = new Random(); rng.NextBytes(data); // Specify mechanism parameters CkKeyDerivationStringData parameter = new CkKeyDerivationStringData(data); // Create mechanism with the object as parameter Mechanism mechanism = new Mechanism(CKM.CKM_XOR_BASE_AND_DATA, parameter); Assert.IsTrue(mechanism.Type == NativeLongUtils.ConvertFromCKM(CKM.CKM_XOR_BASE_AND_DATA)); // We access private Mechanism member here just for the testing purposes CK_MECHANISM ckMechanism = (CK_MECHANISM)typeof(Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism); Assert.IsTrue(ckMechanism.Mechanism == NativeLongUtils.ConvertFromCKM(CKM.CKM_XOR_BASE_AND_DATA)); Assert.IsTrue(ckMechanism.Parameter != IntPtr.Zero); Assert.IsTrue(NativeLongUtils.ConvertToInt32(ckMechanism.ParameterLen) == UnmanagedMemory.SizeOf(typeof(CK_KEY_DERIVATION_STRING_DATA))); }
public void _01_BasicDeriveKeyTest() { using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking)) { // Find first slot with token present Slot slot = Helpers.GetUsableSlot(pkcs11); // Open RW session using (Session session = slot.OpenSession(false)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate symetric key ObjectHandle baseKey = Helpers.GenerateKey(session); // Generate random data needed for key derivation byte[] data = session.GenerateRandom(24); // Specify mechanism parameters CkKeyDerivationStringData mechanismParams = new CkKeyDerivationStringData(data); // Specify derivation mechanism with parameters Mechanism mechanism = new Mechanism(CKM.CKM_XOR_BASE_AND_DATA, mechanismParams); // Derive key ObjectHandle derivedKey = session.DeriveKey(mechanism, baseKey, null); // Do something interesting with derived key Assert.IsTrue(derivedKey.ObjectId != CK.CK_INVALID_HANDLE); session.DestroyObject(baseKey); session.DestroyObject(derivedKey); session.Logout(); } } }
static void Main(string[] args) { try { // Инициализировать библиотеку Console.WriteLine("Library initialization"); using (var pkcs11 = new Pkcs11(Settings.RutokenEcpDllDefaultPath, Settings.OsLockingDefault)) { // Получить доступный слот Console.WriteLine("Checking tokens available"); Slot slot = Helpers.GetUsableSlot(pkcs11); // Определение поддерживаемых токеном механизмов Console.WriteLine("Checking mechanisms available"); List <CKM> mechanisms = slot.GetMechanismList(); Errors.Check(" No mechanisms available", mechanisms.Count > 0); bool isGostR3410_12DeriveSupported = mechanisms.Contains((CKM)Extended_CKM.CKM_GOSTR3410_12_DERIVE); bool isGostWrapSupported = mechanisms.Contains((CKM)Extended_CKM.CKM_GOST28147_KEY_WRAP); Errors.Check(" CKM_GOSTR3410_12_DERIVE isn`t supported!", isGostR3410_12DeriveSupported); Errors.Check(" CKM_GOST28147_KEY_WRAP isn`t supported!", isGostWrapSupported); // Открыть RW сессию в первом доступном слоте Console.WriteLine("Opening RW session"); using (Session session = slot.OpenSession(false)) { // Выполнить аутентификацию Пользователя Console.WriteLine("User authentication"); session.Login(CKU.CKU_USER, SampleConstants.NormalUserPin); ObjectHandle sessionKeyHandle = null; ObjectHandle senderDerivedKeyHandle = null; ObjectHandle recipientDerivedKeyHandle = null; ObjectHandle unwrappedKeyHandle = null; try { // Генерация параметра для структуры типа CK_GOSTR3410_DERIVE_PARAMS // для выработки общего ключа Console.WriteLine("Preparing data for deriving and wrapping..."); byte[] ukm = session.GenerateRandom(SampleConstants.UkmLength); // Генерация значения сессионного ключа byte[] sessionKeyValue = session.GenerateRandom(SampleConstants.Gost28147_KeySize); Console.WriteLine(" Session key data is:"); Helpers.PrintByteArray(sessionKeyValue); Console.WriteLine("Preparing has been completed successfully"); // Выработка общего ключа на стороне отправителя Console.WriteLine("Deriving key on the sender's side..."); Derive_GostR3410_12_Key(session, SenderPrivateKeyAttributes, RecipientPublicKeyAttributes, ukm, out senderDerivedKeyHandle); Console.WriteLine("Key has been derived successfully"); // Маскировать сессионный ключ с помощью общего выработанного ключа // на стороне отправителя Console.WriteLine("Wrapping key..."); Console.WriteLine(" Creating the GOST 28147-89 key to wrap..."); // Выработка ключа, который будет замаскирован SessionKeyAttributes.Add(new ObjectAttribute(CKA.CKA_VALUE, sessionKeyValue)); sessionKeyHandle = session.CreateObject(SessionKeyAttributes); // Определение параметров механизма маскирования var wrapMechanismParams = new CkKeyDerivationStringData(ukm); var wrapMechanism = new Mechanism((uint)Extended_CKM.CKM_GOST28147_KEY_WRAP, wrapMechanismParams); // Маскирование ключа на общем ключе, выработанном на стороне отправителя byte[] wrappedKey = session.WrapKey(wrapMechanism, senderDerivedKeyHandle, sessionKeyHandle); Console.WriteLine(" Wrapped key data is:"); Helpers.PrintByteArray(wrappedKey); Console.WriteLine(" Key has been wrapped successfully"); // Выработка общего ключа на стороне получателя Console.WriteLine("Deriving key on the sender's side..."); Derive_GostR3410_12_Key(session, RecipientPrivateKeyAttributes, SenderPublicKeyAttributes, ukm, out recipientDerivedKeyHandle); Console.WriteLine("Key has been derived successfully"); // Демаскирование сессионного ключа с помощью общего выработанного // ключа на стороне получателя Console.WriteLine("Unwrapping key..."); unwrappedKeyHandle = session.UnwrapKey(wrapMechanism, recipientDerivedKeyHandle, wrappedKey, UnwrappedKeyAttributes); // Сравнение ключа // Получаем публичный ключ по его Id var attributes = new List <CKA> { CKA.CKA_VALUE }; List <ObjectAttribute> unwrappedKeyValueAttribute = session.GetAttributeValue(unwrappedKeyHandle, attributes); byte[] unwrappedKeyValue = unwrappedKeyValueAttribute[0].GetValueAsByteArray(); Console.WriteLine(" Unwrapped key data is:"); Helpers.PrintByteArray(unwrappedKeyValue); Console.WriteLine("Unwrapping has been completed successfully"); bool equal = (Convert.ToBase64String(sessionKeyValue) == Convert.ToBase64String(unwrappedKeyValue)); Errors.Check("Session and unwrapped keys are not equal!", equal); Console.WriteLine("Session and unwrapped keys are equal"); } finally { Console.WriteLine("Destroying keys"); // Удаляем сессионный ключ if (sessionKeyHandle != null) { session.DestroyObject(sessionKeyHandle); } // Удаляем наследованные ключи if (senderDerivedKeyHandle != null) { session.DestroyObject(senderDerivedKeyHandle); } if (recipientDerivedKeyHandle != null) { session.DestroyObject(recipientDerivedKeyHandle); } // Удаляем размаскированный ключ if (unwrappedKeyHandle != null) { session.DestroyObject(unwrappedKeyHandle); } // Сбросить права доступа как в случае исключения, // так и в случае успеха. // Сессия закрывается автоматически. session.Logout(); } } } } catch (Pkcs11Exception ex) { Console.WriteLine($"Operation failed [Method: {ex.Method}, RV: {ex.RV}]"); } catch (Exception ex) { Console.WriteLine($"Operation failed [Message: {ex.Message}]"); } }