Exemplo n.º 1
0
        public void _02_GenerateKeyPairTest()
        {
            Helpers.CheckPlatform();

            CKR rv = CKR.CKR_OK;

            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
            {
                rv = pkcs11.C_Initialize(Settings.InitArgs80);
                if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
                {
                    Assert.Fail(rv.ToString());
                }

                // Find first slot with token present
                NativeULong slotId = Helpers.GetUsableSlot(pkcs11);

                NativeULong session = CK.CK_INVALID_HANDLE;
                rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Login as normal user
                rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt64FromInt32(Settings.NormalUserPinArray.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // The CKA_ID attribute is intended as a means of distinguishing multiple key pairs held by the same subject
                byte[] ckaId = new byte[20];
                rv = pkcs11.C_GenerateRandom(session, ckaId, ConvertUtils.UInt64FromInt32(ckaId.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Prepare attribute template of new public key
                CK_ATTRIBUTE[] pubKeyTemplate = new CK_ATTRIBUTE[10];
                pubKeyTemplate[0] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true);
                pubKeyTemplate[1] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, false);
                pubKeyTemplate[2] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName);
                pubKeyTemplate[3] = CkaUtils.CreateAttribute(CKA.CKA_ID, ckaId);
                pubKeyTemplate[4] = CkaUtils.CreateAttribute(CKA.CKA_ENCRYPT, true);
                pubKeyTemplate[5] = CkaUtils.CreateAttribute(CKA.CKA_VERIFY, true);
                pubKeyTemplate[6] = CkaUtils.CreateAttribute(CKA.CKA_VERIFY_RECOVER, true);
                pubKeyTemplate[7] = CkaUtils.CreateAttribute(CKA.CKA_WRAP, true);
                pubKeyTemplate[8] = CkaUtils.CreateAttribute(CKA.CKA_MODULUS_BITS, 1024);
                pubKeyTemplate[9] = CkaUtils.CreateAttribute(CKA.CKA_PUBLIC_EXPONENT, new byte[] { 0x01, 0x00, 0x01 });

                // Prepare attribute template of new private key
                CK_ATTRIBUTE[] privKeyTemplate = new CK_ATTRIBUTE[9];
                privKeyTemplate[0] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true);
                privKeyTemplate[1] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, true);
                privKeyTemplate[2] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName);
                privKeyTemplate[3] = CkaUtils.CreateAttribute(CKA.CKA_ID, ckaId);
                privKeyTemplate[4] = CkaUtils.CreateAttribute(CKA.CKA_SENSITIVE, true);
                privKeyTemplate[5] = CkaUtils.CreateAttribute(CKA.CKA_DECRYPT, true);
                privKeyTemplate[6] = CkaUtils.CreateAttribute(CKA.CKA_SIGN, true);
                privKeyTemplate[7] = CkaUtils.CreateAttribute(CKA.CKA_SIGN_RECOVER, true);
                privKeyTemplate[8] = CkaUtils.CreateAttribute(CKA.CKA_UNWRAP, true);

                // Specify key generation mechanism (needs no parameter => no unamanaged memory is needed)
                CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_RSA_PKCS_KEY_PAIR_GEN);

                // Generate key pair
                NativeULong pubKeyId  = CK.CK_INVALID_HANDLE;
                NativeULong privKeyId = CK.CK_INVALID_HANDLE;
                rv = pkcs11.C_GenerateKeyPair(session, ref mechanism, pubKeyTemplate, ConvertUtils.UInt64FromInt32(pubKeyTemplate.Length), privKeyTemplate, ConvertUtils.UInt64FromInt32(privKeyTemplate.Length), ref pubKeyId, ref privKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // In LowLevelAPI we have to free unmanaged memory taken by attributes
                for (int i = 0; i < privKeyTemplate.Length; i++)
                {
                    UnmanagedMemory.Free(ref privKeyTemplate[i].value);
                    privKeyTemplate[i].valueLen = 0;
                }

                for (int i = 0; i < pubKeyTemplate.Length; i++)
                {
                    UnmanagedMemory.Free(ref pubKeyTemplate[i].value);
                    pubKeyTemplate[i].valueLen = 0;
                }

                // Do something interesting with generated key pair

                // Destroy object
                rv = pkcs11.C_DestroyObject(session, privKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_DestroyObject(session, pubKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_Logout(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_CloseSession(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_Finalize(IntPtr.Zero);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }
            }
        }
Exemplo n.º 2
0
        public void _01_BasicDeriveKeyTest()
        {
            Helpers.CheckPlatform();

            CKR rv = CKR.CKR_OK;

            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
            {
                rv = pkcs11.C_Initialize(Settings.InitArgs40);
                if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
                {
                    Assert.Fail(rv.ToString());
                }

                // Find first slot with token present
                NativeULong slotId = Helpers.GetUsableSlot(pkcs11);

                // Open RW session
                NativeULong session = CK.CK_INVALID_HANDLE;
                rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Login as normal user
                rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, NativeLongUtils.ConvertFromInt32(Settings.NormalUserPinArray.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Generate symetric key
                NativeULong baseKeyId = CK.CK_INVALID_HANDLE;
                rv = Helpers.GenerateKey(pkcs11, session, ref baseKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Generate random data needed for key derivation
                byte[] data = new byte[24];
                rv = pkcs11.C_GenerateRandom(session, data, NativeLongUtils.ConvertFromInt32(data.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Specify mechanism parameters
                // Note that we are allocating unmanaged memory that will have to be freed later
                CK_KEY_DERIVATION_STRING_DATA mechanismParams = new CK_KEY_DERIVATION_STRING_DATA();
                mechanismParams.Data = UnmanagedMemory.Allocate(data.Length);
                UnmanagedMemory.Write(mechanismParams.Data, data);
                mechanismParams.Len = NativeLongUtils.ConvertFromInt32(data.Length);

                // Specify derivation mechanism with parameters
                // Note that CkmUtils.CreateMechanism() automaticaly copies mechanismParams into newly allocated unmanaged memory
                CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_XOR_BASE_AND_DATA, mechanismParams);

                // Derive key
                NativeULong derivedKey = CK.CK_INVALID_HANDLE;
                rv = pkcs11.C_DeriveKey(session, ref mechanism, baseKeyId, null, 0, ref derivedKey);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Do something interesting with derived key
                Assert.IsTrue(derivedKey != CK.CK_INVALID_HANDLE);

                // In LowLevelAPI we have to free all unmanaged memory we previously allocated
                UnmanagedMemory.Free(ref mechanismParams.Data);
                mechanismParams.Len = 0;

                // In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter
                UnmanagedMemory.Free(ref mechanism.Parameter);
                mechanism.ParameterLen = 0;

                rv = pkcs11.C_DestroyObject(session, baseKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_DestroyObject(session, derivedKey);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_Logout(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_CloseSession(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_Finalize(IntPtr.Zero);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }
            }
        }
Exemplo n.º 3
0
        public void _01_BasicDigestEncryptAndDecryptDigestTest()
        {
            Helpers.CheckPlatform();

            CKR rv = CKR.CKR_OK;

            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
            {
                rv = pkcs11.C_Initialize(Settings.InitArgs81);
                if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
                {
                    Assert.Fail(rv.ToString());
                }

                // Find first slot with token present
                NativeULong slotId = Helpers.GetUsableSlot(pkcs11);

                NativeULong session = CK.CK_INVALID_HANDLE;
                rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Login as normal user
                rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt64FromInt32(Settings.NormalUserPinArray.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Generate symetric key
                NativeULong keyId = CK.CK_INVALID_HANDLE;
                rv = Helpers.GenerateKey(pkcs11, session, ref keyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Generate random initialization vector
                byte[] iv = new byte[8];
                rv = pkcs11.C_GenerateRandom(session, iv, ConvertUtils.UInt64FromInt32(iv.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Specify encryption mechanism with initialization vector as parameter.
                // Note that CkmUtils.CreateMechanism() automaticaly copies iv into newly allocated unmanaged memory.
                CK_MECHANISM encryptionMechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_CBC, iv);

                // Specify digesting mechanism (needs no parameter => no unamanaged memory is needed)
                CK_MECHANISM digestingMechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA_1);

                byte[] sourceData    = ConvertUtils.Utf8StringToBytes("Our new password");
                byte[] encryptedData = null;
                byte[] digest1       = null;
                byte[] decryptedData = null;
                byte[] digest2       = null;

                // Multipart digesting and encryption function C_DigestEncryptUpdate can be used i.e. for digesting and encryption of streamed data
                using (MemoryStream inputStream = new MemoryStream(sourceData), outputStream = new MemoryStream())
                {
                    // Initialize digesting operation
                    rv = pkcs11.C_DigestInit(session, ref digestingMechanism);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }

                    // Initialize encryption operation
                    rv = pkcs11.C_EncryptInit(session, ref encryptionMechanism, keyId);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }

                    // Prepare buffer for source data part
                    // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
                    byte[] part = new byte[8];

                    // Prepare buffer for encrypted data part
                    // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
                    byte[]      encryptedPart    = new byte[8];
                    NativeULong encryptedPartLen = ConvertUtils.UInt64FromInt32(encryptedPart.Length);

                    // Read input stream with source data
                    int bytesRead = 0;
                    while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0)
                    {
                        // Process each individual source data part
                        encryptedPartLen = ConvertUtils.UInt64FromInt32(encryptedPart.Length);
                        rv = pkcs11.C_DigestEncryptUpdate(session, part, ConvertUtils.UInt64FromInt32(bytesRead), encryptedPart, ref encryptedPartLen);
                        if (rv != CKR.CKR_OK)
                        {
                            Assert.Fail(rv.ToString());
                        }

                        // Append encrypted data part to the output stream
                        outputStream.Write(encryptedPart, 0, ConvertUtils.UInt64ToInt32(encryptedPartLen));
                    }

                    // Get length of digest value in first call
                    NativeULong digestLen = 0;
                    rv = pkcs11.C_DigestFinal(session, null, ref digestLen);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }

                    Assert.IsTrue(digestLen > 0);

                    // Allocate array for digest value
                    digest1 = new byte[digestLen];

                    // Get digest value in second call
                    rv = pkcs11.C_DigestFinal(session, digest1, ref digestLen);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }

                    // Get the length of last encrypted data part in first call
                    byte[]      lastEncryptedPart    = null;
                    NativeULong lastEncryptedPartLen = 0;
                    rv = pkcs11.C_EncryptFinal(session, null, ref lastEncryptedPartLen);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }

                    // Allocate array for the last encrypted data part
                    lastEncryptedPart = new byte[lastEncryptedPartLen];

                    // Get the last encrypted data part in second call
                    rv = pkcs11.C_EncryptFinal(session, lastEncryptedPart, ref lastEncryptedPartLen);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }

                    // Append the last encrypted data part to the output stream
                    outputStream.Write(lastEncryptedPart, 0, ConvertUtils.UInt64ToInt32(lastEncryptedPartLen));

                    // Read whole output stream to the byte array so we can compare results more easily
                    encryptedData = outputStream.ToArray();
                }

                // Do something interesting with encrypted data and digest

                // Multipart decryption and digesting function C_DecryptDigestUpdate can be used i.e. for digesting and decryption of streamed data
                using (MemoryStream inputStream = new MemoryStream(encryptedData), outputStream = new MemoryStream())
                {
                    // Initialize decryption operation
                    rv = pkcs11.C_DecryptInit(session, ref encryptionMechanism, keyId);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }

                    // Initialize digesting operation
                    rv = pkcs11.C_DigestInit(session, ref digestingMechanism);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }

                    // Prepare buffer for encrypted data part
                    // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
                    byte[] encryptedPart = new byte[8];

                    // Prepare buffer for decrypted data part
                    // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
                    byte[]      part    = new byte[8];
                    NativeULong partLen = ConvertUtils.UInt64FromInt32(part.Length);

                    // Read input stream with encrypted data
                    int bytesRead = 0;
                    while ((bytesRead = inputStream.Read(encryptedPart, 0, encryptedPart.Length)) > 0)
                    {
                        // Process each individual encrypted data part
                        partLen = ConvertUtils.UInt64FromInt32(part.Length);
                        rv      = pkcs11.C_DecryptDigestUpdate(session, encryptedPart, ConvertUtils.UInt64FromInt32(bytesRead), part, ref partLen);
                        if (rv != CKR.CKR_OK)
                        {
                            Assert.Fail(rv.ToString());
                        }

                        // Append decrypted data part to the output stream
                        outputStream.Write(part, 0, ConvertUtils.UInt64ToInt32(partLen));
                    }

                    // Get the length of last decrypted data part in first call
                    byte[]      lastPart    = null;
                    NativeULong lastPartLen = 0;
                    rv = pkcs11.C_DecryptFinal(session, null, ref lastPartLen);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }

                    // Allocate array for the last decrypted data part
                    lastPart = new byte[lastPartLen];

                    // Get the last decrypted data part in second call
                    rv = pkcs11.C_DecryptFinal(session, lastPart, ref lastPartLen);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }

                    // Append the last decrypted data part to the output stream
                    outputStream.Write(lastPart, 0, ConvertUtils.UInt64ToInt32(lastPartLen));

                    // Read whole output stream to the byte array so we can compare results more easily
                    decryptedData = outputStream.ToArray();

                    // Get length of digest value in first call
                    NativeULong digestLen = 0;
                    rv = pkcs11.C_DigestFinal(session, null, ref digestLen);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }

                    Assert.IsTrue(digestLen > 0);

                    // Allocate array for digest value
                    digest2 = new byte[digestLen];

                    // Get digest value in second call
                    rv = pkcs11.C_DigestFinal(session, digest2, ref digestLen);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }
                }

                // Do something interesting with decrypted data and digest
                Assert.IsTrue(ConvertUtils.BytesToBase64String(sourceData) == ConvertUtils.BytesToBase64String(decryptedData));
                Assert.IsTrue(ConvertUtils.BytesToBase64String(digest1) == ConvertUtils.BytesToBase64String(digest2));

                // In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter (iv in this case)
                UnmanagedMemory.Free(ref encryptionMechanism.Parameter);
                encryptionMechanism.ParameterLen = 0;

                rv = pkcs11.C_DestroyObject(session, keyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_Logout(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_CloseSession(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_Finalize(IntPtr.Zero);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }
            }
        }
        public void _01_GetAttributeValueTest()
        {
            Helpers.CheckPlatform();

            CKR rv = CKR.CKR_OK;

            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
            {
                rv = pkcs11.C_Initialize(Settings.InitArgs80);
                if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
                {
                    Assert.Fail(rv.ToString());
                }

                // Find first slot with token present
                NativeULong slotId = Helpers.GetUsableSlot(pkcs11);

                NativeULong session = CK.CK_INVALID_HANDLE;
                rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Login as normal user
                rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt64FromInt32(Settings.NormalUserPinArray.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Create object
                NativeULong objectId = CK.CK_INVALID_HANDLE;
                rv = Helpers.CreateDataObject(pkcs11, session, ref objectId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Prepare list of empty attributes we want to read
                CK_ATTRIBUTE[] template = new CK_ATTRIBUTE[2];
                template[0] = CkaUtils.CreateAttribute(CKA.CKA_LABEL);
                template[1] = CkaUtils.CreateAttribute(CKA.CKA_VALUE);

                // Get size of each individual attribute value in first call
                rv = pkcs11.C_GetAttributeValue(session, objectId, template, ConvertUtils.UInt64FromInt32(template.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // In LowLevelAPI we have to allocate unmanaged memory for attribute value
                for (int i = 0; i < template.Length; i++)
                {
                    template[i].value = UnmanagedMemory.Allocate(ConvertUtils.UInt64ToInt32(template[i].valueLen));
                }

                // Get attribute value in second call
                rv = pkcs11.C_GetAttributeValue(session, objectId, template, ConvertUtils.UInt64FromInt32(template.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Do something interesting with attribute value
                byte[] ckaLabel = UnmanagedMemory.Read(template[0].value, ConvertUtils.UInt64ToInt32(template[0].valueLen));
                Assert.IsTrue(ConvertUtils.BytesToBase64String(ckaLabel) == ConvertUtils.BytesToBase64String(Settings.ApplicationNameArray));

                // In LowLevelAPI we have to free unmanaged memory taken by attributes
                for (int i = 0; i < template.Length; i++)
                {
                    UnmanagedMemory.Free(ref template[i].value);
                    template[i].valueLen = 0;
                }

                rv = pkcs11.C_DestroyObject(session, objectId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_Logout(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_CloseSession(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_Finalize(IntPtr.Zero);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }
            }
        }
Exemplo n.º 5
0
        public void _01_EncryptAndDecryptSinglePartTest()
        {
            Helpers.CheckPlatform();

            CKR rv = CKR.CKR_OK;

            using (Pkcs11Library pkcs11Library = new Pkcs11Library(Settings.Pkcs11LibraryPath))
            {
                rv = pkcs11Library.C_Initialize(Settings.InitArgs41);
                if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
                {
                    Assert.Fail(rv.ToString());
                }

                // Find first slot with token present
                NativeULong slotId = Helpers.GetUsableSlot(pkcs11Library);

                NativeULong session = CK.CK_INVALID_HANDLE;
                rv = pkcs11Library.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Login as normal user
                rv = pkcs11Library.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt32FromInt32(Settings.NormalUserPinArray.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Generate symetric key
                NativeULong keyId = CK.CK_INVALID_HANDLE;
                rv = Helpers.GenerateKey(pkcs11Library, session, ref keyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Generate random initialization vector
                byte[] iv = new byte[8];
                rv = pkcs11Library.C_GenerateRandom(session, iv, ConvertUtils.UInt32FromInt32(iv.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Specify encryption mechanism with initialization vector as parameter.
                // Note that CkmUtils.CreateMechanism() automaticaly copies iv into newly allocated unmanaged memory.
                CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_CBC, iv);

                // Initialize encryption operation
                rv = pkcs11Library.C_EncryptInit(session, ref mechanism, keyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password");

                // Get length of encrypted data in first call
                NativeULong encryptedDataLen = 0;
                rv = pkcs11Library.C_Encrypt(session, sourceData, ConvertUtils.UInt32FromInt32(sourceData.Length), null, ref encryptedDataLen);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                Assert.IsTrue(encryptedDataLen > 0);

                // Allocate array for encrypted data
                byte[] encryptedData = new byte[encryptedDataLen];

                // Get encrypted data in second call
                rv = pkcs11Library.C_Encrypt(session, sourceData, ConvertUtils.UInt32FromInt32(sourceData.Length), encryptedData, ref encryptedDataLen);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Do something interesting with encrypted data

                // Initialize decryption operation
                rv = pkcs11Library.C_DecryptInit(session, ref mechanism, keyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Get length of decrypted data in first call
                NativeULong decryptedDataLen = 0;
                rv = pkcs11Library.C_Decrypt(session, encryptedData, ConvertUtils.UInt32FromInt32(encryptedData.Length), null, ref decryptedDataLen);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                Assert.IsTrue(decryptedDataLen > 0);

                // Allocate array for decrypted data
                byte[] decryptedData = new byte[decryptedDataLen];

                // Get decrypted data in second call
                rv = pkcs11Library.C_Decrypt(session, encryptedData, ConvertUtils.UInt32FromInt32(encryptedData.Length), decryptedData, ref decryptedDataLen);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Do something interesting with decrypted data
                Assert.IsTrue(ConvertUtils.BytesToBase64String(sourceData) == ConvertUtils.BytesToBase64String(decryptedData));

                // In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter (iv in this case)
                UnmanagedMemory.Free(ref mechanism.Parameter);
                mechanism.ParameterLen = 0;

                rv = pkcs11Library.C_DestroyObject(session, keyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11Library.C_Logout(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11Library.C_CloseSession(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11Library.C_Finalize(IntPtr.Zero);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }
            }
        }
Exemplo n.º 6
0
        public void _01_CreateDestroyObjectTest()
        {
            Helpers.CheckPlatform();

            CKR rv = CKR.CKR_OK;

            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
            {
                rv = pkcs11.C_Initialize(Settings.InitArgs81);
                if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
                {
                    Assert.Fail(rv.ToString());
                }

                // Find first slot with token present
                NativeULong slotId = Helpers.GetUsableSlot(pkcs11);

                NativeULong session = CK.CK_INVALID_HANDLE;
                rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Login as normal user
                rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt64FromInt32(Settings.NormalUserPinArray.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Prepare attribute template of new data object
                CK_ATTRIBUTE[] template = new CK_ATTRIBUTE[5];
                template[0] = CkaUtils.CreateAttribute(CKA.CKA_CLASS, CKO.CKO_DATA);
                template[1] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true);
                template[2] = CkaUtils.CreateAttribute(CKA.CKA_APPLICATION, Settings.ApplicationName);
                template[3] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName);
                template[4] = CkaUtils.CreateAttribute(CKA.CKA_VALUE, "Data object content");

                // Create object
                NativeULong objectId = CK.CK_INVALID_HANDLE;
                rv = pkcs11.C_CreateObject(session, template, ConvertUtils.UInt64FromInt32(template.Length), ref objectId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // In LowLevelAPI we have to free unmanaged memory taken by attributes
                for (int i = 0; i < template.Length; i++)
                {
                    UnmanagedMemory.Free(ref template[i].value);
                    template[i].valueLen = 0;
                }

                // Do something interesting with new object

                // Destroy object
                rv = pkcs11.C_DestroyObject(session, objectId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_Logout(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_CloseSession(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_Finalize(IntPtr.Zero);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }
            }
        }
Exemplo n.º 7
0
        public void _07_AttributeArrayAttributeTest()
        {
            Helpers.CheckPlatform();

            CK_ATTRIBUTE[] originalValue = new CK_ATTRIBUTE[2];
            originalValue[0] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true);
            originalValue[1] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, true);
            // Create attribute with attribute array value
            CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue);

            Assert.IsTrue(attr.type == ConvertUtils.UInt32FromCKA(CKA.CKA_WRAP_TEMPLATE));
            Assert.IsTrue(attr.value != IntPtr.Zero);
            Assert.IsTrue(attr.valueLen == ConvertUtils.UInt32FromInt32(UnmanagedMemory.SizeOf(typeof(CK_ATTRIBUTE)) * originalValue.Length));

            CK_ATTRIBUTE[] recoveredValue = null;
            // Read the value of attribute
            CkaUtils.ConvertValue(ref attr, out recoveredValue);
            Assert.IsTrue(originalValue.Length == recoveredValue.Length);
            for (int i = 0; i < recoveredValue.Length; i++)
            {
                Assert.IsTrue(originalValue[i].type == recoveredValue[i].type);
                Assert.IsTrue(originalValue[i].valueLen == recoveredValue[i].valueLen);

                bool originalBool = false;
                // Read the value of nested attribute
                CkaUtils.ConvertValue(ref originalValue[i], out originalBool);

                bool recoveredBool = true;
                // Read the value of nested attribute
                CkaUtils.ConvertValue(ref recoveredValue[i], out recoveredBool);
                Assert.IsTrue(originalBool == recoveredBool);

                // In this example there is the same pointer to unmanaged memory
                // in both originalValue and recoveredValue array therefore it
                // needs to be freed only once.
                Assert.IsTrue(originalValue[i].value == recoveredValue[i].value);
                // Free value of nested attributes
                UnmanagedMemory.Free(ref originalValue[i].value);
                originalValue[i].valueLen  = 0;
                recoveredValue[i].value    = IntPtr.Zero;
                recoveredValue[i].valueLen = 0;
            }

            // Free attribute value
            UnmanagedMemory.Free(ref attr.value);
            attr.valueLen = 0;
            Assert.IsTrue(attr.type == ConvertUtils.UInt32FromCKA(CKA.CKA_WRAP_TEMPLATE));
            Assert.IsTrue(attr.value == IntPtr.Zero);
            Assert.IsTrue(attr.valueLen == 0);

            // Create attribute with null attribute array value
            attr = CkaUtils.CreateAttribute(CKA.CKA_WRAP_TEMPLATE, (CK_ATTRIBUTE[])null);
            Assert.IsTrue(attr.type == ConvertUtils.UInt32FromCKA(CKA.CKA_WRAP_TEMPLATE));
            Assert.IsTrue(attr.value == IntPtr.Zero);
            Assert.IsTrue(attr.valueLen == 0);

            // Create attribute with empty attribute array value
            attr = CkaUtils.CreateAttribute(CKA.CKA_WRAP_TEMPLATE, new CK_ATTRIBUTE[0]);
            Assert.IsTrue(attr.type == ConvertUtils.UInt32FromCKA(CKA.CKA_WRAP_TEMPLATE));
            Assert.IsTrue(attr.value == IntPtr.Zero);
            Assert.IsTrue(attr.valueLen == 0);
        }
Exemplo n.º 8
0
 /// <summary>
 /// Set memory of depths array to a given value.
 /// </summary>
 public void SetDepthsMemory(byte value)
 {
     UnmanagedMemory.SetMemory(_depthPtr.Ptr, _nodesCount, 0);
 }
Exemplo n.º 9
0
 /// <summary>
 /// Set memory of nodes array to a given value.
 /// </summary>
 public void SetNodesMemory(byte value)
 {
     UnmanagedMemory.SetMemory(_nodesPtr.Ptr, _nodesByteSize, 0);
 }
Exemplo n.º 10
0
 public PushDataContainer(ShaderStages stages, Logger logger = null, long maxByteSize = 128)
 {
     this.stages = stages;
     memory      = new UnmanagedMemory(maxByteSize, logger);
 }
Exemplo n.º 11
0
        public static void Run()
        {
            //Buffer<char>
            Console.WriteLine("Buffer<char>");
            var c1 = Buffer <char> .Create(1);

            //Buffer<char>.Create(ArrayPool<char>.Shared, 1024, out var disposable);
            //StringExtensions.ThreadRent(out var disposable); ThreadStatic
            //StringExtensions.Rent(out var disposable);
            //StringContent.Rent(out var disposable) http

            c1.Write('A');
            c1.Write("This is a String!!!");
            c1.Write(byte.MaxValue);
            c1.Write(short.MaxValue);
            c1.Write(int.MaxValue);
            c1.Write(long.MaxValue);
            c1.Write(DateTime.Now, "yyyy-MM-dd HH:mm:ss");

            var span1 = c1.GetSpan();

            span1[0] = 'X';
            c1.Advance(1);
            var span2 = c1.GetSpan(32);

            Guid.NewGuid().TryFormat(span2, out var charsWritten, "N");
            c1.Advance(charsWritten);


            var bytes1 = Encoding.UTF8.GetBytes("My name is 张贺");

            c1.WriteBytes(bytes1, Encoding.UTF8);
            //c1.WriteBytes(ReadOnlySequence<byte>, Encoding.UTF8)

            var decoder = Encoding.UTF8.GetDecoder();

            c1.WriteBytes(bytes1.AsSpan(0, 2), false, decoder);
            c1.WriteBytes(bytes1.AsSpan(2, 3), false, decoder);
            c1.WriteBytes(bytes1.AsSpan(5), true, decoder);
            //c1.WriteBytes(byte*, bool, decoder)

            var tempSeq1  = c1.Sequence;//ReadOnlySequence<char>
            var tempSpan1 = tempSeq1.IsSingleSegment ? tempSeq1.First.Span : tempSeq1.ToArray();

            Console.WriteLine(Encoding.UTF8.GetByteCount(tempSeq1));
            byte[] byteArray = Encoding.UTF8.GetBytes(tempSeq1);
            Console.WriteLine(c1.ToString());

            //------------------------------------------------------------------------

            //Buffer<byte>
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Buffer<byte>");
            var b1 = Buffer <byte> .Create(1);

            //Buffer<byte>.Create(ArrayPool<byte>.Shared, 1024, out var disposable);
            //MemoryContent.Rent(out var disposable) http

            b1.Write((byte)'A');
            b1.Write(Encoding.UTF8.GetBytes("This is a String!!!"));

            var span3 = b1.GetSpan();

            span3[0] = (byte)'X';
            b1.Advance(1);
            //var result = (stream,content...).ReadAsync(b1.GetSpan());
            //b1.Advance(result);
            //var result = await (stream, content...).ReadAsync(b1.GetMemory());
            //b1.Advance(result);


            b1.WriteChars("My name is 张贺", Encoding.UTF8);
            //b1.WriteChars(ReadOnlySequence<char>, Encoding.UTF8)

            var encoder = Encoding.UTF8.GetEncoder();

            b1.WriteChars("My", false, encoder);
            b1.WriteChars(" name is ", false, encoder);
            b1.WriteChars("张贺", true, encoder);
            //b1.WriteChars(char*, bool, encoder)


            var tempSeq2  = b1.Sequence;//ReadOnlySequence<byte>
            var tempSpan2 = tempSeq2.IsSingleSegment ? tempSeq2.First.Span : tempSeq2.ToArray();

            Console.WriteLine(Encoding.UTF8.GetCharCount(tempSeq2));
            Console.WriteLine(Encoding.UTF8.GetString(tempSeq2));

            //------------------------------------------------------------------------

            //BufferExtensions.SizeOf<T>()
            Console.WriteLine($"{sizeof(byte)}={BufferExtensions.SizeOf<byte>()}");
            Console.WriteLine($"{sizeof(sbyte)}={BufferExtensions.SizeOf<sbyte>()}");
            Console.WriteLine($"{sizeof(short)}={BufferExtensions.SizeOf<short>()}");
            Console.WriteLine($"{sizeof(ushort)}={BufferExtensions.SizeOf<ushort>()}");
            Console.WriteLine($"{sizeof(int)}={BufferExtensions.SizeOf<int>()}");
            Console.WriteLine($"{sizeof(uint)}={BufferExtensions.SizeOf<uint>()}");
            Console.WriteLine($"{sizeof(long)}={BufferExtensions.SizeOf<long>()}");
            Console.WriteLine($"{sizeof(ulong)}={BufferExtensions.SizeOf<ulong>()}");
            Console.WriteLine($"{sizeof(float)}={BufferExtensions.SizeOf<float>()}");
            Console.WriteLine($"{sizeof(double)}={BufferExtensions.SizeOf<double>()}");
            Console.WriteLine($"{sizeof(decimal)}={BufferExtensions.SizeOf<decimal>()}");
            unsafe
            {
                Console.WriteLine($"{sizeof(DateTime)}={BufferExtensions.SizeOf<DateTime>()}");
                Console.WriteLine($"{sizeof(DateTimeOffset)}={BufferExtensions.SizeOf<DateTimeOffset>()}");
            }

            //------------------------------------------------------------------------

            //AsWriter()
            var sb = Buffer <char> .Create(1);

            var writer = sb.AsWriter(); //TextWriter

            writer.Write("ABC");
            writer.Write(int.MaxValue);
            writer.Write(long.MaxValue);
            writer.Write("EFG");
            Console.WriteLine(sb.ToString());

            //------------------------------------------------------------------------
            //UnmanagedMemory<T>

            //Marshal.AllocHGlobal
            var um1 = new UnmanagedMemory <char>(10);

            unsafe
            {
                char *dataPtr = um1.DataPtr;
                Console.WriteLine(new IntPtr(dataPtr));
            }
            var um1Span   = um1.GetSpan();
            var um1Length = um1.Length;

            for (int i = 0; i < um1Length; i++)
            {
                um1Span[i] = 'A';
            }
            Console.WriteLine(new string(um1.GetSpan()));
            um1.Dispose();

            var um2 = new UnmanagedMemory <byte>(9);

            //um2.GetSpan().Clear();
            //um2.GetSpan().Fill(0);
            for (int i = 0; i < um2.Length; i++)//not zero
            {
                Console.WriteLine(um2.GetSpan()[i]);
            }
            Encoding.ASCII.GetBytes("123456789", um2.GetSpan());
            Console.WriteLine(Encoding.ASCII.GetString(um2.GetSpan()));
            um2.Dispose();

            //pointer
            UnmanagedMemory <byte> um3;

            unsafe
            {
                var stackPtr1 = stackalloc byte[10];//byte*
                um3 = new UnmanagedMemory <byte>(stackPtr1, 10);
            }
            Task.Run(async() =>
            {
                var testStream = Stream.Null;
                await testStream.ReadAsync(um3.Memory);
            }).Wait();
            um3.Dispose();
        }
Exemplo n.º 12
0
        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)));
        }
Exemplo n.º 13
0
        public bool ReadOneTransaction(StorageEnvironmentOptions options, bool checkCrc = true)
        {
            if (_readingPage >= _pager.NumberOfAllocatedPages)
            {
                return(false);
            }

            if (MaxPageToRead != null && _readingPage >= MaxPageToRead.Value)
            {
                return(false);
            }

            TransactionHeader *current;

            if (!TryReadAndValidateHeader(options, out current))
            {
                return(false);
            }

            // Uncompressed transactions will respect boundaries between the TransactionHeader page and the data, so we move to the data page.
            if (current->Compressed == false)
            {
                _readingPage++;
            }

            var transactionSize = GetNumberOfPagesFromSize(options, current->Compressed ? current->CompressedSize + sizeof(TransactionHeader) : current->UncompressedSize);

            if (current->TransactionId <= _lastSyncedTransactionId)
            {
                LastTransactionHeader = current;
                _readingPage         += transactionSize;
                return(true); // skipping
            }

            if (checkCrc && !ValidatePagesHash(options, current))
            {
                return(false);
            }

            byte *outputPage;

            if (current->Compressed)
            {
                _recoveryPager.EnsureContinuous(_recoveryPage, (current->PageCount + current->OverflowPageCount));
                outputPage = _recoveryPager.AcquirePagePointer(null, _recoveryPage);
                UnmanagedMemory.Set(outputPage, 0, (current->PageCount + current->OverflowPageCount) * options.PageSize);

                // Compressed transactions will put the TransactionHeader in the same page of the data.
                if (TryDecompressTransactionPages(options, current, outputPage) == false)
                {
                    return(false);
                }
            }
            else
            {
                _recoveryPager.EnsureContinuous(_recoveryPage, (current->PageCount + current->OverflowPageCount) + 1);
                outputPage = _recoveryPager.AcquirePagePointer(null, _recoveryPage);
                UnmanagedMemory.Set(outputPage, 0, (current->PageCount + current->OverflowPageCount) * options.PageSize);

                Memory.Copy(outputPage, _pager.AcquirePagePointer(null, _readingPage), (current->PageCount + current->OverflowPageCount) * options.PageSize);
            }

            var tempTransactionPageTranslaction = new Dictionary <long, RecoveryPagePosition>();

            for (var i = 0; i < current->PageCount; i++)
            {
                Debug.Assert(_pager.Disposed == false);
                Debug.Assert(_recoveryPager.Disposed == false);

                var page = _recoveryPager.Read(null, _recoveryPage);

                var pagePosition = new RecoveryPagePosition
                {
                    JournalPos    = _recoveryPage,
                    TransactionId = current->TransactionId
                };

                if (page.IsOverflow)
                {
                    var numOfPages = _recoveryPager.GetNumberOfOverflowPages(page.OverflowSize);

                    pagePosition.IsOverflow            = true;
                    pagePosition.NumberOfOverflowPages = numOfPages;

                    _recoveryPage += numOfPages;
                }
                else
                {
                    _recoveryPage++;
                }

                tempTransactionPageTranslaction[page.PageNumber] = pagePosition;
            }

            _readingPage += transactionSize;

            LastTransactionHeader = current;

            foreach (var pagePosition in tempTransactionPageTranslaction)
            {
                _transactionPageTranslation[pagePosition.Key] = pagePosition.Value;

                if (pagePosition.Value.IsOverflow)
                {
                    Debug.Assert(pagePosition.Value.NumberOfOverflowPages != -1);

                    for (int i = 1; i < pagePosition.Value.NumberOfOverflowPages; i++)
                    {
                        _transactionPageTranslation.Remove(pagePosition.Key + i);
                    }
                }
            }

            return(true);
        }
        /// <summary>
        /// Obtains a list of managed struct sizes.
        /// </summary>
        /// <returns>List of managed struct sizes</returns>
        private List <ulong> GetManagedStructSizeList()
        {
            List <ulong> sizeList = new List <ulong>();

            if (Platform.UnmanagedLongSize == 4)
            {
                if (Platform.StructPackingSize == 0)
                {
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.CK_ATTRIBUTE))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.CK_C_INITIALIZE_ARGS))));
#if COREFX
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.CK_INFO).GetTypeInfo().Assembly.GetType("Net.Pkcs11Interop.LowLevelAPI40.CK_FUNCTION_LIST"))));
#else
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.CK_INFO).Assembly.GetType("Net.Pkcs11Interop.LowLevelAPI40.CK_FUNCTION_LIST"))));
#endif
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.CK_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.CK_MECHANISM))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.CK_MECHANISM_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.CK_SESSION_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.CK_SLOT_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.CK_TOKEN_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.CK_VERSION))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_AES_CBC_ENCRYPT_DATA_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_AES_CTR_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_ARIA_CBC_ENCRYPT_DATA_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_CAMELLIA_CTR_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_CMS_SIG_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_DES_CBC_ENCRYPT_DATA_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_ECDH1_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_ECDH2_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_ECMQV_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_EXTRACT_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_KEA_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_KEY_DERIVATION_STRING_DATA))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_KEY_WRAP_SET_OAEP_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_KIP_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_MAC_GENERAL_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_OTP_PARAM))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_OTP_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_OTP_SIGNATURE_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_PBE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_PKCS5_PBKD2_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_RC2_CBC_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_RC2_MAC_GENERAL_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_RC2_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_RC5_CBC_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_RC5_MAC_GENERAL_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_RC5_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_RSA_PKCS_OAEP_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_RSA_PKCS_PSS_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_SKIPJACK_PRIVATE_WRAP_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_SKIPJACK_RELAYX_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_SSL3_KEY_MAT_OUT))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_SSL3_KEY_MAT_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_SSL3_MASTER_KEY_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_SSL3_RANDOM_DATA))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_TLS_PRF_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_WTLS_KEY_MAT_OUT))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_WTLS_KEY_MAT_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_WTLS_MASTER_KEY_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_WTLS_PRF_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_WTLS_RANDOM_DATA))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_X9_42_DH1_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_X9_42_DH2_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_X9_42_MQV_DERIVE_PARAMS))));
                }
                else
                {
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.CK_ATTRIBUTE))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.CK_C_INITIALIZE_ARGS))));
#if COREFX
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.CK_INFO).GetTypeInfo().Assembly.GetType("Net.Pkcs11Interop.LowLevelAPI41.CK_FUNCTION_LIST"))));
#else
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.CK_INFO).Assembly.GetType("Net.Pkcs11Interop.LowLevelAPI41.CK_FUNCTION_LIST"))));
#endif
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.CK_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.CK_MECHANISM))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.CK_MECHANISM_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.CK_SESSION_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.CK_SLOT_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.CK_TOKEN_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.CK_VERSION))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_AES_CBC_ENCRYPT_DATA_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_AES_CTR_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_ARIA_CBC_ENCRYPT_DATA_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_CAMELLIA_CTR_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_CMS_SIG_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_DES_CBC_ENCRYPT_DATA_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_ECDH1_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_ECDH2_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_ECMQV_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_EXTRACT_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_KEA_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_KEY_DERIVATION_STRING_DATA))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_KEY_WRAP_SET_OAEP_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_KIP_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_MAC_GENERAL_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_OTP_PARAM))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_OTP_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_OTP_SIGNATURE_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_PBE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_PKCS5_PBKD2_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_RC2_CBC_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_RC2_MAC_GENERAL_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_RC2_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_RC5_CBC_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_RC5_MAC_GENERAL_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_RC5_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_RSA_PKCS_OAEP_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_RSA_PKCS_PSS_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_SKIPJACK_PRIVATE_WRAP_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_SKIPJACK_RELAYX_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_SSL3_KEY_MAT_OUT))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_SSL3_KEY_MAT_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_SSL3_MASTER_KEY_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_SSL3_RANDOM_DATA))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_TLS_PRF_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_WTLS_KEY_MAT_OUT))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_WTLS_KEY_MAT_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_WTLS_MASTER_KEY_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_WTLS_PRF_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_WTLS_RANDOM_DATA))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_X9_42_DH1_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_X9_42_DH2_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_X9_42_MQV_DERIVE_PARAMS))));
                }
            }
            else
            {
                if (Platform.StructPackingSize == 0)
                {
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.CK_ATTRIBUTE))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.CK_C_INITIALIZE_ARGS))));
#if COREFX
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.CK_INFO).GetTypeInfo().Assembly.GetType("Net.Pkcs11Interop.LowLevelAPI80.CK_FUNCTION_LIST"))));
#else
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.CK_INFO).Assembly.GetType("Net.Pkcs11Interop.LowLevelAPI80.CK_FUNCTION_LIST"))));
#endif
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.CK_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.CK_MECHANISM))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.CK_MECHANISM_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.CK_SESSION_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.CK_SLOT_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.CK_TOKEN_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.CK_VERSION))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_AES_CBC_ENCRYPT_DATA_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_AES_CTR_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_ARIA_CBC_ENCRYPT_DATA_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_CAMELLIA_CTR_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_CMS_SIG_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_DES_CBC_ENCRYPT_DATA_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_ECDH1_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_ECDH2_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_ECMQV_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_EXTRACT_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_KEA_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_KEY_DERIVATION_STRING_DATA))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_KEY_WRAP_SET_OAEP_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_KIP_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_MAC_GENERAL_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_OTP_PARAM))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_OTP_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_OTP_SIGNATURE_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_PBE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_PKCS5_PBKD2_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_RC2_CBC_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_RC2_MAC_GENERAL_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_RC2_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_RC5_CBC_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_RC5_MAC_GENERAL_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_RC5_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_RSA_PKCS_OAEP_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_RSA_PKCS_PSS_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_SKIPJACK_PRIVATE_WRAP_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_SKIPJACK_RELAYX_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_SSL3_KEY_MAT_OUT))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_SSL3_KEY_MAT_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_SSL3_MASTER_KEY_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_SSL3_RANDOM_DATA))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_TLS_PRF_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_WTLS_KEY_MAT_OUT))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_WTLS_KEY_MAT_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_WTLS_MASTER_KEY_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_WTLS_PRF_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_WTLS_RANDOM_DATA))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_X9_42_DH1_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_X9_42_DH2_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_X9_42_MQV_DERIVE_PARAMS))));
                }
                else
                {
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.CK_ATTRIBUTE))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.CK_C_INITIALIZE_ARGS))));
#if COREFX
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.CK_INFO).GetTypeInfo().Assembly.GetType("Net.Pkcs11Interop.LowLevelAPI81.CK_FUNCTION_LIST"))));
#else
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.CK_INFO).Assembly.GetType("Net.Pkcs11Interop.LowLevelAPI81.CK_FUNCTION_LIST"))));
#endif
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.CK_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.CK_MECHANISM))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.CK_MECHANISM_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.CK_SESSION_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.CK_SLOT_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.CK_TOKEN_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.CK_VERSION))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_AES_CBC_ENCRYPT_DATA_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_AES_CTR_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_ARIA_CBC_ENCRYPT_DATA_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_CAMELLIA_CTR_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_CMS_SIG_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_DES_CBC_ENCRYPT_DATA_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_ECDH1_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_ECDH2_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_ECMQV_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_EXTRACT_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_KEA_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_KEY_DERIVATION_STRING_DATA))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_KEY_WRAP_SET_OAEP_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_KIP_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_MAC_GENERAL_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_OTP_PARAM))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_OTP_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_OTP_SIGNATURE_INFO))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_PBE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_PKCS5_PBKD2_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_RC2_CBC_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_RC2_MAC_GENERAL_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_RC2_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_RC5_CBC_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_RC5_MAC_GENERAL_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_RC5_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_RSA_PKCS_OAEP_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_RSA_PKCS_PSS_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_SKIPJACK_PRIVATE_WRAP_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_SKIPJACK_RELAYX_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_SSL3_KEY_MAT_OUT))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_SSL3_KEY_MAT_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_SSL3_MASTER_KEY_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_SSL3_RANDOM_DATA))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_TLS_PRF_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_WTLS_KEY_MAT_OUT))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_WTLS_KEY_MAT_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_WTLS_MASTER_KEY_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_WTLS_PRF_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_WTLS_RANDOM_DATA))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_X9_42_DH1_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_X9_42_DH2_DERIVE_PARAMS))));
                    sizeList.Add(Convert.ToUInt64(UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_X9_42_MQV_DERIVE_PARAMS))));
                }
            }

            return(sizeList);
        }
