Пример #1
0
        /// <summary>
        /// Initializes a new instance of the CkKipParams class.
        /// </summary>
        /// <param name='mechanism'>Underlying cryptographic mechanism (CKM)</param>
        /// <param name='key'>Handle to a key that will contribute to the entropy of the derived key (CKM_KIP_DERIVE) or will be used in the MAC operation (CKM_KIP_MAC)</param>
        /// <param name='seed'>Input seed</param>
        public CkKipParams(NativeULong?mechanism, ObjectHandle key, byte[] seed)
        {
            _lowLevelStruct.Mechanism = IntPtr.Zero;
            _lowLevelStruct.Key       = 0;
            _lowLevelStruct.Seed      = IntPtr.Zero;
            _lowLevelStruct.SeedLen   = 0;

            if (mechanism != null)
            {
                byte[] bytes = NativeLongUtils.ConvertToByteArray(mechanism.Value);
                _lowLevelStruct.Mechanism = UnmanagedMemory.Allocate(bytes.Length);
                UnmanagedMemory.Write(_lowLevelStruct.Mechanism, bytes);
            }

            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            _lowLevelStruct.Key = key.ObjectId;

            if (seed != null)
            {
                _lowLevelStruct.Seed = UnmanagedMemory.Allocate(seed.Length);
                UnmanagedMemory.Write(_lowLevelStruct.Seed, seed);
                _lowLevelStruct.SeedLen = NativeLongUtils.ConvertFromInt32(seed.Length);
            }
        }
Пример #2
0
        /// <summary>
        /// Initializes a new instance of the CkCcmParams class.
        /// </summary>
        /// <param name="dataLen">Length of the data</param>
        /// <param name="nonce">Nonce</param>
        /// <param name="aad">Additional authentication data</param>
        /// <param name="macLen">Length of the MAC (output following cipher text) in bytes</param>
        public CkCcmParams(NativeULong dataLen, byte[] nonce, byte[] aad, NativeULong macLen)
        {
            _lowLevelStruct.DataLen  = 0;
            _lowLevelStruct.Nonce    = IntPtr.Zero;
            _lowLevelStruct.NonceLen = 0;
            _lowLevelStruct.AAD      = IntPtr.Zero;
            _lowLevelStruct.AADLen   = 0;
            _lowLevelStruct.MACLen   = 0;

            _lowLevelStruct.DataLen = dataLen;

            if (nonce != null)
            {
                _lowLevelStruct.Nonce = UnmanagedMemory.Allocate(nonce.Length);
                UnmanagedMemory.Write(_lowLevelStruct.Nonce, nonce);
                _lowLevelStruct.NonceLen = NativeLongUtils.ConvertFromInt32(nonce.Length);
            }

            if (aad != null)
            {
                _lowLevelStruct.AAD = UnmanagedMemory.Allocate(aad.Length);
                UnmanagedMemory.Write(_lowLevelStruct.AAD, aad);
                _lowLevelStruct.AADLen = NativeLongUtils.ConvertFromInt32(aad.Length);
            }

            _lowLevelStruct.MACLen = macLen;
        }
Пример #3
0
        public void _02_UintAttributeTest()
        {
            Helpers.CheckPlatform();

            NativeULong originalValue = NativeLongUtils.ConvertFromCKO(CKO.CKO_DATA);
            // Create attribute with NativeULong value
            CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_CLASS, originalValue);

            Assert.IsTrue(attr.type == NativeLongUtils.ConvertFromCKA(CKA.CKA_CLASS));
            Assert.IsTrue(attr.value != IntPtr.Zero);
            Assert.IsTrue(attr.valueLen == NativeLongUtils.ConvertFromInt32(UnmanagedMemory.SizeOf(typeof(NativeULong))));

            NativeULong recoveredValue = 0;

            // Read the value of attribute
            CkaUtils.ConvertValue(ref attr, out recoveredValue);
            Assert.IsTrue(originalValue == recoveredValue);

            // Free attribute value
            UnmanagedMemory.Free(ref attr.value);
            attr.valueLen = 0;
            Assert.IsTrue(attr.type == NativeLongUtils.ConvertFromCKA(CKA.CKA_CLASS));
            Assert.IsTrue(attr.value == IntPtr.Zero);
            Assert.IsTrue(attr.valueLen == 0);
        }
Пример #4
0
        /// <summary>
        /// Initializes a new instance of the CkTlsPrfParams class.
        /// </summary>
        /// <param name='seed'>Input seed</param>
        /// <param name='label'>Identifying label</param>
        /// <param name='outputLen'>Length in bytes that the output to be created shall have</param>
        public CkTlsPrfParams(byte[] seed, byte[] label, NativeULong outputLen)
        {
            _lowLevelStruct.Seed      = IntPtr.Zero;
            _lowLevelStruct.SeedLen   = 0;
            _lowLevelStruct.Label     = IntPtr.Zero;
            _lowLevelStruct.LabelLen  = 0;
            _lowLevelStruct.Output    = IntPtr.Zero;
            _lowLevelStruct.OutputLen = IntPtr.Zero;

            if (seed != null)
            {
                _lowLevelStruct.Seed = UnmanagedMemory.Allocate(seed.Length);
                UnmanagedMemory.Write(_lowLevelStruct.Seed, seed);
                _lowLevelStruct.SeedLen = NativeLongUtils.ConvertFromInt32(seed.Length);
            }

            if (label != null)
            {
                _lowLevelStruct.Label = UnmanagedMemory.Allocate(label.Length);
                UnmanagedMemory.Write(_lowLevelStruct.Label, label);
                _lowLevelStruct.LabelLen = NativeLongUtils.ConvertFromInt32(label.Length);
            }

            if (outputLen < 1)
            {
                throw new ArgumentException("Value has to be positive number", "outputLen");
            }

            _lowLevelStruct.Output = UnmanagedMemory.Allocate(NativeLongUtils.ConvertToInt32(outputLen));

            byte[] outputLenBytes = NativeLongUtils.ConvertToByteArray(outputLen);
            _lowLevelStruct.OutputLen = UnmanagedMemory.Allocate(outputLenBytes.Length);
            UnmanagedMemory.Write(_lowLevelStruct.OutputLen, outputLenBytes);
        }