Exemplo n.º 15
0
        public static List<VideoCapability> GetAllVideoCapabilities(IAMStreamConfig videoStreamConfig)
        {
            if (videoStreamConfig == null)
                throw new ArgumentNullException("videoStreamConfig");

            UnmanagedMemory pCaps = null;

            List<VideoCapability> capsList = new List<VideoCapability>();

            try
            {
                // Ensure this device reports capabilities
                int c, size;
                int hr = videoStreamConfig.GetNumberOfCapabilities(out c, out size);
                DsError.ThrowExceptionForHR(hr);

                
                if (c <= 0)
                    throw new NotSupportedException("Video device does not report capabilities.");

                if (size > Marshal.SizeOf(typeof(VIDEO_STREAM_CONFIG_CAPS)))
                    throw new NotSupportedException("Unable to retrieve video device capabilities. This video device requires a larger VideoStreamConfigCaps structure.");


                // Alloc memory for structure
                pCaps = new UnmanagedMemory(Marshal.SizeOf(typeof(VIDEO_STREAM_CONFIG_CAPS)));

                VIDEO_STREAM_CONFIG_CAPS cap;


                // Retrieve all capability structures
                for (int i = 0; i < c; i++)
                {
                    AMMediaType mediaType = new AMMediaType();
                    hr = videoStreamConfig.GetStreamCaps(i, out mediaType, pCaps.MemoryPointer);
                    DsError.ThrowExceptionForHR(hr);

                    if (MediaType.Video.Equals(mediaType.majorType))
                    {
                        cap = (VIDEO_STREAM_CONFIG_CAPS)Marshal.PtrToStructure(pCaps.MemoryPointer, typeof(VIDEO_STREAM_CONFIG_CAPS));
                        VideoCapability newCap = new VideoCapability(mediaType, cap);
                        capsList.Add(newCap);
                    } else if (MediaType.Audio.Equals(mediaType.majorType))
                    {
                            Console.WriteLine("Audio Configuration");
                    }
                }
            }
            finally
            {
                if (pCaps != null)
                    pCaps.Dispose();
                pCaps = null;

                //if (mediaType != null)
                //    DsUtils.FreeAMMediaType(mediaType); 
                //mediaType = null;
            }

            return capsList;
        }
Exemplo n.º 16
0
        public bool ReadOneTransactionToDataFile(StorageEnvironmentOptions options, bool checkCrc = true)
        {
            if (_readingPage >= _journalPager.NumberOfAllocatedPages)
            {
                return(false);
            }

            if (MaxPageToRead != null && _readingPage >= MaxPageToRead.Value)
            {
                return(false);
            }

            TransactionHeader *current;

            if (!TryReadAndValidateHeader(options, out current))
            {
                return(false);
            }


            var transactionSize = GetNumberOfPagesFromSize(options, current->CompressedSize + sizeof(TransactionHeader));

            if (current->TransactionId <= _lastSyncedTransactionId)
            {
                _readingPage         += transactionSize;
                LastTransactionHeader = current;
                return(true); // skipping
            }

            if (checkCrc && !ValidatePagesHash(options, current))
            {
                return(false);
            }

            _readingPage += transactionSize;
            var numberOfPages = _recoveryPager.GetNumberOfOverflowPages(current->UncompressedSize);

            _recoveryPager.EnsureContinuous(0, numberOfPages);
            _recoveryPager.EnsureMapped(this, 0, numberOfPages);
            var outputPage = _recoveryPager.AcquirePagePointer(this, 0);

            UnmanagedMemory.Set(outputPage, 0, (long)numberOfPages * options.PageSize);

            try
            {
                LZ4.Decode64LongBuffers((byte *)current + sizeof(TransactionHeader), current->CompressedSize, outputPage,
                                        current->UncompressedSize, true);
            }
            catch (Exception e)
            {
                options.InvokeRecoveryError(this, "Could not de-compress, invalid data", e);
                RequireHeaderUpdate = true;

                return(false);
            }

            var pageInfoPtr = (TransactionHeaderPageInfo *)outputPage;

            long totalRead = sizeof(TransactionHeaderPageInfo) * current->PageCount;

            for (var i = 0; i < current->PageCount; i++)
            {
                if (totalRead > current->UncompressedSize)
                {
                    throw new InvalidDataException($"Attempted to read position {totalRead} from transaction data while the transaction is size {current->UncompressedSize}");
                }

                Debug.Assert(_journalPager.Disposed == false);
                Debug.Assert(_recoveryPager.Disposed == false);

                var numberOfPagesOnDestination = GetNumberOfPagesFromSize(options, pageInfoPtr[i].Size);
                _dataPager.EnsureContinuous(pageInfoPtr[i].PageNumber, numberOfPagesOnDestination);
                _dataPager.EnsureMapped(this, pageInfoPtr[i].PageNumber, numberOfPagesOnDestination);
                var pagePtr = _dataPager.AcquirePagePointer(this, pageInfoPtr[i].PageNumber);

                var diffPageNumber = *(long *)(outputPage + totalRead);
                if (pageInfoPtr[i].PageNumber != diffPageNumber)
                {
                    throw new InvalidDataException($"Expected a diff for page {pageInfoPtr[i].PageNumber} but got one for {diffPageNumber}");
                }
                totalRead += sizeof(long);

                _dataPager.UnprotectPageRange(pagePtr, (ulong)pageInfoPtr[i].Size);

                if (pageInfoPtr[i].DiffSize == 0)
                {
                    Memory.Copy(pagePtr, outputPage + totalRead, pageInfoPtr[i].Size);
                    totalRead += pageInfoPtr[i].Size;
                }
                else
                {
                    _diffApplier.Destination = pagePtr;
                    _diffApplier.Diff        = outputPage + totalRead;
                    _diffApplier.Size        = pageInfoPtr[i].Size;
                    _diffApplier.DiffSize    = pageInfoPtr[i].DiffSize;
                    _diffApplier.Apply();
                    totalRead += pageInfoPtr[i].DiffSize;
                }

                _dataPager.ProtectPageRange(pagePtr, (ulong)pageInfoPtr[i].Size);
            }

            LastTransactionHeader = current;

            return(true);
        }