Пример #5
0
        public void _03_StructureParameterTest()
        {
            Helpers.CheckPlatform();

            byte[]        data = new byte[24];
            System.Random rng  = new Random();
            rng.NextBytes(data);

            // Specify mechanism parameters
            // Note that we are allocating unmanaged memory that will have to be freed later
            CK_KEY_DERIVATION_STRING_DATA parameter = new CK_KEY_DERIVATION_STRING_DATA();

            parameter.Data = UnmanagedMemory.Allocate(data.Length);
            UnmanagedMemory.Write(parameter.Data, data);
            parameter.Len = NativeLongUtils.ConvertFromInt32(data.Length);

            // Create mechanism with the structure as parameter
            // Note that CkmUtils.CreateMechanism() automaticaly copies mechanismParams into newly allocated unmanaged memory
            CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_XOR_BASE_AND_DATA, parameter);

            Assert.IsTrue(mechanism.Mechanism == NativeLongUtils.ConvertFromCKM(CKM.CKM_XOR_BASE_AND_DATA));
            Assert.IsTrue(mechanism.Parameter != IntPtr.Zero);
            Assert.IsTrue(mechanism.ParameterLen == NativeLongUtils.ConvertFromInt32(UnmanagedMemory.SizeOf(typeof(CK_KEY_DERIVATION_STRING_DATA))));

            // Free all unmanaged memory we previously allocated
            UnmanagedMemory.Free(ref parameter.Data);
            parameter.Len = 0;

            // Free unmanaged memory taken by mechanism parameter
            UnmanagedMemory.Free(ref mechanism.Parameter);
            mechanism.ParameterLen = 0;
            Assert.IsTrue(mechanism.Mechanism == NativeLongUtils.ConvertFromCKM(CKM.CKM_XOR_BASE_AND_DATA));
            Assert.IsTrue(mechanism.Parameter == IntPtr.Zero);
            Assert.IsTrue(mechanism.ParameterLen == 0);
        }
Пример #6
0
        public void _10_CustomAttributeTest()
        {
            Helpers.CheckPlatform();

            byte[] originalValue = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 };

            // Create attribute without the value
            CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_VALUE);

            Assert.IsTrue(attr.type == NativeLongUtils.ConvertFromCKA(CKA.CKA_VALUE));
            Assert.IsTrue(attr.value == IntPtr.Zero);
            Assert.IsTrue(attr.valueLen == 0);

            // Allocate unmanaged memory for attribute value..
            attr.value = UnmanagedMemory.Allocate(originalValue.Length);
            // ..then set the value of attribute..
            UnmanagedMemory.Write(attr.value, originalValue);
            // ..and finally set the length of attribute value.
            attr.valueLen = NativeLongUtils.ConvertFromInt32(originalValue.Length);
            Assert.IsTrue(attr.type == NativeLongUtils.ConvertFromCKA(CKA.CKA_VALUE));
            Assert.IsTrue(attr.value != IntPtr.Zero);
            Assert.IsTrue(attr.valueLen == NativeLongUtils.ConvertFromInt32(originalValue.Length));

            // Read the value of attribute
            byte[] recoveredValue = UnmanagedMemory.Read(attr.value, NativeLongUtils.ConvertToInt32(attr.valueLen));
            Assert.IsTrue(ConvertUtils.BytesToBase64String(originalValue) == ConvertUtils.BytesToBase64String(recoveredValue));

            // Free attribute value
            UnmanagedMemory.Free(ref attr.value);
            attr.valueLen = 0;
            Assert.IsTrue(attr.type == NativeLongUtils.ConvertFromCKA(CKA.CKA_VALUE));
            Assert.IsTrue(attr.value == IntPtr.Zero);
            Assert.IsTrue(attr.valueLen == 0);
        }
Пример #7
0
        public void _04_StringAttributeTest()
        {
            Helpers.CheckPlatform();

            string originalValue = "Hello world";
            // Create attribute with string value
            CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_LABEL, originalValue);

            Assert.IsTrue(attr.type == NativeLongUtils.ConvertFromCKA(CKA.CKA_LABEL));
            Assert.IsTrue(attr.value != IntPtr.Zero);
            Assert.IsTrue(attr.valueLen == NativeLongUtils.ConvertFromInt32(originalValue.Length));

            string recoveredValue = null;

            // Read the value of attribute
            CkaUtils.ConvertValue(ref attr, out recoveredValue);
            Assert.IsTrue(originalValue == recoveredValue);

            // Free attribute value
            UnmanagedMemory.Free(ref attr.value);
            attr.valueLen = 0;
            Assert.IsTrue(attr.type == NativeLongUtils.ConvertFromCKA(CKA.CKA_LABEL));
            Assert.IsTrue(attr.value == IntPtr.Zero);
            Assert.IsTrue(attr.valueLen == 0);

            // Create attribute with null string value
            attr = CkaUtils.CreateAttribute(CKA.CKA_LABEL, (string)null);
            Assert.IsTrue(attr.type == NativeLongUtils.ConvertFromCKA(CKA.CKA_LABEL));
            Assert.IsTrue(attr.value == IntPtr.Zero);
            Assert.IsTrue(attr.valueLen == 0);
        }
Пример #8
0
        public void _05_ByteArrayAttributeTest()
        {
            Helpers.CheckPlatform();

            byte[] originalValue = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 };
            // Create attribute with byte array value
            CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_ID, originalValue);

            Assert.IsTrue(attr.type == NativeLongUtils.ConvertFromCKA(CKA.CKA_ID));
            Assert.IsTrue(attr.value != IntPtr.Zero);
            Assert.IsTrue(attr.valueLen == NativeLongUtils.ConvertFromInt32(originalValue.Length));

            byte[] recoveredValue = null;
            // Read the value of attribute
            CkaUtils.ConvertValue(ref attr, out recoveredValue);
            Assert.IsTrue(ConvertUtils.BytesToBase64String(originalValue) == ConvertUtils.BytesToBase64String(recoveredValue));

            // Free attribute value
            UnmanagedMemory.Free(ref attr.value);
            attr.valueLen = 0;
            Assert.IsTrue(attr.type == NativeLongUtils.ConvertFromCKA(CKA.CKA_ID));
            Assert.IsTrue(attr.value == IntPtr.Zero);
            Assert.IsTrue(attr.valueLen == 0);

            // Create attribute with null byte array value
            attr = CkaUtils.CreateAttribute(CKA.CKA_ID, (byte[])null);
            Assert.IsTrue(attr.type == NativeLongUtils.ConvertFromCKA(CKA.CKA_ID));
            Assert.IsTrue(attr.value == IntPtr.Zero);
            Assert.IsTrue(attr.valueLen == 0);
        }
Пример #9
0
        /// <summary>
        /// Initializes a new instance of the CkGcmParams class.
        /// </summary>
        /// <param name="iv">Initialization vector</param>
        /// <param name="ivBits">Member is defined in PKCS#11 v2.40e1 headers but the description is not present in the specification</param>
        /// <param name="aad">Additional authentication data</param>
        /// <param name="tagBits">Length of authentication tag (output following cipher text) in bits</param>
        public CkGcmParams(byte[] iv, NativeULong ivBits, byte[] aad, NativeULong tagBits)
        {
            _lowLevelStruct.Iv      = IntPtr.Zero;
            _lowLevelStruct.IvLen   = 0;
            _lowLevelStruct.IvBits  = 0; // TODO - Fix description when fixed in PKCS#11 specification
            _lowLevelStruct.AAD     = IntPtr.Zero;
            _lowLevelStruct.AADLen  = 0;
            _lowLevelStruct.TagBits = 0;

            if (iv != null)
            {
                _lowLevelStruct.Iv = UnmanagedMemory.Allocate(iv.Length);
                UnmanagedMemory.Write(_lowLevelStruct.Iv, iv);
                _lowLevelStruct.IvLen = NativeLongUtils.ConvertFromInt32(iv.Length);
            }

            _lowLevelStruct.IvBits = ivBits;

            if (aad != null)
            {
                _lowLevelStruct.AAD = UnmanagedMemory.Allocate(aad.Length);
                UnmanagedMemory.Write(_lowLevelStruct.AAD, aad);
                _lowLevelStruct.AADLen = NativeLongUtils.ConvertFromInt32(aad.Length);
            }

            _lowLevelStruct.TagBits = tagBits;
        }
Пример #10
0
        /// <summary>
        /// Initializes a new instance of the CkTlsKdfParams class.
        /// </summary>
        /// <param name="prfMechanism">Hash mechanism used in the TLS 1.2 PRF construct or CKM_TLS_PRF to use with the TLS 1.0 and 1.1 PRF construct (CKM)</param>
        /// <param name="label">Label for this key derivation</param>
        /// <param name="randomInfo">Random data for the key derivation</param>
        /// <param name="contextData">Context data for this key derivation</param>
        public CkTlsKdfParams(NativeULong prfMechanism, byte[] label, CkSsl3RandomData randomInfo, byte[] contextData)
        {
            _lowLevelStruct.Label             = IntPtr.Zero;
            _lowLevelStruct.LabelLength       = 0;
            _lowLevelStruct.ContextData       = IntPtr.Zero;
            _lowLevelStruct.ContextDataLength = 0;

            if (randomInfo == null)
            {
                throw new ArgumentNullException("randomInfo");
            }

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

            _lowLevelStruct.PrfMechanism = prfMechanism;

            if (label != null)
            {
                _lowLevelStruct.Label = UnmanagedMemory.Allocate(label.Length);
                UnmanagedMemory.Write(_lowLevelStruct.Label, label);
                _lowLevelStruct.LabelLength = NativeLongUtils.ConvertFromInt32(label.Length);
            }

            _lowLevelStruct.RandomInfo = (CK_SSL3_RANDOM_DATA)_randomInfo.ToMarshalableStructure();

            if (contextData != null)
            {
                _lowLevelStruct.ContextData = UnmanagedMemory.Allocate(contextData.Length);
                UnmanagedMemory.Write(_lowLevelStruct.ContextData, contextData);
                _lowLevelStruct.ContextDataLength = NativeLongUtils.ConvertFromInt32(contextData.Length);
            }
        }