Exemplo n.º 17
0
        public void _01_GenerateKeyTest()
        {
            Helpers.CheckPlatform();

            CKR rv = CKR.CKR_OK;

            using (Pkcs11Library pkcs11Library = new Pkcs11Library(Settings.Pkcs11LibraryPath))
            {
                rv = pkcs11Library.C_Initialize(Settings.InitArgs80);
                if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
                {
                    Assert.Fail(rv.ToString());
                }

                // Find first slot with token present
                NativeULong slotId = Helpers.GetUsableSlot(pkcs11Library);

                NativeULong session = CK.CK_INVALID_HANDLE;
                rv = pkcs11Library.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Login as normal user
                rv = pkcs11Library.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt64FromInt32(Settings.NormalUserPinArray.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Prepare attribute template of new key
                CK_ATTRIBUTE[] template = new CK_ATTRIBUTE[4];
                template[0] = CkaUtils.CreateAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY);
                template[1] = CkaUtils.CreateAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3);
                template[2] = CkaUtils.CreateAttribute(CKA.CKA_ENCRYPT, true);
                template[3] = CkaUtils.CreateAttribute(CKA.CKA_DECRYPT, true);

                // Specify key generation mechanism (needs no parameter => no unamanaged memory is needed)
                CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_KEY_GEN);

                // Generate key
                NativeULong keyId = CK.CK_INVALID_HANDLE;
                rv = pkcs11Library.C_GenerateKey(session, ref mechanism, template, ConvertUtils.UInt64FromInt32(template.Length), ref keyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // In LowLevelAPI we have to free unmanaged memory taken by attributes
                for (int i = 0; i < template.Length; i++)
                {
                    UnmanagedMemory.Free(ref template[i].value);
                    template[i].valueLen = 0;
                }

                // Do something interesting with generated key

                // Destroy object
                rv = pkcs11Library.C_DestroyObject(session, keyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11Library.C_Logout(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11Library.C_CloseSession(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11Library.C_Finalize(IntPtr.Zero);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }
            }
        }
Exemplo n.º 18
0
        public void _LL_09_02_ExtendedInitTokenAndPinTest()
        {
            Helpers.CheckPlatform();

            CKR rv = CKR.CKR_OK;

            using (RutokenPkcs11Library pkcs11 = new RutokenPkcs11Library(Settings.Pkcs11LibraryPath))
            {
                // Инициализация библиотеки
                rv = pkcs11.C_Initialize(Settings.InitArgs80);
                if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
                {
                    Assert.Fail(rv.ToString());
                }

                // Установление соединения с Рутокен в первом доступном слоте
                NativeULong slotId = Helpers.GetUsableSlot(pkcs11);

                // Инициализация токена
                var rutokenInitParam = new CK_RUTOKEN_INIT_PARAM()
                {
                    SizeofThisStructure = Convert.ToUInt64(Marshal.SizeOf(typeof(CK_RUTOKEN_INIT_PARAM))),
                    UseRepairMode       = 0,
                    NewAdminPinLen      = Convert.ToUInt64(Settings.SecurityOfficerPinArray.Length),
                    NewUserPinLen       = Convert.ToUInt64(Settings.NewUserPinArray.Length),
                    MinAdminPinLen      = 6,
                    MinUserPinLen       = 6,
                    ChangeUserPINPolicy = Convert.ToUInt64(RutokenFlag.AdminChangeUserPin | RutokenFlag.UserChangeUserPin),
                    MaxAdminRetryCount  = Settings.MAX_ADMIN_RETRY_COUNT,
                    MaxUserRetryCount   = Settings.MAX_USER_RETRY_COUNT,
                    LabelLen            = Convert.ToUInt64(Settings.TokenStdLabelArray.Length),
                    SmMode = 0
                };

                // Выделение памяти для IntPtr (можно не выделять, а использовать GCPinnedArray)
                // После использования нужно освободить память
                rutokenInitParam.NewAdminPin = UnmanagedMemory.Allocate(Settings.SecurityOfficerPinArray.Length);
                UnmanagedMemory.Write(rutokenInitParam.NewAdminPin, Settings.SecurityOfficerPinArray);
                rutokenInitParam.NewUserPin = UnmanagedMemory.Allocate(Settings.NewUserPinArray.Length);
                UnmanagedMemory.Write(rutokenInitParam.NewUserPin, Settings.NewUserPinArray);
                rutokenInitParam.TokenLabel = UnmanagedMemory.Allocate(Settings.TokenStdLabelArray.Length);
                UnmanagedMemory.Write(rutokenInitParam.TokenLabel, Settings.TokenStdLabelArray);

                // Расширенная инициализация токена
                rv = pkcs11.C_EX_InitToken(slotId, Settings.SecurityOfficerPinArray,
                                           ref rutokenInitParam);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Освобождение выделенной памяти
                UnmanagedMemory.Free(ref rutokenInitParam.NewAdminPin);
                rutokenInitParam.NewAdminPinLen = 0;
                UnmanagedMemory.Free(ref rutokenInitParam.NewUserPin);
                rutokenInitParam.NewUserPinLen = 0;
                UnmanagedMemory.Free(ref rutokenInitParam.TokenLabel);
                rutokenInitParam.LabelLen = 0;

                // Открытие RW сессии
                NativeULong session = CK.CK_INVALID_HANDLE;
                rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Блокировка PIN-кода пользователя путем ввода неверного пин-кода нужное число раз
                for (NativeULong i = 0; i < Settings.MAX_USER_RETRY_COUNT; i++)
                {
                    rv = pkcs11.C_Login(session, CKU.CKU_USER,
                                        Settings.WrongUserPinArray, Convert.ToUInt64(Settings.WrongUserPinArray.Length));
                    if (rv != CKR.CKR_PIN_INCORRECT && rv != CKR.CKR_PIN_LOCKED)
                    {
                        Assert.Fail(rv.ToString());
                    }
                }

                // Аутентификация администратора
                rv = pkcs11.C_Login(session, CKU.CKU_SO,
                                    Settings.SecurityOfficerPinArray, Convert.ToUInt64(Settings.SecurityOfficerPinArray.Length));
                if (rv != CKR.CKR_OK && rv != CKR.CKR_USER_ALREADY_LOGGED_IN)
                {
                    Assert.Fail(rv.ToString());
                }

                // Разблокировка PIN-кода пользователя
                rv = pkcs11.C_EX_UnblockUserPIN(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Завершение сессии администратора
                rv = pkcs11.C_Logout(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Аутентификация пользователя
                rv = pkcs11.C_Login(session, CKU.CKU_USER,
                                    Settings.NewUserPinArray, Convert.ToUInt64(Settings.NewUserPinArray.Length));
                if (rv != CKR.CKR_OK && rv != CKR.CKR_USER_ALREADY_LOGGED_IN)
                {
                    Assert.Fail(rv.ToString());
                }

                // Изменение метки токена на "длинную"
                rv = pkcs11.C_EX_SetTokenName(session, Settings.TokenLongLabelArray);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Получение метки токена
                NativeULong tokenLabelLength = 0;
                rv = pkcs11.C_EX_GetTokenName(session, null, ref tokenLabelLength);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                Assert.IsTrue(tokenLabelLength > 0);

                byte[] tokenLabel = new byte[tokenLabelLength];

                rv = pkcs11.C_EX_GetTokenName(session, tokenLabel, ref tokenLabelLength);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Сравнение записанной и полученной метки
                Assert.IsTrue(Convert.ToBase64String(Settings.TokenLongLabelArray) == Convert.ToBase64String(tokenLabel));

                // Установка PIN-кода пользователя по-умолчанию
                rv = pkcs11.C_SetPIN(session, Settings.NormalUserPinArray,
                                     Convert.ToUInt64(Settings.NormalUserPinArray.Length),
                                     Settings.NormalUserPinArray,
                                     Convert.ToUInt64(Settings.NormalUserPinArray.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_Finalize(IntPtr.Zero);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }
            }
        }
Exemplo n.º 19
0
        public void _01_BasicObjectFindingTest()
        {
            if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 1)
            {
                Assert.Inconclusive("Test cannot be executed on this platform");
            }

            CKR rv = CKR.CKR_OK;

            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
            {
                rv = pkcs11.C_Initialize(Settings.InitArgs81);
                if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
                {
                    Assert.Fail(rv.ToString());
                }

                // Find first slot with token present
                ulong slotId = Helpers.GetUsableSlot(pkcs11);

                ulong session = CK.CK_INVALID_HANDLE;
                rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Login as normal user
                rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Let's create two objects so we can find something
                ulong objectId1 = CK.CK_INVALID_HANDLE;
                rv = Helpers.CreateDataObject(pkcs11, session, ref objectId1);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                ulong objectId2 = CK.CK_INVALID_HANDLE;
                rv = Helpers.CreateDataObject(pkcs11, session, ref objectId2);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Prepare attribute template that defines search criteria
                CK_ATTRIBUTE[] template = new CK_ATTRIBUTE[2];
                template[0] = CkaUtils.CreateAttribute(CKA.CKA_CLASS, CKO.CKO_DATA);
                template[1] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true);

                // Initialize searching
                rv = pkcs11.C_FindObjectsInit(session, template, Convert.ToUInt64(template.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Get search results
                ulong   foundObjectCount = 0;
                ulong[] foundObjectIds   = new ulong[2];
                foundObjectIds[0] = CK.CK_INVALID_HANDLE;
                foundObjectIds[1] = CK.CK_INVALID_HANDLE;
                rv = pkcs11.C_FindObjects(session, foundObjectIds, Convert.ToUInt64(foundObjectIds.Length), ref foundObjectCount);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Terminate searching
                rv = pkcs11.C_FindObjectsFinal(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Do something interesting with found objects
                Assert.IsTrue((foundObjectIds[0] != CK.CK_INVALID_HANDLE) && (foundObjectIds[1] != CK.CK_INVALID_HANDLE));

                // In LowLevelAPI we have to free unmanaged memory taken by attributes
                for (int i = 0; i < template.Length; i++)
                {
                    UnmanagedMemory.Free(ref template[i].value);
                    template[i].valueLen = 0;
                }

                rv = pkcs11.C_DestroyObject(session, objectId2);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_DestroyObject(session, objectId1);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_Logout(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_CloseSession(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_Finalize(IntPtr.Zero);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Initializes a new instance of the CkSkipjackPrivateWrapParams class.
        /// </summary>
        /// <param name='password'>User-supplied password</param>
        /// <param name='publicData'>Other party's key exchange public key value</param>
        /// <param name='randomA'>Ra data</param>
        /// <param name='primeP'>Prime, p, value</param>
        /// <param name='baseG'>Base, g, value</param>
        /// <param name='subprimeQ'>Subprime, q, value</param>
        public CkSkipjackPrivateWrapParams(byte[] password, byte[] publicData, byte[] randomA, byte[] primeP, byte[] baseG, byte[] subprimeQ)
        {
            _lowLevelStruct.PasswordLen   = 0;
            _lowLevelStruct.Password      = IntPtr.Zero;
            _lowLevelStruct.PublicDataLen = 0;
            _lowLevelStruct.PublicData    = IntPtr.Zero;
            _lowLevelStruct.PAndGLen      = 0;
            _lowLevelStruct.QLen          = 0;
            _lowLevelStruct.RandomLen     = 0;
            _lowLevelStruct.RandomA       = IntPtr.Zero;
            _lowLevelStruct.PrimeP        = IntPtr.Zero;
            _lowLevelStruct.BaseG         = IntPtr.Zero;
            _lowLevelStruct.SubprimeQ     = IntPtr.Zero;

            if (password != null)
            {
                _lowLevelStruct.Password = UnmanagedMemory.Allocate(password.Length);
                UnmanagedMemory.Write(_lowLevelStruct.Password, password);
                _lowLevelStruct.PasswordLen = ConvertUtils.UInt64FromInt32(password.Length);
            }

            if (publicData != null)
            {
                _lowLevelStruct.PublicData = UnmanagedMemory.Allocate(publicData.Length);
                UnmanagedMemory.Write(_lowLevelStruct.PublicData, publicData);
                _lowLevelStruct.PublicDataLen = ConvertUtils.UInt64FromInt32(publicData.Length);
            }

            if (randomA != null)
            {
                _lowLevelStruct.RandomA = UnmanagedMemory.Allocate(randomA.Length);
                UnmanagedMemory.Write(_lowLevelStruct.RandomA, randomA);
                _lowLevelStruct.RandomLen = ConvertUtils.UInt64FromInt32(randomA.Length);
            }

            if ((primeP != null) && (baseG != null))
            {
                if (primeP.Length != baseG.Length)
                {
                    throw new ArgumentException("Length of primeP has to be the same as length of baseG");
                }
            }

            if (primeP != null)
            {
                _lowLevelStruct.PrimeP = UnmanagedMemory.Allocate(primeP.Length);
                UnmanagedMemory.Write(_lowLevelStruct.PrimeP, primeP);
                _lowLevelStruct.PAndGLen = ConvertUtils.UInt64FromInt32(primeP.Length);
            }

            if (baseG != null)
            {
                _lowLevelStruct.BaseG = UnmanagedMemory.Allocate(baseG.Length);
                UnmanagedMemory.Write(_lowLevelStruct.BaseG, baseG);
                _lowLevelStruct.PAndGLen = ConvertUtils.UInt64FromInt32(baseG.Length);
            }

            if (subprimeQ != null)
            {
                _lowLevelStruct.SubprimeQ = UnmanagedMemory.Allocate(subprimeQ.Length);
                UnmanagedMemory.Write(_lowLevelStruct.SubprimeQ, subprimeQ);
                _lowLevelStruct.QLen = ConvertUtils.UInt64FromInt32(subprimeQ.Length);
            }
        }
        public void _02_SetAttributeValueTest()
        {
            Helpers.CheckPlatform();

            CKR rv = CKR.CKR_OK;

            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
            {
                rv = pkcs11.C_Initialize(Settings.InitArgs80);
                if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
                {
                    Assert.Fail(rv.ToString());
                }

                // Find first slot with token present
                NativeULong slotId = Helpers.GetUsableSlot(pkcs11);

                NativeULong session = CK.CK_INVALID_HANDLE;
                rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Login as normal user
                rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt64FromInt32(Settings.NormalUserPinArray.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Create object
                NativeULong objectId = CK.CK_INVALID_HANDLE;
                rv = Helpers.CreateDataObject(pkcs11, session, ref objectId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Prepare list of attributes we want to set
                CK_ATTRIBUTE[] template = new CK_ATTRIBUTE[2];
                template[0] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, "Hello world");
                template[1] = CkaUtils.CreateAttribute(CKA.CKA_VALUE, "New data object content");

                // Set attributes
                rv = pkcs11.C_SetAttributeValue(session, objectId, template, ConvertUtils.UInt64FromInt32(template.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // In LowLevelAPI we have to free unmanaged memory taken by attributes
                for (int i = 0; i < template.Length; i++)
                {
                    UnmanagedMemory.Free(ref template[i].value);
                    template[i].valueLen = 0;
                }

                rv = pkcs11.C_DestroyObject(session, objectId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_Logout(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_CloseSession(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_Finalize(IntPtr.Zero);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }
            }
        }
Exemplo n.º 22
0
        public void _LL_25_26_02_DeriveAndWrap_VKO_Gost3410_12_Test()
        {
            if (Platform.NativeULongSize != 4 || Platform.StructPackingSize != 1)
            {
                Assert.Inconclusive("Test cannot be executed on this platform");
            }

            CKR rv = CKR.CKR_OK;

            using (RutokenPkcs11Library pkcs11 = new RutokenPkcs11Library(Settings.Pkcs11LibraryPath))
            {
                // Инициализация библиотеки
                rv = pkcs11.C_Initialize(Settings.InitArgs41);
                if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
                {
                    Assert.Fail(rv.ToString());
                }

                // Установление соединения с Рутокен в первом доступном слоте
                NativeULong slotId = Helpers.GetUsableSlot(pkcs11);

                // Открытие RW сессии
                NativeULong session = CK.CK_INVALID_HANDLE;
                rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Выполнение аутентификации пользователя
                rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt32(Settings.NormalUserPinArray.Length));
                if (rv != CKR.CKR_OK && rv != CKR.CKR_USER_ALREADY_LOGGED_IN)
                {
                    Assert.Fail(rv.ToString());
                }

                // Генерация параметра для структуры типа CK_GOSTR3410_DERIVE_PARAMS
                // для выработки общего ключа
                byte[] ukm = new byte[Settings.UKM_LENGTH];
                rv = pkcs11.C_GenerateRandom(session, ukm, Convert.ToUInt32(ukm.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Генерация значения сессионного ключа
                byte[] sessionKeyValue = new byte[Settings.GOST_28147_KEY_SIZE];
                rv = pkcs11.C_GenerateRandom(session, sessionKeyValue, Convert.ToUInt32(sessionKeyValue.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Генерация ключевой пары ГОСТ Р 34.10-2012 отправителя
                NativeULong senderPubKeyId  = CK.CK_INVALID_HANDLE;
                NativeULong senderPrivKeyId = CK.CK_INVALID_HANDLE;
                Helpers.GenerateGost512KeyPair(pkcs11, session, ref senderPubKeyId, ref senderPrivKeyId, Settings.Gost512KeyPairId1);

                // Генерация ключевой пары ГОСТ Р 34.10-2012 получателя
                NativeULong recipientPubKeyId  = CK.CK_INVALID_HANDLE;
                NativeULong recipientPrivKeyId = CK.CK_INVALID_HANDLE;
                Helpers.GenerateGost512KeyPair(pkcs11, session, ref recipientPubKeyId, ref recipientPrivKeyId, Settings.Gost512KeyPairId2);

                // Выработка общего ключа на стороне отправителя
                NativeULong senderDerivedKeyId = CK.CK_INVALID_HANDLE;
                Helpers.Derive_GostR3410_12_Key(pkcs11, session, recipientPubKeyId, senderPrivKeyId, ukm, ref senderDerivedKeyId);

                // Шаблон для создания маскируемого ключа
                CK_ATTRIBUTE[] sessionKeyTemplate = new CK_ATTRIBUTE[9];
                sessionKeyTemplate[0] = CkaUtils.CreateAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY);
                sessionKeyTemplate[1] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.WrappedGost28147_89KeyLabel);
                sessionKeyTemplate[2] = CkaUtils.CreateAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_GOST28147);
                sessionKeyTemplate[3] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, false);
                sessionKeyTemplate[4] = CkaUtils.CreateAttribute(CKA.CKA_MODIFIABLE, true);
                sessionKeyTemplate[5] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, true);
                sessionKeyTemplate[6] = CkaUtils.CreateAttribute(CKA.CKA_VALUE, sessionKeyValue);
                sessionKeyTemplate[7] = CkaUtils.CreateAttribute(CKA.CKA_EXTRACTABLE, true);
                sessionKeyTemplate[8] = CkaUtils.CreateAttribute(CKA.CKA_SENSITIVE, false);

                // Выработка ключа, который будет замаскирован
                NativeULong sessionKeyId = CK.CK_INVALID_HANDLE;
                rv = pkcs11.C_CreateObject(session, sessionKeyTemplate, Convert.ToUInt32(sessionKeyTemplate.Length), ref sessionKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                Assert.IsTrue(sessionKeyId != CK.CK_INVALID_HANDLE);

                // Определение параметров механизма маскирования
                // В LowLevelAPI выделенная для параметров память должны быть освобождена после использования
                CK_KEY_DERIVATION_STRING_DATA wrapMechanismParams = new CK_KEY_DERIVATION_STRING_DATA();
                wrapMechanismParams.Data = UnmanagedMemory.Allocate(ukm.Length);
                UnmanagedMemory.Write(wrapMechanismParams.Data, ukm);
                wrapMechanismParams.Len = Convert.ToUInt32(ukm.Length);
                CK_MECHANISM wrapMechanism = CkmUtils.CreateMechanism(CKM.CKM_GOST28147_KEY_WRAP, wrapMechanismParams);

                // Получение длины маскированного ключа
                NativeULong wrappedKeyLen = 0;
                rv = pkcs11.C_WrapKey(session, ref wrapMechanism, senderDerivedKeyId, sessionKeyId, null, ref wrappedKeyLen);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                Assert.IsTrue(wrappedKeyLen > 0);

                byte[] wrappedKey = new byte[wrappedKeyLen];

                // Маскирование ключа на общем ключе, выработанном на стороне отправителя
                rv = pkcs11.C_WrapKey(session, ref wrapMechanism, senderDerivedKeyId, sessionKeyId, wrappedKey, ref wrappedKeyLen);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Выработка общего ключа на стороне получателя
                NativeULong recipientDerivedKeyId = CK.CK_INVALID_HANDLE;
                Helpers.Derive_GostR3410_12_Key(pkcs11, session, senderPubKeyId, recipientPrivKeyId, ukm, ref recipientDerivedKeyId);

                // Шаблон демаскированного ключа
                CK_ATTRIBUTE[] unwrappedKeyTemplate = new CK_ATTRIBUTE[8];
                unwrappedKeyTemplate[0] = CkaUtils.CreateAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY);
                unwrappedKeyTemplate[1] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.UnwrappedGost28147_89KeyLabel);
                unwrappedKeyTemplate[2] = CkaUtils.CreateAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_GOST28147);
                unwrappedKeyTemplate[3] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, false);
                unwrappedKeyTemplate[4] = CkaUtils.CreateAttribute(CKA.CKA_MODIFIABLE, true);
                unwrappedKeyTemplate[5] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, false);
                unwrappedKeyTemplate[6] = CkaUtils.CreateAttribute(CKA.CKA_EXTRACTABLE, true);
                unwrappedKeyTemplate[7] = CkaUtils.CreateAttribute(CKA.CKA_SENSITIVE, false);

                // Демаскирование сессионного ключа с помощью общего выработанного
                // ключа на стороне получателя
                NativeULong unwrappedKeyId = 0;
                rv = pkcs11.C_UnwrapKey(session, ref wrapMechanism, recipientDerivedKeyId, wrappedKey, wrappedKeyLen,
                                        unwrappedKeyTemplate, Convert.ToUInt32(unwrappedKeyTemplate.Length), ref unwrappedKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                CK_ATTRIBUTE[] valueTemplate = new CK_ATTRIBUTE[1];
                valueTemplate[0] = CkaUtils.CreateAttribute(CKA.CKA_VALUE);
                // In LowLevelAPI we have to allocate unmanaged memory for attribute value
                valueTemplate[0].value    = UnmanagedMemory.Allocate(Convert.ToInt32(32));
                valueTemplate[0].valueLen = 32;

                // Get attribute value in second call
                rv = pkcs11.C_GetAttributeValue(session, unwrappedKeyId, valueTemplate, Convert.ToUInt32(valueTemplate.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Сравнение ключа
                byte[] unwrappedKey = UnmanagedMemory.Read(valueTemplate[0].value, Convert.ToInt32(valueTemplate[0].valueLen));
                Assert.IsTrue(Convert.ToBase64String(sessionKeyValue) == Convert.ToBase64String(unwrappedKey));

                // Освобождение выделенной памяти для параметров механизма
                UnmanagedMemory.Free(ref wrapMechanismParams.Data);
                wrapMechanismParams.Len = 0;
                UnmanagedMemory.Free(ref wrapMechanism.Parameter);
                wrapMechanism.ParameterLen = 0;

                // Удаляем созданные пары ключей
                rv = pkcs11.C_DestroyObject(session, senderPrivKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_DestroyObject(session, senderPubKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_DestroyObject(session, recipientPrivKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_DestroyObject(session, recipientPubKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Удаляем сессионный ключ
                rv = pkcs11.C_DestroyObject(session, sessionKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Удаляем наследованные ключи
                rv = pkcs11.C_DestroyObject(session, senderDerivedKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_DestroyObject(session, recipientDerivedKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Закрываем сессию
                rv = pkcs11.C_Logout(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_CloseSession(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_Finalize(IntPtr.Zero);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }
            }
        }
Exemplo n.º 23
0
        public void _03_EncryptAndDecryptSinglePartOaepTest()
        {
            Helpers.CheckPlatform();

            CKR rv = CKR.CKR_OK;

            using (Pkcs11Library pkcs11Library = new Pkcs11Library(Settings.Pkcs11LibraryPath))
            {
                rv = pkcs11Library.C_Initialize(Settings.InitArgs41);
                if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
                {
                    Assert.Fail(rv.ToString());
                }

                // Find first slot with token present
                NativeULong slotId = Helpers.GetUsableSlot(pkcs11Library);

                NativeULong session = CK.CK_INVALID_HANDLE;
                rv = pkcs11Library.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Login as normal user
                rv = pkcs11Library.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt32FromInt32(Settings.NormalUserPinArray.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Generate asymetric key pair
                NativeULong pubKeyId  = CK.CK_INVALID_HANDLE;
                NativeULong privKeyId = CK.CK_INVALID_HANDLE;
                rv = Helpers.GenerateKeyPair(pkcs11Library, session, ref pubKeyId, ref privKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Specify mechanism parameters
                CK_RSA_PKCS_OAEP_PARAMS mechanismParams = new CK_RSA_PKCS_OAEP_PARAMS();
                mechanismParams.HashAlg       = ConvertUtils.UInt32FromCKM(CKM.CKM_SHA_1);
                mechanismParams.Mgf           = ConvertUtils.UInt32FromCKG(CKG.CKG_MGF1_SHA1);
                mechanismParams.Source        = ConvertUtils.UInt32FromUInt32(CKZ.CKZ_DATA_SPECIFIED);
                mechanismParams.SourceData    = IntPtr.Zero;
                mechanismParams.SourceDataLen = 0;

                // Specify encryption mechanism with parameters
                // Note that CkmUtils.CreateMechanism() automaticaly copies mechanismParams into newly allocated unmanaged memory.
                CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_RSA_PKCS_OAEP, mechanismParams);

                // Initialize encryption operation
                rv = pkcs11Library.C_EncryptInit(session, ref mechanism, pubKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world");

                // Get length of encrypted data in first call
                NativeULong encryptedDataLen = 0;
                rv = pkcs11Library.C_Encrypt(session, sourceData, ConvertUtils.UInt32FromInt32(sourceData.Length), null, ref encryptedDataLen);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                Assert.IsTrue(encryptedDataLen > 0);

                // Allocate array for encrypted data
                byte[] encryptedData = new byte[encryptedDataLen];

                // Get encrypted data in second call
                rv = pkcs11Library.C_Encrypt(session, sourceData, ConvertUtils.UInt32FromInt32(sourceData.Length), encryptedData, ref encryptedDataLen);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Do something interesting with encrypted data

                // Initialize decryption operation
                rv = pkcs11Library.C_DecryptInit(session, ref mechanism, privKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Get length of decrypted data in first call
                NativeULong decryptedDataLen = 0;
                rv = pkcs11Library.C_Decrypt(session, encryptedData, ConvertUtils.UInt32FromInt32(encryptedData.Length), null, ref decryptedDataLen);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                Assert.IsTrue(decryptedDataLen > 0);

                // Allocate array for decrypted data
                byte[] decryptedData = new byte[decryptedDataLen];

                // Get decrypted data in second call
                rv = pkcs11Library.C_Decrypt(session, encryptedData, ConvertUtils.UInt32FromInt32(encryptedData.Length), decryptedData, ref decryptedDataLen);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Array may need to be shrinked
                if (decryptedData.Length != ConvertUtils.UInt32ToInt32(decryptedDataLen))
                {
                    Array.Resize(ref decryptedData, ConvertUtils.UInt32ToInt32(decryptedDataLen));
                }

                // Do something interesting with decrypted data
                Assert.IsTrue(ConvertUtils.BytesToBase64String(sourceData) == ConvertUtils.BytesToBase64String(decryptedData));

                // In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter
                UnmanagedMemory.Free(ref mechanism.Parameter);
                mechanism.ParameterLen = 0;

                rv = pkcs11Library.C_DestroyObject(session, privKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11Library.C_DestroyObject(session, pubKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11Library.C_Logout(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11Library.C_CloseSession(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11Library.C_Finalize(IntPtr.Zero);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }
            }
        }
Exemplo n.º 24
0
        public void _LL_25_26_03_KegKexp15KuznechikTwisted_Test()
        {
            if (Platform.NativeULongSize != 4 || Platform.StructPackingSize != 1)
            {
                Assert.Inconclusive("Test cannot be executed on this platform");
            }

            CKR rv = CKR.CKR_OK;

            using (var pkcs11 = new RutokenPkcs11Library(Settings.Pkcs11LibraryPath))
            {
                // Инициализация библиотеки
                rv = pkcs11.C_Initialize(Settings.InitArgs41);
                if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
                {
                    Assert.Fail(rv.ToString());
                }

                // Установление соединения с Рутокен в первом доступном слоте
                NativeULong slotId = Helpers.GetUsableSlot(pkcs11);

                // Открытие RW сессии
                NativeULong session = CK.CK_INVALID_HANDLE;
                rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Выполнение аутентификации пользователя
                rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt32(Settings.NormalUserPinArray.Length));
                if (rv != CKR.CKR_OK && rv != CKR.CKR_USER_ALREADY_LOGGED_IN)
                {
                    Assert.Fail(rv.ToString());
                }

                // Генерация параметра для структуры типа CK_VENDOR_GOST_KEG_PARAMS
                // для выработки двойственного ключа экспорта
                byte[] ukm = new byte[Settings.KEG_256_UKM_LENGTH];
                rv = pkcs11.C_GenerateRandom(session, ukm, Convert.ToUInt32(ukm.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Генерация значения сессионного ключа
                byte[] sessionKeyValue = new byte[Settings.GOST_28147_KEY_SIZE];
                rv = pkcs11.C_GenerateRandom(session, sessionKeyValue, Convert.ToUInt32(sessionKeyValue.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Генерация ключевой пары ГОСТ Р 34.10-2012(256) отправителя
                NativeULong senderPubKeyId  = CK.CK_INVALID_HANDLE;
                NativeULong senderPrivKeyId = CK.CK_INVALID_HANDLE;
                Helpers.GenerateGost256KeyPair(pkcs11, session, ref senderPubKeyId, ref senderPrivKeyId, Settings.GostKeyPairId1);

                // Генерация ключевой пары ГОСТ Р 34.10-2012(256) получателя
                NativeULong recipientPubKeyId  = CK.CK_INVALID_HANDLE;
                NativeULong recipientPrivKeyId = CK.CK_INVALID_HANDLE;
                Helpers.GenerateGost256KeyPair(pkcs11, session, ref recipientPubKeyId, ref recipientPrivKeyId, Settings.GostKeyPairId2);

                // Выработка общего ключа на стороне отправителя
                NativeULong senderDerivedKeyId = CK.CK_INVALID_HANDLE;
                Helpers.DeriveKuznechikTwin_GostR3410_12_Key(pkcs11, session, recipientPubKeyId, senderPrivKeyId, ukm, ref senderDerivedKeyId);

                // Шаблон для создания маскируемого ключа
                CK_ATTRIBUTE[] sessionKeyTemplate = new CK_ATTRIBUTE[9];
                sessionKeyTemplate[0] = CkaUtils.CreateAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY);
                sessionKeyTemplate[1] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.WrappedKuznechikKeyLabel);
                sessionKeyTemplate[2] = CkaUtils.CreateAttribute(CKA.CKA_KEY_TYPE, (CKK)Extended_CKK.CKK_KUZNECHIK);
                sessionKeyTemplate[3] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, false);
                sessionKeyTemplate[4] = CkaUtils.CreateAttribute(CKA.CKA_MODIFIABLE, true);
                sessionKeyTemplate[5] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, true);
                sessionKeyTemplate[6] = CkaUtils.CreateAttribute(CKA.CKA_VALUE, sessionKeyValue);
                sessionKeyTemplate[7] = CkaUtils.CreateAttribute(CKA.CKA_EXTRACTABLE, true);
                sessionKeyTemplate[8] = CkaUtils.CreateAttribute(CKA.CKA_SENSITIVE, false);

                // Выработка ключа, который будет замаскирован
                NativeULong sessionKeyId = CK.CK_INVALID_HANDLE;
                rv = pkcs11.C_CreateObject(session, sessionKeyTemplate, Convert.ToUInt32(sessionKeyTemplate.Length), ref sessionKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                Assert.IsTrue(sessionKeyId != CK.CK_INVALID_HANDLE);

                // Генерация имитовставки для алгоритма экспорта ключей KExp15
                byte[] kexp15Ukm = new byte[Settings.KEXP15_KUZNECHIK_TWIN_UKM_LENGTH];
                rv = pkcs11.C_GenerateRandom(session, kexp15Ukm, Convert.ToUInt32(kexp15Ukm.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                CK_MECHANISM wrapMechanism = CkmUtils.CreateMechanism((NativeULong)Extended_CKM.CKM_KUZNECHIK_KEXP_15_WRAP, kexp15Ukm);

                // Получение длины маскированного ключа
                NativeULong wrappedKeyLen = 0;
                rv = pkcs11.C_WrapKey(session, ref wrapMechanism, senderDerivedKeyId, sessionKeyId, null, ref wrappedKeyLen);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                Assert.IsTrue(wrappedKeyLen > 0);

                byte[] wrappedKey = new byte[wrappedKeyLen];

                // Маскирование ключа на общем ключе, выработанном на стороне отправителя
                rv = pkcs11.C_WrapKey(session, ref wrapMechanism, senderDerivedKeyId, sessionKeyId, wrappedKey, ref wrappedKeyLen);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Выработка общего ключа на стороне получателя
                NativeULong recipientDerivedKeyId = CK.CK_INVALID_HANDLE;
                Helpers.DeriveKuznechikTwin_GostR3410_12_Key(pkcs11, session, senderPubKeyId, recipientPrivKeyId, ukm, ref recipientDerivedKeyId);

                // Шаблон демаскированного ключа
                CK_ATTRIBUTE[] unwrappedKeyTemplate = new CK_ATTRIBUTE[8];
                unwrappedKeyTemplate[0] = CkaUtils.CreateAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY);
                unwrappedKeyTemplate[1] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.UnwrappedGost28147_89KeyLabel);
                unwrappedKeyTemplate[2] = CkaUtils.CreateAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_GOST28147);
                unwrappedKeyTemplate[3] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, false);
                unwrappedKeyTemplate[4] = CkaUtils.CreateAttribute(CKA.CKA_MODIFIABLE, true);
                unwrappedKeyTemplate[5] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, false);
                unwrappedKeyTemplate[6] = CkaUtils.CreateAttribute(CKA.CKA_EXTRACTABLE, true);
                unwrappedKeyTemplate[7] = CkaUtils.CreateAttribute(CKA.CKA_SENSITIVE, false);

                // Демаскирование сессионного ключа с помощью общего выработанного
                // ключа на стороне получателя
                NativeULong unwrappedKeyId = 0;
                rv = pkcs11.C_UnwrapKey(session, ref wrapMechanism, recipientDerivedKeyId, wrappedKey, wrappedKeyLen,
                                        unwrappedKeyTemplate, Convert.ToUInt32(unwrappedKeyTemplate.Length), ref unwrappedKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                CK_ATTRIBUTE[] valueTemplate = new CK_ATTRIBUTE[1];
                valueTemplate[0]          = CkaUtils.CreateAttribute(CKA.CKA_VALUE);
                valueTemplate[0].value    = UnmanagedMemory.Allocate(Convert.ToInt32(32));
                valueTemplate[0].valueLen = 32;

                rv = pkcs11.C_GetAttributeValue(session, unwrappedKeyId, valueTemplate, Convert.ToUInt32(valueTemplate.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Сравнение ключа
                byte[] unwrappedKey = UnmanagedMemory.Read(valueTemplate[0].value, Convert.ToInt32(valueTemplate[0].valueLen));
                Assert.IsTrue(Convert.ToBase64String(sessionKeyValue) == Convert.ToBase64String(unwrappedKey));

                // Освобождение выделенной памяти под аттрибуты
                for (int i = 0; i < valueTemplate.Length; i++)
                {
                    UnmanagedMemory.Free(ref valueTemplate[i].value);
                    valueTemplate[i].valueLen = 0;
                }

                for (int i = 0; i < sessionKeyTemplate.Length; i++)
                {
                    UnmanagedMemory.Free(ref sessionKeyTemplate[i].value);
                    sessionKeyTemplate[i].valueLen = 0;
                }

                for (int i = 0; i < unwrappedKeyTemplate.Length; i++)
                {
                    UnmanagedMemory.Free(ref unwrappedKeyTemplate[i].value);
                    unwrappedKeyTemplate[i].valueLen = 0;
                }

                // Удаляем созданные пары ключей
                rv = pkcs11.C_DestroyObject(session, senderPrivKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_DestroyObject(session, senderPubKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_DestroyObject(session, recipientPrivKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_DestroyObject(session, recipientPubKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Удаляем сессионный ключ
                rv = pkcs11.C_DestroyObject(session, sessionKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Удаляем наследованные ключи
                rv = pkcs11.C_DestroyObject(session, senderDerivedKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_DestroyObject(session, recipientDerivedKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Закрываем сессию
                rv = pkcs11.C_Logout(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_CloseSession(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_Finalize(IntPtr.Zero);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }
            }
        }
Exemplo n.º 25
0
        private static int LZ4_decompress_generic <TEndCondition, TEarlyEnd, TDictionaryType>(byte *source, byte *dest, int inputSize, int outputSize, int targetOutputSize, byte *lowPrefix, byte *dictStart, int dictSize)
            where TEndCondition : IEndConditionDirective
            where TEarlyEnd : IEarlyEndDirective
            where TDictionaryType : IDictionaryTypeDirective
        {
            /* Local Variables */
            byte *ip   = source;
            byte *iend = ip + inputSize;

            byte *op   = dest;
            byte *oend = op + outputSize;

            byte *oexit    = op + targetOutputSize;
            byte *lowLimit = lowPrefix - dictSize;

            byte *dictEnd = dictStart + dictSize;

            bool checkOffset = ((typeof(TEndCondition) == typeof(EndOnInputSize)) && (dictSize < 64 * Constants.Size.Kilobyte));

            // Special Cases
            if ((typeof(TEarlyEnd) == typeof(Partial)) && (oexit > oend - MFLIMIT))
            {
                oexit = oend - MFLIMIT;                                                                                              // targetOutputSize too high => decode everything
            }
            if ((typeof(TEndCondition) == typeof(EndOnInputSize)) && (outputSize == 0))
            {
                return(((inputSize == 1) && (*ip == 0)) ? 0 : -1);  // Empty output buffer
            }
            if ((typeof(TEndCondition) == typeof(EndOnOutputSize)) && (outputSize == 0))
            {
                return(*ip == 0 ? 1 : -1);
            }

            // Main Loop
            while (true)
            {
                int length;

                /* get literal length */
                byte token = *ip++;
                if ((length = (token >> ML_BITS)) == RUN_MASK)
                {
                    byte s;
                    do
                    {
                        s       = *ip++;
                        length += s;
                    }while (((typeof(TEndCondition) == typeof(EndOnInputSize)) ? ip < iend - RUN_MASK : true) && (s == 255));

                    if ((typeof(TEndCondition) == typeof(EndOnInputSize)) && (op + length) < op)
                    {
                        goto _output_error;                                                                            /* overflow detection */
                    }
                    if ((typeof(TEndCondition) == typeof(EndOnInputSize)) && (ip + length) < ip)
                    {
                        goto _output_error;                                                                            /* overflow detection */
                    }
                }

                // copy literals
                byte *cpy = op + length;
                if (((typeof(TEndCondition) == typeof(EndOnInputSize)) && ((cpy > (typeof(TEarlyEnd) == typeof(Partial) ? oexit : oend - MFLIMIT)) || (ip + length > iend - (2 + 1 + LASTLITERALS)))) ||
                    ((typeof(TEndCondition) == typeof(EndOnOutputSize)) && (cpy > oend - COPYLENGTH)))
                {
                    if (typeof(TEarlyEnd) == typeof(Partial))
                    {
                        if (cpy > oend)
                        {
                            goto _output_error;                           /* Error : write attempt beyond end of output buffer */
                        }
                        if ((typeof(TEndCondition) == typeof(EndOnInputSize)) && (ip + length > iend))
                        {
                            goto _output_error;   /* Error : read attempt beyond end of input buffer */
                        }
                    }
                    else
                    {
                        if ((typeof(TEndCondition) == typeof(EndOnOutputSize)) && (cpy != oend))
                        {
                            goto _output_error;       /* Error : block decoding must stop exactly there */
                        }
                        if ((typeof(TEndCondition) == typeof(EndOnInputSize)) && ((ip + length != iend) || (cpy > oend)))
                        {
                            goto _output_error;   /* Error : input must be consumed */
                        }
                    }

                    Unsafe.CopyBlock(op, ip, (uint)length);
                    ip += length;
                    op += length;
                    break;     /* Necessarily EOF, due to parsing restrictions */
                }

                WildCopy(op, ip, cpy);
                ip += length; op = cpy;

                /* get offset */
                byte *match = cpy - *((ushort *)ip); ip += sizeof(ushort);
                if ((checkOffset) && (match < lowLimit))
                {
                    goto _output_error;   /* Error : offset outside destination buffer */
                }
                /* get matchlength */
                if ((length = (token & ML_MASK)) == ML_MASK)
                {
                    byte s;
                    do
                    {
                        if ((typeof(TEndCondition) == typeof(EndOnInputSize)) && (ip > iend - LASTLITERALS))
                        {
                            goto _output_error;
                        }

                        s       = *ip++;
                        length += s;
                    }while (s == 255);

                    if ((typeof(TEndCondition) == typeof(EndOnInputSize)) && (op + length) < op)
                    {
                        goto _output_error;   /* overflow detection */
                    }
                }

                length += MINMATCH;

                /* check external dictionary */
                if ((typeof(TDictionaryType) == typeof(UsingExtDict)) && (match < lowPrefix))
                {
                    if (op + length > oend - LASTLITERALS)
                    {
                        goto _output_error;   /* doesn't respect parsing restriction */
                    }
                    if (length <= (int)(lowPrefix - match))
                    {
                        /* match can be copied as a single segment from external dictionary */
                        match = dictEnd - (lowPrefix - match);
                        UnmanagedMemory.Move(op, match, length);
                        op += length;
                    }
                    else
                    {
                        /* match encompass external dictionary and current segment */
                        int copySize = (int)(lowPrefix - match);
                        Unsafe.CopyBlock(op, dictEnd - copySize, (uint)copySize);
                        op += copySize;

                        copySize = length - copySize;
                        if (copySize > (int)(op - lowPrefix))   /* overlap within current segment */
                        {
                            byte *endOfMatch = op + copySize;
                            byte *copyFrom   = lowPrefix;
                            while (op < endOfMatch)
                            {
                                *op++ = *copyFrom++;
                            }
                        }
                        else
                        {
                            Unsafe.CopyBlock(op, lowPrefix, (uint)copySize);
                            op += copySize;
                        }
                    }
                    continue;
                }

                /* copy repeated sequence */
                cpy = op + length;
                if ((op - match) < 8)
                {
                    int dec64 = dec64table[op - match];
                    op[0] = match[0];
                    op[1] = match[1];
                    op[2] = match[2];
                    op[3] = match[3];

                    match += dec32table[op - match];
                    *((uint *)(op + 4)) = *(uint *)match;
                    op    += 8;
                    match -= dec64;
                }
                else
                {
                    *((ulong *)op) = *(ulong *)match;
                    op            += sizeof(ulong);
                    match         += sizeof(ulong);
                }

                if (cpy > oend - 12)
                {
                    if (cpy > oend - LASTLITERALS)
                    {
                        goto _output_error;    /* Error : last LASTLITERALS bytes must be literals */
                    }
                    if (op < oend - 8)
                    {
                        WildCopy(op, match, (oend - 8));
                        match += (oend - 8) - op;
                        op     = oend - 8;
                    }

                    while (op < cpy)
                    {
                        *op++ = *match++;
                    }
                }
                else
                {
                    WildCopy(op, match, cpy);
                }

                op = cpy;   /* correction */
            }

            /* end of decoding */
            if (typeof(TEndCondition) == typeof(EndOnInputSize))
            {
                return((int)(op - dest));     /* Nb of output bytes decoded */
            }
            else
            {
                return((int)(ip - source));   /* Nb of input bytes read */
            }
            /* Overflow error detected */
_output_error:
            return((int)(-(ip - source)) - 1);
        }
Exemplo n.º 26
0
 public TestTree(Int64 nodesCount)
     : base(nodesCount, Marshal.SizeOf(typeof(TestNode)))
 {
     UnmanagedMemory.SetMemory(_nodesPtr.Ptr, _nodesByteSize, 0);
     _nodes = (TestNode *)_nodesPtr.Ptr.ToPointer();
 }
Exemplo n.º 27
0
        /// <summary>
        /// Initializes a new instance of the CkWtlsMasterKeyDeriveParams class.
        /// </summary>
        /// <param name='digestMechanism'>Digest mechanism to be used (CKM)</param>
        /// <param name='randomInfo'>Client's and server's random data information</param>
        /// <param name='dh'>Set to false for CKM_WTLS_MASTER_KEY_DERIVE mechanism and to true for CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC mechanism</param>
        public CkWtlsMasterKeyDeriveParams(NativeULong digestMechanism, ICkWtlsRandomData randomInfo, bool dh)
        {
            if (randomInfo == null)
            {
                throw new ArgumentNullException("randomInfo");
            }

            // Keep reference to randomInfo so GC will not free it while this object exists
            _randomInfo = randomInfo;

            _lowLevelStruct.DigestMechanism = digestMechanism;
            _lowLevelStruct.RandomInfo      = (CK_WTLS_RANDOM_DATA)_randomInfo.ToMarshalableStructure();
            _lowLevelStruct.Version         = (dh) ? IntPtr.Zero : UnmanagedMemory.Allocate(UnmanagedMemory.SizeOf(typeof(CK_VERSION)));
        }
Exemplo n.º 28
0
 /// <summary>
 /// Allocate memory for arrays. Must be called when n, dim and k are set.
 /// </summary>
 public void Allocate()
 {
     points  = (double *)UnmanagedMemory.AllocHGlobalEx(n * dim * 8);
     centers = (double *)UnmanagedMemory.AllocHGlobalEx(k * dim * 8);
 }
Exemplo n.º 29
0
        /// <summary>
        /// Initializes a new instance of the CkSkipjackRelayxParams class.
        /// </summary>
        /// <param name='oldWrappedX'>Old wrapper key</param>
        /// <param name='oldPassword'>Old user-supplied password</param>
        /// <param name='oldPublicData'>Old key exchange public key value</param>
        /// <param name='oldRandomA'>Old Ra data</param>
        /// <param name='newPassword'>New user-supplied password</param>
        /// <param name='newPublicData'>New key exchange public key value</param>
        /// <param name='newRandomA'>New Ra data</param>
        public CkSkipjackRelayxParams(byte[] oldWrappedX, byte[] oldPassword, byte[] oldPublicData, byte[] oldRandomA, byte[] newPassword, byte[] newPublicData, byte[] newRandomA)
        {
            _lowLevelStruct.OldWrappedXLen   = 0;
            _lowLevelStruct.OldWrappedX      = IntPtr.Zero;
            _lowLevelStruct.OldPasswordLen   = 0;
            _lowLevelStruct.OldPassword      = IntPtr.Zero;
            _lowLevelStruct.OldPublicDataLen = 0;
            _lowLevelStruct.OldPublicData    = IntPtr.Zero;
            _lowLevelStruct.OldRandomLen     = 0;
            _lowLevelStruct.OldRandomA       = IntPtr.Zero;
            _lowLevelStruct.NewPasswordLen   = 0;
            _lowLevelStruct.NewPassword      = IntPtr.Zero;
            _lowLevelStruct.NewPublicDataLen = 0;
            _lowLevelStruct.NewPublicData    = IntPtr.Zero;
            _lowLevelStruct.NewRandomLen     = 0;
            _lowLevelStruct.NewRandomA       = IntPtr.Zero;

            if (oldWrappedX != null)
            {
                _lowLevelStruct.OldWrappedX = UnmanagedMemory.Allocate(oldWrappedX.Length);
                UnmanagedMemory.Write(_lowLevelStruct.OldWrappedX, oldWrappedX);
                _lowLevelStruct.OldWrappedXLen = ConvertUtils.UInt32FromInt32(oldWrappedX.Length);
            }

            if (oldPassword != null)
            {
                _lowLevelStruct.OldPassword = UnmanagedMemory.Allocate(oldPassword.Length);
                UnmanagedMemory.Write(_lowLevelStruct.OldPassword, oldPassword);
                _lowLevelStruct.OldPasswordLen = ConvertUtils.UInt32FromInt32(oldPassword.Length);
            }

            if (oldPublicData != null)
            {
                _lowLevelStruct.OldPublicData = UnmanagedMemory.Allocate(oldPublicData.Length);
                UnmanagedMemory.Write(_lowLevelStruct.OldPublicData, oldPublicData);
                _lowLevelStruct.OldPublicDataLen = ConvertUtils.UInt32FromInt32(oldPublicData.Length);
            }

            if (oldRandomA != null)
            {
                _lowLevelStruct.OldRandomA = UnmanagedMemory.Allocate(oldRandomA.Length);
                UnmanagedMemory.Write(_lowLevelStruct.OldRandomA, oldRandomA);
                _lowLevelStruct.OldRandomLen = ConvertUtils.UInt32FromInt32(oldRandomA.Length);
            }

            if (newPassword != null)
            {
                _lowLevelStruct.NewPassword = UnmanagedMemory.Allocate(newPassword.Length);
                UnmanagedMemory.Write(_lowLevelStruct.NewPassword, newPassword);
                _lowLevelStruct.NewPasswordLen = ConvertUtils.UInt32FromInt32(newPassword.Length);
            }

            if (newPublicData != null)
            {
                _lowLevelStruct.NewPublicData = UnmanagedMemory.Allocate(newPublicData.Length);
                UnmanagedMemory.Write(_lowLevelStruct.NewPublicData, newPublicData);
                _lowLevelStruct.NewPublicDataLen = ConvertUtils.UInt32FromInt32(newPublicData.Length);
            }

            if (newRandomA != null)
            {
                _lowLevelStruct.NewRandomA = UnmanagedMemory.Allocate(newRandomA.Length);
                UnmanagedMemory.Write(_lowLevelStruct.NewRandomA, newRandomA);
                _lowLevelStruct.NewRandomLen = ConvertUtils.UInt32FromInt32(newRandomA.Length);
            }
        }
        public void _01_BasicSignEncryptAndDecryptVerifyTest()
        {
            if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 1)
            {
                Assert.Inconclusive("Test cannot be executed on this platform");
            }

            CKR rv = CKR.CKR_OK;

            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
            {
                rv = pkcs11.C_Initialize(Settings.InitArgs81);
                if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
                {
                    Assert.Fail(rv.ToString());
                }

                // Find first slot with token present
                ulong slotId = Helpers.GetUsableSlot(pkcs11);

                ulong session = CK.CK_INVALID_HANDLE;
                rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Login as normal user
                rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Generate asymetric key pair
                ulong pubKeyId  = CK.CK_INVALID_HANDLE;
                ulong privKeyId = CK.CK_INVALID_HANDLE;
                rv = Helpers.GenerateKeyPair(pkcs11, session, ref pubKeyId, ref privKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Specify signing mechanism (needs no parameter => no unamanaged memory is needed)
                CK_MECHANISM signingMechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA1_RSA_PKCS);

                // Generate symetric key
                ulong keyId = CK.CK_INVALID_HANDLE;
                rv = Helpers.GenerateKey(pkcs11, session, ref keyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Generate random initialization vector
                byte[] iv = new byte[8];
                rv = pkcs11.C_GenerateRandom(session, iv, Convert.ToUInt64(iv.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Specify encryption mechanism with initialization vector as parameter.
                // Note that CkmUtils.CreateMechanism() automaticaly copies iv into newly allocated unmanaged memory.
                CK_MECHANISM encryptionMechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_CBC, iv);

                byte[] sourceData    = ConvertUtils.Utf8StringToBytes("Passw0rd");
                byte[] signature     = null;
                byte[] encryptedData = null;
                byte[] decryptedData = null;

                // Multipart signing and encryption function C_SignEncryptUpdate can be used i.e. for signing and encryption of streamed data
                using (MemoryStream inputStream = new MemoryStream(sourceData), outputStream = new MemoryStream())
                {
                    // Initialize signing operation
                    rv = pkcs11.C_SignInit(session, ref signingMechanism, privKeyId);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }

                    // Initialize encryption operation
                    rv = pkcs11.C_EncryptInit(session, ref encryptionMechanism, keyId);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }

                    // Prepare buffer for source data part
                    // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
                    byte[] part = new byte[8];

                    // Prepare buffer for encrypted data part
                    // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
                    byte[] encryptedPart    = new byte[8];
                    ulong  encryptedPartLen = Convert.ToUInt64(encryptedPart.Length);

                    // Read input stream with source data
                    int bytesRead = 0;
                    while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0)
                    {
                        // Process each individual source data part
                        encryptedPartLen = Convert.ToUInt64(encryptedPart.Length);
                        rv = pkcs11.C_SignEncryptUpdate(session, part, Convert.ToUInt64(bytesRead), encryptedPart, ref encryptedPartLen);
                        if (rv != CKR.CKR_OK)
                        {
                            Assert.Fail(rv.ToString());
                        }

                        // Append encrypted data part to the output stream
                        outputStream.Write(encryptedPart, 0, Convert.ToInt32(encryptedPartLen));
                    }

                    // Get the length of signature in first call
                    ulong signatureLen = 0;
                    rv = pkcs11.C_SignFinal(session, null, ref signatureLen);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }

                    Assert.IsTrue(signatureLen > 0);

                    // Allocate array for signature
                    signature = new byte[signatureLen];

                    // Get signature in second call
                    rv = pkcs11.C_SignFinal(session, signature, ref signatureLen);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }

                    // Get the length of last encrypted data part in first call
                    byte[] lastEncryptedPart    = null;
                    ulong  lastEncryptedPartLen = 0;
                    rv = pkcs11.C_EncryptFinal(session, null, ref lastEncryptedPartLen);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }

                    // Allocate array for the last encrypted data part
                    lastEncryptedPart = new byte[lastEncryptedPartLen];

                    // Get the last encrypted data part in second call
                    rv = pkcs11.C_EncryptFinal(session, lastEncryptedPart, ref lastEncryptedPartLen);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }

                    // Append the last encrypted data part to the output stream
                    outputStream.Write(lastEncryptedPart, 0, Convert.ToInt32(lastEncryptedPartLen));

                    // Read whole output stream to the byte array so we can compare results more easily
                    encryptedData = outputStream.ToArray();
                }

                // Do something interesting with signature and encrypted data

                // Multipart decryption and verification function C_DecryptVerifyUpdate can be used i.e. for decryption and signature verification of streamed data
                using (MemoryStream inputStream = new MemoryStream(encryptedData), outputStream = new MemoryStream())
                {
                    // Initialize decryption operation
                    rv = pkcs11.C_DecryptInit(session, ref encryptionMechanism, keyId);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }

                    // Initialize verification operation
                    rv = pkcs11.C_VerifyInit(session, ref signingMechanism, pubKeyId);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }

                    // Prepare buffer for encrypted data part
                    // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
                    byte[] encryptedPart = new byte[8];

                    // Prepare buffer for decrypted data part
                    // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
                    byte[] part    = new byte[8];
                    ulong  partLen = Convert.ToUInt64(part.Length);

                    // Read input stream with encrypted data
                    int bytesRead = 0;
                    while ((bytesRead = inputStream.Read(encryptedPart, 0, encryptedPart.Length)) > 0)
                    {
                        // Process each individual encrypted data part
                        partLen = Convert.ToUInt64(part.Length);
                        rv      = pkcs11.C_DecryptVerifyUpdate(session, encryptedPart, Convert.ToUInt64(bytesRead), part, ref partLen);
                        if (rv != CKR.CKR_OK)
                        {
                            Assert.Fail(rv.ToString());
                        }

                        // Append decrypted data part to the output stream
                        outputStream.Write(part, 0, Convert.ToInt32(partLen));
                    }

                    // Get the length of last decrypted data part in first call
                    byte[] lastPart    = null;
                    ulong  lastPartLen = 0;
                    rv = pkcs11.C_DecryptFinal(session, null, ref lastPartLen);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }

                    // Allocate array for the last decrypted data part
                    lastPart = new byte[lastPartLen];

                    // Get the last decrypted data part in second call
                    rv = pkcs11.C_DecryptFinal(session, lastPart, ref lastPartLen);
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }

                    // Append the last decrypted data part to the output stream
                    outputStream.Write(lastPart, 0, Convert.ToInt32(lastPartLen));

                    // Read whole output stream to the byte array so we can compare results more easily
                    decryptedData = outputStream.ToArray();

                    // Verify signature
                    rv = pkcs11.C_VerifyFinal(session, signature, Convert.ToUInt64(signature.Length));
                    if (rv != CKR.CKR_OK)
                    {
                        Assert.Fail(rv.ToString());
                    }
                }

                // Do something interesting with decrypted data and verification result
                Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData));

                // In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter (iv in this case)
                UnmanagedMemory.Free(ref encryptionMechanism.Parameter);
                encryptionMechanism.ParameterLen = 0;

                rv = pkcs11.C_DestroyObject(session, privKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_DestroyObject(session, pubKeyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_DestroyObject(session, keyId);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_Logout(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_CloseSession(session);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                rv = pkcs11.C_Finalize(IntPtr.Zero);
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }
            }
        }
Exemplo n.º 31
0
        public static IEnumerable<HidDevice> GetDevices()
        {
            Guid hidGuid = HidDevice.HIDGuid;

            // Get the list of HID devices
            IntPtr deviceInfoSet = new IntPtr();
            deviceInfoSet = setup.SetupDiGetClassDevs(ref hidGuid, IntPtr.Zero, IntPtr.Zero, setup.DIGCF_PRESENT | setup.DIGCF_DEVICEINTERFACE);

            int memberIndex = 0;
            SP_DEVICE_INTERFACE_DATA MyDeviceInterfaceData = new SP_DEVICE_INTERFACE_DATA();
            MyDeviceInterfaceData.cbSize = Marshal.SizeOf(MyDeviceInterfaceData);

            bool success;
            bool lastDevice = false;
            int bufferSize = 0;
            UnmanagedMemory detailDataBuffer;
            List<HidDevice> devicePathNames = new List<HidDevice>();
            bool deviceFound = false;

            do
            {
                success = setup.SetupDiEnumDeviceInterfaces(deviceInfoSet,
                    IntPtr.Zero,
                    ref hidGuid,
                    memberIndex,
                    ref MyDeviceInterfaceData);

                if (!success)
                {
                    lastDevice = true;
                }
                else
                {
                    // First call to get size of data buffer
                    success = setup.SetupDiGetDeviceInterfaceDetail(deviceInfoSet,
                        ref MyDeviceInterfaceData,
                        IntPtr.Zero,
                        0,
                        ref bufferSize,
                        IntPtr.Zero);

                    // Allocate memory for the SP_DEVICE_INTERFACE_DETAIL_DATA structure using the returned buffer size
                    detailDataBuffer = new UnmanagedMemory(bufferSize);

                    // Store cbSize in the first bytes of the array. The number of bytes varies with 32- and 64-bit systems.

                    Marshal.WriteInt32(detailDataBuffer.MemoryPointer, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8);

                    // Call SetupDiGetDeviceInterfaceDetail again.
                    // This time, pass a pointer to DetailDataBuffer
                    // and the returned required buffer size.
                    success = setup.SetupDiGetDeviceInterfaceDetail
                        (deviceInfoSet,
                        ref MyDeviceInterfaceData,
                        detailDataBuffer.MemoryPointer,
                        bufferSize,
                        ref bufferSize,
                        IntPtr.Zero);

                    //diDetail.cbSize = (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8;
                    //SP_DEVICE_INTERFACE_DETAIL_DATA diDetail = new SP_DEVICE_INTERFACE_DETAIL_DATA();
                    //diDetail.cbSize = Marshal.SizeOf(diDetail);
                    //success = setup.SetupDiGetDeviceInterfaceDetail
                    //    (deviceInfoSet,
                    //    ref MyDeviceInterfaceData,
                    //    ref diDetail,
                    //    diDetail.cbSize,
                    //    ref bufferSize,
                    //    IntPtr.Zero);

                    IntPtr pDevicePathName = detailDataBuffer.MemoryPointer + 4;
                    string devicePathName = Marshal.PtrToStringAuto(pDevicePathName);

                    HidDevice newDevice = new HidDevice(devicePathName);
                    devicePathNames.Add(newDevice);
                    deviceFound = true;
                }
                memberIndex++;
            } while (!lastDevice);

            // Destroy the device Info Set to cleanup memory
            setup.SetupDiDestroyDeviceInfoList(deviceInfoSet);

            return devicePathNames;

        }
Exemplo n.º 32
0
 public unsafe void Deserialize(byte[] buffer, int offset)
 {
     fixed(byte *ptr = buffer)
     using (var pointer = new UnmanagedMemory(new IntPtr(ptr + offset), buffer.Length - offset))
         Deserialize(pointer);
 }