Пример #11
0
        /// <summary>
        /// Generates symetric key.
        /// </summary>
        /// <param name='pkcs11'>Initialized PKCS11 wrapper</param>
        /// <param name='session'>Read-write session with user logged in</param>
        /// <param name='keyId'>Output parameter for key object handle</param>
        /// <returns>Return value of C_GenerateKey</returns>
        public static CKR GenerateKey(Pkcs11 pkcs11, NativeULong session, ref NativeULong keyId)
        {
            CKR rv = CKR.CKR_OK;

            // Prepare attribute template of new key
            CK_ATTRIBUTE[] template = new CK_ATTRIBUTE[6];
            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);
            template[4] = CkaUtils.CreateAttribute(CKA.CKA_DERIVE, true);
            template[5] = CkaUtils.CreateAttribute(CKA.CKA_EXTRACTABLE, 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
            rv = pkcs11.C_GenerateKey(session, ref mechanism, template, NativeLongUtils.ConvertFromInt32(template.Length), ref keyId);

            // 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;
            }

            return(rv);
        }
        /// <summary>
        /// Initializes a new instance of the CkAriaCbcEncryptDataParams class.
        /// </summary>
        /// <param name='iv'>IV value (16 bytes)</param>
        /// <param name='data'>Data to encrypt</param>
        public CkAriaCbcEncryptDataParams(byte[] iv, byte[] data)
        {
            _lowLevelStruct.Iv     = new byte[16];
            _lowLevelStruct.Data   = IntPtr.Zero;
            _lowLevelStruct.Length = 0;

            if (iv == null)
            {
                throw new ArgumentNullException("iv");
            }

            if (iv.Length != 16)
            {
                throw new ArgumentOutOfRangeException("iv", "Array has to be 16 bytes long");
            }

            Array.Copy(iv, _lowLevelStruct.Iv, iv.Length);

            if (data != null)
            {
                _lowLevelStruct.Data = UnmanagedMemory.Allocate(data.Length);
                UnmanagedMemory.Write(_lowLevelStruct.Data, data);
                _lowLevelStruct.Length = NativeLongUtils.ConvertFromInt32(data.Length);
            }
        }
Пример #13
0
        public void _02_ByteArrayParameterTest()
        {
            Helpers.CheckPlatform();

            byte[]        parameter = new byte[16];
            System.Random rng       = new Random();
            rng.NextBytes(parameter);

            // Create mechanism with the byte array parameter
            // Note that CkmUtils.CreateMechanism() automaticaly copies mechanismParams into newly allocated unmanaged memory
            CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_AES_CBC, parameter);

            Assert.IsTrue(mechanism.Mechanism == NativeLongUtils.ConvertFromCKM(CKM.CKM_AES_CBC));
            Assert.IsTrue(mechanism.Parameter != IntPtr.Zero);
            Assert.IsTrue(mechanism.ParameterLen == NativeLongUtils.ConvertFromInt32(parameter.Length));

            // Free unmanaged memory taken by mechanism parameter
            UnmanagedMemory.Free(ref mechanism.Parameter);
            mechanism.ParameterLen = 0;
            Assert.IsTrue(mechanism.Mechanism == NativeLongUtils.ConvertFromCKM(CKM.CKM_AES_CBC));
            Assert.IsTrue(mechanism.Parameter == IntPtr.Zero);
            Assert.IsTrue(mechanism.ParameterLen == 0);

            parameter = null;

            // Create mechanism with null byte array parameter
            mechanism = CkmUtils.CreateMechanism(CKM.CKM_AES_CBC, parameter);
            Assert.IsTrue(mechanism.Mechanism == NativeLongUtils.ConvertFromCKM(CKM.CKM_AES_CBC));
            Assert.IsTrue(mechanism.Parameter == IntPtr.Zero);
            Assert.IsTrue(mechanism.ParameterLen == 0);
        }
Пример #14
0
        /// <summary>
        /// Generates asymetric key pair.
        /// </summary>
        /// <param name='pkcs11'>Initialized PKCS11 wrapper</param>
        /// <param name='session'>Read-write session with user logged in</param>
        /// <param name='pubKeyId'>Output parameter for public key object handle</param>
        /// <param name='privKeyId'>Output parameter for private key object handle</param>
        /// <returns>Return value of C_GenerateKeyPair</returns>
        public static CKR GenerateKeyPair(Pkcs11 pkcs11, NativeULong session, ref NativeULong pubKeyId, ref NativeULong privKeyId)
        {
            CKR rv = CKR.CKR_OK;

            // 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, NativeLongUtils.ConvertFromInt32(ckaId.Length));
            if (rv != CKR.CKR_OK)
            {
                return(rv);
            }

            // 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
            rv = pkcs11.C_GenerateKeyPair(session, ref mechanism, pubKeyTemplate, NativeLongUtils.ConvertFromInt32(pubKeyTemplate.Length), privKeyTemplate, NativeLongUtils.ConvertFromInt32(privKeyTemplate.Length), ref pubKeyId, ref privKeyId);

            // 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;
            }

            return(rv);
        }
Пример #15
0
        public void _01_BasicSetPinTest()
        {
            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);

                // 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());
                }

                // Set new pin for the logged in user
                rv = pkcs11.C_SetPIN(session, Settings.NormalUserPinArray, NativeLongUtils.ConvertFromInt32(Settings.NormalUserPinArray.Length), Settings.NormalUserPinArray, NativeLongUtils.ConvertFromInt32(Settings.NormalUserPinArray.Length));
                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());
                }
            }
        }
Пример #16
0
        /// <summary>
        /// Initializes a new instance of the CkCmsSigParams class.
        /// </summary>
        /// <param name='certificateHandle'>Object handle for a certificate associated with the signing key</param>
        /// <param name='signingMechanism'>Mechanism to use when signing a constructed CMS SignedAttributes value</param>
        /// <param name='digestMechanism'>Mechanism to use when digesting the data</param>
        /// <param name='contentType'>String indicating complete MIME Content-type of message to be signed or null if the message is a MIME object</param>
        /// <param name='requestedAttributes'>DER-encoded list of CMS Attributes the caller requests to be included in the signed attributes</param>
        /// <param name='requiredAttributes'>DER-encoded list of CMS Attributes (with accompanying values) required to be included in the resulting signed attributes</param>
        public CkCmsSigParams(ObjectHandle certificateHandle, NativeULong?signingMechanism, NativeULong?digestMechanism, string contentType, byte[] requestedAttributes, byte[] requiredAttributes)
        {
            _lowLevelStruct.CertificateHandle      = CK.CK_INVALID_HANDLE;
            _lowLevelStruct.SigningMechanism       = IntPtr.Zero;
            _lowLevelStruct.DigestMechanism        = IntPtr.Zero;
            _lowLevelStruct.ContentType            = IntPtr.Zero;
            _lowLevelStruct.RequestedAttributes    = IntPtr.Zero;
            _lowLevelStruct.RequestedAttributesLen = 0;
            _lowLevelStruct.RequiredAttributes     = IntPtr.Zero;
            _lowLevelStruct.RequiredAttributesLen  = 0;

            if (certificateHandle == null)
            {
                throw new ArgumentNullException("certificateHandle");
            }

            _lowLevelStruct.CertificateHandle = certificateHandle.ObjectId;

            if (signingMechanism != null)
            {
                byte[] bytes = NativeLongUtils.ConvertToByteArray(signingMechanism.Value);
                _lowLevelStruct.SigningMechanism = UnmanagedMemory.Allocate(bytes.Length);
                UnmanagedMemory.Write(_lowLevelStruct.SigningMechanism, bytes);
            }

            if (digestMechanism != null)
            {
                byte[] bytes = NativeLongUtils.ConvertToByteArray(digestMechanism.Value);
                _lowLevelStruct.DigestMechanism = UnmanagedMemory.Allocate(bytes.Length);
                UnmanagedMemory.Write(_lowLevelStruct.DigestMechanism, bytes);
            }

            if (contentType != null)
            {
                byte[] bytes = ConvertUtils.Utf8StringToBytes(contentType);
                Array.Resize(ref bytes, bytes.Length + 1);
                bytes[bytes.Length - 1] = 0;

                _lowLevelStruct.ContentType = UnmanagedMemory.Allocate(bytes.Length);
                UnmanagedMemory.Write(_lowLevelStruct.ContentType, bytes);
            }

            if (requestedAttributes != null)
            {
                _lowLevelStruct.RequestedAttributes = UnmanagedMemory.Allocate(requestedAttributes.Length);
                UnmanagedMemory.Write(_lowLevelStruct.RequestedAttributes, requestedAttributes);
                _lowLevelStruct.RequestedAttributesLen = NativeLongUtils.ConvertFromInt32(requestedAttributes.Length);
            }

            if (requiredAttributes != null)
            {
                _lowLevelStruct.RequiredAttributes = UnmanagedMemory.Allocate(requiredAttributes.Length);
                UnmanagedMemory.Write(_lowLevelStruct.RequiredAttributes, requiredAttributes);
                _lowLevelStruct.RequiredAttributesLen = NativeLongUtils.ConvertFromInt32(requiredAttributes.Length);
            }
        }
        /// <summary>
        /// Initializes a new instance of the CkKeyDerivationStringData class.
        /// </summary>
        /// <param name='data'>Byte string used as the input for derivation mechanism</param>
        public CkKeyDerivationStringData(byte[] data)
        {
            _lowLevelStruct.Data = IntPtr.Zero;
            _lowLevelStruct.Len  = 0;

            if (data != null)
            {
                _lowLevelStruct.Data = UnmanagedMemory.Allocate(data.Length);
                UnmanagedMemory.Write(_lowLevelStruct.Data, data);
                _lowLevelStruct.Len = NativeLongUtils.ConvertFromInt32(data.Length);
            }
        }
Пример #18
0
        /// <summary>
        /// Initializes a new instance of the CkEcmqvDeriveParams class.
        /// </summary>>
        /// <param name='kdf'>Key derivation function used on the shared secret value (CKD)</param>
        /// <param name='sharedData'>Some data shared between the two parties</param>
        /// <param name='publicData'>Other party's first EC public key value</param>
        /// <param name='privateDataLen'>The length in bytes of the second EC private key</param>
        /// <param name='privateData'>Key handle for second EC private key value</param>
        /// <param name='publicData2'>Other party's second EC public key value</param>
        /// <param name='publicKey'>Handle to the first party's ephemeral public key</param>
        public CkEcmqvDeriveParams(NativeULong kdf, byte[] sharedData, byte[] publicData, NativeULong privateDataLen, ObjectHandle privateData, byte[] publicData2, ObjectHandle publicKey)
        {
            _lowLevelStruct.Kdf            = 0;
            _lowLevelStruct.SharedDataLen  = 0;
            _lowLevelStruct.SharedData     = IntPtr.Zero;
            _lowLevelStruct.PublicDataLen  = 0;
            _lowLevelStruct.PublicData     = IntPtr.Zero;
            _lowLevelStruct.PrivateDataLen = 0;
            _lowLevelStruct.PrivateData    = 0;
            _lowLevelStruct.PublicDataLen2 = 0;
            _lowLevelStruct.PublicData2    = IntPtr.Zero;
            _lowLevelStruct.PublicKey      = 0;

            _lowLevelStruct.Kdf = kdf;

            if (sharedData != null)
            {
                _lowLevelStruct.SharedData = UnmanagedMemory.Allocate(sharedData.Length);
                UnmanagedMemory.Write(_lowLevelStruct.SharedData, sharedData);
                _lowLevelStruct.SharedDataLen = NativeLongUtils.ConvertFromInt32(sharedData.Length);
            }

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

            _lowLevelStruct.PrivateDataLen = privateDataLen;

            if (privateData == null)
            {
                throw new ArgumentNullException("privateData");
            }

            _lowLevelStruct.PrivateData = privateData.ObjectId;

            if (publicData2 != null)
            {
                _lowLevelStruct.PublicData2 = UnmanagedMemory.Allocate(publicData2.Length);
                UnmanagedMemory.Write(_lowLevelStruct.PublicData2, publicData2);
                _lowLevelStruct.PublicDataLen2 = NativeLongUtils.ConvertFromInt32(publicData2.Length);
            }

            if (publicKey == null)
            {
                throw new ArgumentNullException("publicKey");
            }

            _lowLevelStruct.PublicKey = publicKey.ObjectId;
        }
        public void _02_GenerateRandomTest()
        {
            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);

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

                // Allocate array for random bytes
                byte[] randomData = new byte[256];

                // Get random or pseudo-random data
                rv = pkcs11.C_GenerateRandom(session, randomData, NativeLongUtils.ConvertFromInt32(randomData.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Do something interesting with random data

                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());
                }
            }
        }
Пример #20
0
        /// <summary>
        /// Initializes a new instance of the CkKeyWrapSetOaepParams class.
        /// </summary>
        /// <param name='bc'>Block contents byte</param>
        /// <param name='x'>Concatenation of hash of plaintext data (if present) and extra data (if present)</param>
        public CkKeyWrapSetOaepParams(byte bc, byte[] x)
        {
            _lowLevelStruct.BC   = 0;
            _lowLevelStruct.X    = IntPtr.Zero;
            _lowLevelStruct.XLen = 0;

            _lowLevelStruct.BC = bc;

            if (x != null)
            {
                _lowLevelStruct.X = UnmanagedMemory.Allocate(x.Length);
                UnmanagedMemory.Write(_lowLevelStruct.X, x);
                _lowLevelStruct.XLen = NativeLongUtils.ConvertFromInt32(x.Length);
            }
        }
Пример #21
0
        /// <summary>
        /// Initializes a new instance of the CkOtpParam class.
        /// </summary>
        /// <param name='type'>Parameter type</param>
        /// <param name='value'>Value of the parameter</param>
        public CkOtpParam(NativeULong type, byte[] value)
        {
            _lowLevelStruct.Type     = 0;
            _lowLevelStruct.Value    = IntPtr.Zero;
            _lowLevelStruct.ValueLen = 0;

            _lowLevelStruct.Type = type;

            if (value != null)
            {
                _lowLevelStruct.Value = UnmanagedMemory.Allocate(value.Length);
                UnmanagedMemory.Write(_lowLevelStruct.Value, value);
                _lowLevelStruct.ValueLen = NativeLongUtils.ConvertFromInt32(value.Length);
            }
        }
        public void _01_SeedRandomTest()
        {
            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);

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

                // Mix additional seed material into the token's random number generator
                byte[] seed = ConvertUtils.Utf8StringToBytes("Additional seed material");
                rv = pkcs11.C_SeedRandom(session, seed, NativeLongUtils.ConvertFromInt32(seed.Length));
                if (rv != CKR.CKR_OK)
                {
                    Assert.Fail(rv.ToString());
                }

                // Do something interesting with random number generator

                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());
                }
            }
        }
Пример #23
0
        /// <summary>
        /// Initializes a new instance of the CkEcdhAesKeyWrapParams class.
        /// </summary>
        /// <param name="aesKeyBits">Length of the temporary AES key in bits</param>
        /// <param name="kdf">Key derivation function used on the shared secret value to generate AES key (CKD)</param>
        /// <param name="sharedData">Data shared between the two parties</param>
        public CkEcdhAesKeyWrapParams(NativeULong aesKeyBits, NativeULong kdf, byte[] sharedData)
        {
            _lowLevelStruct.AESKeyBits    = 0;
            _lowLevelStruct.Kdf           = 0;
            _lowLevelStruct.SharedData    = IntPtr.Zero;
            _lowLevelStruct.SharedDataLen = 0;

            _lowLevelStruct.AESKeyBits = aesKeyBits;
            _lowLevelStruct.Kdf        = kdf;

            if (sharedData != null)
            {
                _lowLevelStruct.SharedData = UnmanagedMemory.Allocate(sharedData.Length);
                UnmanagedMemory.Write(_lowLevelStruct.SharedData, sharedData);
                _lowLevelStruct.SharedDataLen = NativeLongUtils.ConvertFromInt32(sharedData.Length);
            }
        }
Пример #24
0
        /// <summary>
        /// Initializes a new instance of the CkDsaParameterGenParam class
        /// </summary>
        /// <param name="hash">Mechanism value for the base hash used in PQG generation (CKM)</param>
        /// <param name="seed">Seed value used to generate PQ and G</param>
        /// <param name="index">Index value for generating G</param>
        public CkDsaParameterGenParam(NativeULong hash, byte[] seed, NativeULong index)
        {
            _lowLevelStruct.Hash    = 0;
            _lowLevelStruct.Seed    = IntPtr.Zero;
            _lowLevelStruct.SeedLen = 0;
            _lowLevelStruct.Index   = 0;

            _lowLevelStruct.Hash = hash;

            if (seed != null)
            {
                _lowLevelStruct.Seed = UnmanagedMemory.Allocate(seed.Length);
                UnmanagedMemory.Write(_lowLevelStruct.Seed, seed);
                _lowLevelStruct.SeedLen = NativeLongUtils.ConvertFromInt32(seed.Length);
            }

            _lowLevelStruct.Index = index;
        }
Пример #25
0
        /// <summary>
        /// Initializes a new instance of the CkRc5CbcParams class.
        /// </summary>
        /// <param name='wordsize'>Wordsize of RC5 cipher in bytes</param>
        /// <param name='rounds'>Number of rounds of RC5 encipherment</param>
        /// <param name='iv'>Initialization vector (IV) for CBC encryption</param>
        public CkRc5CbcParams(NativeULong wordsize, NativeULong rounds, byte[] iv)
        {
            _lowLevelStruct.Wordsize = 0;
            _lowLevelStruct.Rounds   = 0;
            _lowLevelStruct.Iv       = IntPtr.Zero;
            _lowLevelStruct.IvLen    = 0;

            _lowLevelStruct.Wordsize = wordsize;

            _lowLevelStruct.Rounds = rounds;

            if (iv != null)
            {
                _lowLevelStruct.Iv = UnmanagedMemory.Allocate(iv.Length);
                UnmanagedMemory.Write(_lowLevelStruct.Iv, iv);
                _lowLevelStruct.IvLen = NativeLongUtils.ConvertFromInt32(iv.Length);
            }
        }
        /// <summary>
        /// Initializes a new instance of the CkX942Dh2DeriveParams class.
        /// </summary>
        /// <param name='kdf'>Key derivation function used on the shared secret value (CKD)</param>
        /// <param name='otherInfo'>Some data shared between the two parties</param>
        /// <param name='publicData'>Other party's first X9.42 Diffie-Hellman public key value</param>
        /// <param name='privateDataLen'>The length in bytes of the second X9.42 Diffie-Hellman private key</param>
        /// <param name='privateData'>Key handle for second X9.42 Diffie-Hellman private key value</param>
        /// <param name='publicData2'>Other party's second X9.42 Diffie-Hellman public key value</param>
        public CkX942Dh2DeriveParams(NativeULong kdf, byte[] otherInfo, byte[] publicData, NativeULong privateDataLen, ObjectHandle privateData, byte[] publicData2)
        {
            _lowLevelStruct.Kdf            = 0;
            _lowLevelStruct.OtherInfoLen   = 0;
            _lowLevelStruct.OtherInfo      = IntPtr.Zero;
            _lowLevelStruct.PublicDataLen  = 0;
            _lowLevelStruct.PublicData     = IntPtr.Zero;
            _lowLevelStruct.PrivateDataLen = 0;
            _lowLevelStruct.PrivateData    = 0;
            _lowLevelStruct.PublicDataLen2 = 0;
            _lowLevelStruct.PublicData2    = IntPtr.Zero;

            _lowLevelStruct.Kdf = kdf;

            if (otherInfo != null)
            {
                _lowLevelStruct.OtherInfo = UnmanagedMemory.Allocate(otherInfo.Length);
                UnmanagedMemory.Write(_lowLevelStruct.OtherInfo, otherInfo);
                _lowLevelStruct.OtherInfoLen = NativeLongUtils.ConvertFromInt32(otherInfo.Length);
            }

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

            _lowLevelStruct.PrivateDataLen = privateDataLen;

            if (privateData == null)
            {
                throw new ArgumentNullException("privateData");
            }

            _lowLevelStruct.PrivateData = privateData.ObjectId;

            if (publicData2 != null)
            {
                _lowLevelStruct.PublicData2 = UnmanagedMemory.Allocate(publicData2.Length);
                UnmanagedMemory.Write(_lowLevelStruct.PublicData2, publicData2);
                _lowLevelStruct.PublicDataLen2 = NativeLongUtils.ConvertFromInt32(publicData2.Length);
            }
        }
Пример #27
0
        /// <summary>
        /// Initializes a new instance of the CkRsaPkcsOaepParams class.
        /// </summary>
        /// <param name='hashAlg'>Mechanism ID of the message digest algorithm used to calculate the digest of the encoding parameter (CKM)</param>
        /// <param name='mgf'>Mask generation function to use on the encoded block (CKG)</param>
        /// <param name='source'>Source of the encoding parameter (CKZ)</param>
        /// <param name='sourceData'>Data used as the input for the encoding parameter source</param>
        public CkRsaPkcsOaepParams(NativeULong hashAlg, NativeULong mgf, NativeULong source, byte[] sourceData)
        {
            _lowLevelStruct.HashAlg       = 0;
            _lowLevelStruct.Mgf           = 0;
            _lowLevelStruct.Source        = 0;
            _lowLevelStruct.SourceData    = IntPtr.Zero;
            _lowLevelStruct.SourceDataLen = 0;

            _lowLevelStruct.HashAlg = hashAlg;
            _lowLevelStruct.Mgf     = mgf;
            _lowLevelStruct.Source  = source;

            if (sourceData != null)
            {
                _lowLevelStruct.SourceData = UnmanagedMemory.Allocate(sourceData.Length);
                UnmanagedMemory.Write(_lowLevelStruct.SourceData, sourceData);
                _lowLevelStruct.SourceDataLen = NativeLongUtils.ConvertFromInt32(sourceData.Length);
            }
        }
Пример #28
0
        /// <summary>
        /// Initializes a new instance of the CkPkcs5Pbkd2Params class.
        /// </summary>
        /// <param name='saltSource'>Source of the salt value (CKZ)</param>
        /// <param name='saltSourceData'>Data used as the input for the salt source</param>
        /// <param name='iterations'>Number of iterations to perform when generating each block of random data</param>
        /// <param name='prf'>Pseudo-random function to used to generate the key (CKP)</param>
        /// <param name='prfData'>Data used as the input for PRF in addition to the salt value</param>
        /// <param name='password'>Password to be used in the PBE key generation</param>
        public CkPkcs5Pbkd2Params(NativeULong saltSource, byte[] saltSourceData, NativeULong iterations, NativeULong prf, byte[] prfData, byte[] password)
        {
            _lowLevelStruct.SaltSource        = 0;
            _lowLevelStruct.SaltSourceData    = IntPtr.Zero;
            _lowLevelStruct.SaltSourceDataLen = 0;
            _lowLevelStruct.Iterations        = 0;
            _lowLevelStruct.Prf         = 0;
            _lowLevelStruct.PrfData     = IntPtr.Zero;
            _lowLevelStruct.PrfDataLen  = 0;
            _lowLevelStruct.Password    = IntPtr.Zero;
            _lowLevelStruct.PasswordLen = IntPtr.Zero;

            _lowLevelStruct.SaltSource = saltSource;

            if (saltSourceData != null)
            {
                _lowLevelStruct.SaltSourceData = UnmanagedMemory.Allocate(saltSourceData.Length);
                UnmanagedMemory.Write(_lowLevelStruct.SaltSourceData, saltSourceData);
                _lowLevelStruct.SaltSourceDataLen = NativeLongUtils.ConvertFromInt32(saltSourceData.Length);
            }

            _lowLevelStruct.Iterations = iterations;

            _lowLevelStruct.Prf = prf;

            if (prfData != null)
            {
                _lowLevelStruct.PrfData = UnmanagedMemory.Allocate(prfData.Length);
                UnmanagedMemory.Write(_lowLevelStruct.PrfData, prfData);
                _lowLevelStruct.PrfDataLen = NativeLongUtils.ConvertFromInt32(prfData.Length);
            }

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

                NativeULong passwordLength = NativeLongUtils.ConvertFromInt32(password.Length);
                _lowLevelStruct.PasswordLen = UnmanagedMemory.Allocate(UnmanagedMemory.SizeOf(typeof(NativeULong)));
                UnmanagedMemory.Write(_lowLevelStruct.PasswordLen, BitConverter.GetBytes(passwordLength));
            }
        }
Пример #29
0
        public void _09_MechanismArrayAttributeTest()
        {
            Helpers.CheckPlatform();

            CKM[] originalValue = new CKM[2];
            originalValue[0] = CKM.CKM_RSA_PKCS;
            originalValue[1] = CKM.CKM_AES_CBC;
            // Create attribute with mechanism array value
            CK_ATTRIBUTE attr = CkaUtils.CreateAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue);

            Assert.IsTrue(attr.type == NativeLongUtils.ConvertFromCKA(CKA.CKA_ALLOWED_MECHANISMS));
            Assert.IsTrue(attr.value != IntPtr.Zero);
            Assert.IsTrue(attr.valueLen == NativeLongUtils.ConvertFromInt32(UnmanagedMemory.SizeOf(typeof(NativeULong)) * originalValue.Length));

            CKM[] 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] == recoveredValue[i]);
            }

            // Free attribute value
            UnmanagedMemory.Free(ref attr.value);
            attr.valueLen = 0;
            Assert.IsTrue(attr.type == NativeLongUtils.ConvertFromCKA(CKA.CKA_ALLOWED_MECHANISMS));
            Assert.IsTrue(attr.value == IntPtr.Zero);
            Assert.IsTrue(attr.valueLen == 0);

            // Create attribute with null mechanism array value
            attr = CkaUtils.CreateAttribute(CKA.CKA_ALLOWED_MECHANISMS, (CKM[])null);
            Assert.IsTrue(attr.type == NativeLongUtils.ConvertFromCKA(CKA.CKA_ALLOWED_MECHANISMS));
            Assert.IsTrue(attr.value == IntPtr.Zero);
            Assert.IsTrue(attr.valueLen == 0);

            // Create attribute with empty mechanism array value
            attr = CkaUtils.CreateAttribute(CKA.CKA_ALLOWED_MECHANISMS, new CKM[0]);
            Assert.IsTrue(attr.type == NativeLongUtils.ConvertFromCKA(CKA.CKA_ALLOWED_MECHANISMS));
            Assert.IsTrue(attr.value == IntPtr.Zero);
            Assert.IsTrue(attr.valueLen == 0);
        }
Пример #30
0
        /// <summary>
        /// Initializes a new instance of the CkOtpParams class.
        /// </summary>
        /// <param name='parameters'>List of OTP parameters</param>
        public CkOtpParams(List <CkOtpParam> parameters)
        {
            _lowLevelStruct.Params = IntPtr.Zero;
            _lowLevelStruct.Count  = 0;

            if ((parameters != null) && (parameters.Count > 0))
            {
                // Allocate memory for parameters
                int ckOtpParamSize = UnmanagedMemory.SizeOf(typeof(CK_OTP_PARAM));
                _lowLevelStruct.Params = UnmanagedMemory.Allocate(ckOtpParamSize * parameters.Count);
                _lowLevelStruct.Count  = NativeLongUtils.ConvertFromInt32(parameters.Count);

                // Copy paramaters to allocated memory
                for (int i = 0; i < parameters.Count; i++)
                {
                    IntPtr tempPointer = new IntPtr(_lowLevelStruct.Params.ToInt64() + (i * ckOtpParamSize));
                    UnmanagedMemory.Write(tempPointer, parameters[i].ToMarshalableStructure());
                }
            }
        }