Inheritance: MonoBehaviour
        public void _03_DigestKeyTest()
        {
            if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1)
                Assert.Inconclusive("Test cannot be executed on this platform");

            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.AppType))
            {
                // Find first slot with token present
                Slot slot = Helpers.GetUsableSlot(pkcs11);
                
                // Open RW session
                using (Session session = slot.OpenSession(SessionType.ReadWrite))
                {
                    // Login as normal user
                    session.Login(CKU.CKU_USER, Settings.NormalUserPin);
                    
                    // Generate symetric key
                    ObjectHandle generatedKey = Helpers.GenerateKey(session);

                    // Specify digesting mechanism
                    Mechanism mechanism = new Mechanism(CKM.CKM_SHA_1);
                    
                    // Digest key
                    byte[] digest = session.DigestKey(mechanism, generatedKey);
                    
                    // Do something interesting with digest value
                    Assert.IsNotNull(digest);

                    session.DestroyObject(generatedKey);
                    session.Logout();
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the HashAlgorithm class.
 /// </summary>
 /// <param name="serviceProvider">The name of the service provider which implements the hash algorithm</param>
 /// <param name="mechanism">The hash algorithm type</param>
 public HashAlgorithm(HashAlgorithmType hashAlgorithm, string serviceProvider = "")
     : base(new Session(serviceProvider, (MechanismType)hashAlgorithm), true)
 {
     m_mechanism = new Mechanism((MechanismType)hashAlgorithm);
     m_hashSize  = -1;
     Initialize();
 }
        public void _02_DigestMultiPartTest()
        {
            if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1)
                Assert.Inconclusive("Test cannot be executed on this platform");

            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.AppType))
            {
                // Find first slot with token present
                Slot slot = Helpers.GetUsableSlot(pkcs11);
                
                // Open RO session
                using (Session session = slot.OpenSession(SessionType.ReadOnly))
                {
                    // Specify digesting mechanism
                    Mechanism mechanism = new Mechanism(CKM.CKM_SHA_1);
                    
                    byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world");
                    byte[] digest = null;
                    
                    // Multipart digesting can be used i.e. for digesting of streamed data
                    using (MemoryStream inputStream = new MemoryStream(sourceData))
                    {
                        // Digest data
                        digest = session.Digest(mechanism, inputStream);
                    }

                    // Do something interesting with digest value
                    Assert.IsTrue(Convert.ToBase64String(digest) == "e1AsOh9IyGCa4hLN+2Od7jlnP14=");
                }
            }
        }
Beispiel #4
0
        public void _02_EncryptAndDecryptMultiPartTest()
        {
            Helpers.CheckPlatform();

            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.AppType))
            {
                // Find first slot with token present
                Slot slot = Helpers.GetUsableSlot(pkcs11);

                // Open RW session
                using (Session session = slot.OpenSession(SessionType.ReadWrite))
                {
                    // Login as normal user
                    session.Login(CKU.CKU_USER, Settings.NormalUserPin);

                    // Generate symetric key
                    ObjectHandle generatedKey = Helpers.GenerateKey(session);

                    // Generate random initialization vector
                    byte[] iv = session.GenerateRandom(8);

                    // Specify encryption mechanism with initialization vector as parameter
                    Mechanism mechanism = new Mechanism(CKM.CKM_DES3_CBC, iv);

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

                    // Multipart encryption can be used i.e. for encryption of streamed data
                    using (MemoryStream inputStream = new MemoryStream(sourceData), outputStream = new MemoryStream())
                    {
                        // Encrypt data
                        // Note that in real world application we would rather use bigger read buffer i.e. 4096
                        session.Encrypt(mechanism, generatedKey, inputStream, outputStream, 8);

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

                    // Do something interesting with encrypted data

                    // Multipart decryption can be used i.e. for decryption of streamed data
                    using (MemoryStream inputStream = new MemoryStream(encryptedData), outputStream = new MemoryStream())
                    {
                        // Decrypt data
                        // Note that in real world application we would rather use bigger read buffer i.e. 4096
                        session.Decrypt(mechanism, generatedKey, inputStream, outputStream, 8);

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

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

                    session.DestroyObject(generatedKey);
                    session.Logout();
                }
            }
        }
        public void _01_GenerateKeyTest()
        {
            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.AppType))
            {
                // Find first slot with token present
                Slot slot = Helpers.GetUsableSlot(pkcs11);

                // Open RW session
                using (Session session = slot.OpenSession(SessionType.ReadWrite))
                {
                    // Login as normal user
                    session.Login(CKU.CKU_USER, Settings.NormalUserPin);

                    // Prepare attribute template of new key
                    List <ObjectAttribute> objectAttributes = new List <ObjectAttribute>();
                    objectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY));
                    objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3));
                    objectAttributes.Add(new ObjectAttribute(CKA.CKA_ENCRYPT, true));
                    objectAttributes.Add(new ObjectAttribute(CKA.CKA_DECRYPT, true));

                    // Specify key generation mechanism
                    Mechanism mechanism = new Mechanism(CKM.CKM_DES3_KEY_GEN);

                    // Generate key
                    ObjectHandle objectHandle = session.GenerateKey(mechanism, objectAttributes);

                    // Do something interesting with generated key

                    // Destroy object
                    session.DestroyObject(objectHandle);

                    session.Logout();
                }
            }
        }
        public void SerializeObject_AllPropertiesSetToNonDefault_SerializesValidObject()
        {
            var sut = new Mechanism
            {
                Type        = "mechanism type",
                Description = "mechanism description",
                Handled     = true,
                HelpLink    = "https://helplink",
            };

            sut.Data.Add("data-key", "data-value");
            sut.Meta.Add("meta-key", "meta-value");

            var actual = sut.ToJsonString();

            Assert.Equal(
                "{\"data\":{\"data-key\":\"data-value\"}," +
                "\"meta\":{\"meta-key\":\"meta-value\"}," +
                "\"type\":\"mechanism type\"," +
                "\"description\":\"mechanism description\"," +
                "\"help_link\":\"https://helplink\"," +
                "\"handled\":true}",
                actual
                );
        }
Beispiel #7
0
        /// <summary>
        /// Signs single-part data, where the signature is an appendix to the data
        /// </summary>
        /// <param name="session">Instance of the extended class</param>
        /// <param name="mechanism">Signature mechanism</param>
        /// <param name="keyHandle">Signature key</param>
        /// <param name="data">Data to be signed</param>
        /// <param name="pin">Pin of user</param>
        /// <returns>Signature</returns>
        public static byte[] Sign(this Session session, Mechanism mechanism, ObjectHandle keyHandle, byte[] data, byte[] pin)
        {
            if (Platform.UnmanagedLongSize == 4)
            {
                if (Platform.StructPackingSize == 0)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    var mechanism41 = (HLA41.Mechanism) typeof(Mechanism).GetField("_mechanism41", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism);
                    var keyHandle41 = (HLA41.ObjectHandle) typeof(ObjectHandle).GetField("_objectHandle41", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(keyHandle);

                    return(session.HLA41Session.Sign(mechanism41, keyHandle41, data, pin));
                }
            }
            else
            {
                if (Platform.StructPackingSize == 0)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    throw new NotImplementedException();
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the HashAlgorithm class.
 /// </summary>
 /// <param name="session">The Cryptoki session context the hash algorithm will execute in.</param>
 /// <param name="mechanism">The hash algorithm type</param>
 public HashAlgorithm(HashAlgorithmType hashAlgorithm, Session session)
     : base(session, false)
 {
     m_mechanism = new Mechanism((MechanismType)hashAlgorithm);
     m_hashSize  = -1;
     Initialize();
 }
 /// <summary>
 /// Creates and Resets a new timer.
 /// </summary>
 /// <param name="mechanism">The directional mechanism to use.</param>
 /// <param name="timeMode">The time counting mode to use.</param>
 public UTimer(Mechanism mechanism, TimeMode timeMode)
 {
     allTimers.Add(this);
     this.mechanism = mechanism;
     this.timeMode = timeMode;
     Reset();
 }
Beispiel #10
0
        public void _02_GenerateKeyPairTest()
        {
            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
            {
                // Find first slot with token present
                Slot slot = Helpers.GetUsableSlot(pkcs11);

                // Open RW session
                using (Session session = slot.OpenSession(false))
                {
                    // Login as normal user
                    session.Login(CKU.CKU_USER, Settings.NormalUserPin);

                    // The CKA_ID attribute is intended as a means of distinguishing multiple key pairs held by the same subject
                    byte[] ckaId = session.GenerateRandom(20);

                    // Prepare attribute template of new public key
                    List <ObjectAttribute> publicKeyAttributes = new List <ObjectAttribute>();
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_TOKEN, true));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PRIVATE, false));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, Settings.ApplicationName));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ID, ckaId));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ENCRYPT, true));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_VERIFY, true));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_VERIFY_RECOVER, true));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_WRAP, true));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_MODULUS_BITS, 1024));
                    publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PUBLIC_EXPONENT, new byte[] { 0x01, 0x00, 0x01 }));

                    // Prepare attribute template of new private key
                    List <ObjectAttribute> privateKeyAttributes = new List <ObjectAttribute>();
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_TOKEN, true));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PRIVATE, true));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, Settings.ApplicationName));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ID, ckaId));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SENSITIVE, true));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_DECRYPT, true));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SIGN, true));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SIGN_RECOVER, true));
                    privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_UNWRAP, true));

                    // Specify key generation mechanism
                    Mechanism mechanism = new Mechanism(CKM.CKM_RSA_PKCS_KEY_PAIR_GEN);

                    // Generate key pair
                    ObjectHandle publicKeyHandle  = null;
                    ObjectHandle privateKeyHandle = null;
                    session.GenerateKeyPair(mechanism, publicKeyAttributes, privateKeyAttributes, out publicKeyHandle, out privateKeyHandle);

                    // Do something interesting with generated key pair

                    // Destroy keys
                    session.DestroyObject(privateKeyHandle);
                    session.DestroyObject(publicKeyHandle);

                    session.Logout();
                }
            }
        }
Beispiel #11
0
        public bool Run(object[] inputParams)
        {
            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, false))
            {
                // Find first slot with token present
                Slot slot = Helpers.GetUsableSlot(pkcs11);

                // Open RW session
                using (Session session = slot.OpenSession(false))
                {
                    string    pin        = Convert.ToString(inputParams[0]);
                    Mechanism mechanism  = null;
                    string    opName     = "sha256";
                    string    pathSource = null;

                    if (inputParams.Length >= 2)
                    {
                        opName = Convert.ToString(inputParams[1]);
                    }

                    if (inputParams.Length >= 3)
                    {
                        pathSource = Convert.ToString(inputParams[2]);
                    }

                    if (opName.Equals("sha512"))
                    {
                        mechanism = new Mechanism(CKM.CKM_SHA512);
                    }
                    else if (opName.Equals("sha384"))
                    {
                        mechanism = new Mechanism(CKM.CKM_SHA384);
                    }
                    else
                    {
                        mechanism = new Mechanism(CKM.CKM_SHA256);
                        opName    = "sha256";
                    }
                    Console.WriteLine("Mechanism is " + opName);

                    if (String.IsNullOrEmpty(pathSource))
                    {
                        pathSource = Settings.Pkcs11LibraryPath;
                    }
                    // Login as normal user
                    session.Login(CKU.CKU_USER, pin);

                    using (FileStream sourceFileStream = new FileStream(pathSource, FileMode.Open, FileAccess.Read))
                    {
                        byte[] digestBytes = session.Digest(mechanism, sourceFileStream);
                        Console.WriteLine("Digest Text: " + ConvertUtils.BytesToHexString(digestBytes));
                    }

                    session.Logout();
                    slot.CloseSession(session);
                }
            }
            return(true);
        }
Beispiel #12
0
    private void SetupMechanisms()
    {
        mechanisms["AccInput"] = new Mechanism
        {
            name       = "AccInput",
            trialType  = TrialType.AccInput,
            rate       = 0f,
            trials     = accTrials,
            trialsLeft = accTrials,
            behavior   = UrnEntryBehavior.Persist
        };

        mechanisms["FabInput"] = new Mechanism
        {
            name       = "FabInput",
            trialType  = TrialType.FabInput,
            rate       = 0f,
            trials     = fabTrials,
            trialsLeft = fabTrials,
            behavior   = UrnEntryBehavior.Persist
        };

        mechanisms["RejInput"] = new Mechanism
        {
            name       = "RejInput",
            trialType  = TrialType.RejInput,
            rate       = 0f,
            trials     = rejTrials,
            trialsLeft = rejTrials,
            behavior   = UrnEntryBehavior.Override
        };
        mechanisms["AssistSuccess"] = new Mechanism
        {
            name       = "AssistSuccess",
            trialType  = TrialType.AssistSuccess,
            rate       = 0f,
            trials     = assistSuccessTrials,
            trialsLeft = assistSuccessTrials,
            behavior   = UrnEntryBehavior.Persist
        };
        mechanisms["AssistFail"] = new Mechanism
        {
            name       = "AssistFail",
            trialType  = TrialType.AssistFail,
            rate       = 0f,
            trials     = assistFailTrials,
            trialsLeft = assistFailTrials,
            behavior   = UrnEntryBehavior.Persist
        };
        mechanisms["ExplicitSham"] = new Mechanism
        {
            name       = "ExplicitSham",
            trialType  = TrialType.ExplicitSham,
            rate       = 0f,
            trials     = explicitShamTrials,
            trialsLeft = explicitShamTrials,
            behavior   = UrnEntryBehavior.Persist
        };
    }
Beispiel #13
0
        //Method that sets robots position
        public static void SetRobPos(int setVal)
        {
            Station   station2 = Project.ActiveProject as Station;
            Mechanism mech     = station2.ActiveTask.Mechanism;

            mech.SetJointValues(RecData.JointValuesList[setVal], false);
            //AddMarkup();
        }
        public void Remove()
        {
            OnRemove();
            TryRemoveNetwork(Mechanism.Body);

            Mechanism = null !;
            Removed   = true;
        }
Beispiel #15
0
        public Army()
        {
            Soldier   soldier   = new Soldier("Fighter", 100, 10);
            Rider     rider     = new Rider("Rider", 100, 10);
            Mechanism mechanism = new Mechanism("catapult", 790, 100, 10, 50);

            Console.WriteLine("Army is created!");
        }
Beispiel #16
0
 public void StartDraggingUnplaced(Mechanism mechanism)
 {
     draggingMechanism = mechanism;
     if (draggingMechanism != null)
     {
         draggingMechanism.StartDrag();
     }
 }
 private void Start()
 {
     mechanism = GetComponent <Mechanism>();
     if (mechanism == null)
     {
         Debug.LogError("在" + gameObject.name + "中,找不到Machanism组件");
     }
 }
Beispiel #18
0
 void StopDragging()
 {
     if (draggingMechanism != null)
     {
         draggingMechanism.StopDrag();
         draggingMechanism = null;
     }
 }
Beispiel #19
0
        /// <summary>
        /// Generates a new CryptoKey object that represents a public/private key pair.
        /// </summary>
        /// <param name="session">The Cryptoki session context.</param>
        /// <param name="mechanism">The key algorithm and parameters.</param>
        /// <param name="publicKeyTemplate">The public key attribute template.</param>
        /// <param name="privateKeyTemplate">The private key attribute template.</param>
        /// <returns></returns>
        public static CryptoKey GenerateKeyPair(Session session, Mechanism mechanism, CryptokiAttribute[] publicKeyTemplate, CryptokiAttribute[] privateKeyTemplate)
        {
            CryptoKey ret = GenerateKeyPairInternal(session, mechanism, publicKeyTemplate, privateKeyTemplate);

            session.AddSessionObject(ret);

            return(ret);
        }
Beispiel #20
0
        /// <summary>
        /// Generates a new CryptoKey within the specified session context with the specified key mechanism and key template.
        /// </summary>
        /// <param name="session">The Cryptoki session context.</param>
        /// <param name="mechanism">The key algorithm and parameters.</param>
        /// <param name="template">The key attribute template that defines the resulting key's properties.</param>
        /// <returns></returns>
        public static CryptoKey GenerateKey(Session session, Mechanism mechanism, CryptokiAttribute[] template)
        {
            CryptoKey ret = GenerateKeyInternal(session, mechanism, template);

            session.AddSessionObject(ret);

            return(ret);
        }
 void Start()
 {
     parentMechanism = transform.GetComponentInParent <Mechanism>();
     if (parentMechanism == null)
     {
         Debug.LogError("在" + gameObject.name + "中,找不到parentMechanism");
     }
 }
Beispiel #22
0
        /// <summary>
        /// Verifies that a digital signature is valid by determining the hash value in the signature using the specified hash algorithm and padding, and comparing it to the provided hash value
        /// </summary>
        /// <param name="hash">he hash value of the signed data</param>
        /// <param name="signature">The signature data to be verified</param>
        /// <param name="hashAlgorithm">The hash algorithm used to create the hash value</param>
        /// <param name="padding">The padding mode</param>
        /// <returns>True if the signature is valid, false otherwise</returns>
        public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
        {
            if (hash == null || hash.Length == 0)
            {
                throw new ArgumentNullException(nameof(hash));
            }

            if (signature == null || signature.Length == 0)
            {
                throw new ArgumentNullException(nameof(signature));
            }

            if (hashAlgorithm == null)
            {
                throw new ArgumentNullException(nameof(hashAlgorithm));
            }

            if (padding == null)
            {
                throw new ArgumentNullException(nameof(padding));
            }

            if (padding == RSASignaturePadding.Pkcs1)
            {
                byte[] pkcs1DigestInfo = CreatePkcs1DigestInfo(hash, hashAlgorithm);
                if (pkcs1DigestInfo == null)
                {
                    throw new NotSupportedException(string.Format("Algorithm {0} is not supported", hashAlgorithm));
                }

                using (Session session = _certContext.TokenContext.SlotContext.Slot.OpenSession(SessionType.ReadOnly))
                    using (var mechanism = new Mechanism(CKM.CKM_RSA_PKCS))
                    {
                        session.Verify(mechanism, _certContext.PubKeyHandle, pkcs1DigestInfo, signature, out bool isValid);
                        return(isValid);
                    }
            }
            else if (padding == RSASignaturePadding.Pss)
            {
                CkRsaPkcsPssParams pssMechanismParams = CreateCkRsaPkcsPssParams(hash, hashAlgorithm);
                if (pssMechanismParams == null)
                {
                    throw new NotSupportedException(string.Format("Algorithm {0} is not supported", hashAlgorithm.Name));
                }

                using (Session session = _certContext.TokenContext.SlotContext.Slot.OpenSession(SessionType.ReadOnly))
                    using (var mechanism = new Mechanism(CKM.CKM_RSA_PKCS_PSS, pssMechanismParams))
                    {
                        session.Verify(mechanism, _certContext.PubKeyHandle, hash, signature, out bool isValid);
                        return(isValid);
                    }
            }
            else
            {
                throw new NotSupportedException(string.Format("Padding {0} is not supported", padding));
            }
        }
Beispiel #23
0
        public void _01_BasicSignEncryptAndDecryptVerifyTest()
        {
            Helpers.CheckPlatform();

            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.AppType))
            {
                // Find first slot with token present
                Slot slot = Helpers.GetUsableSlot(pkcs11);

                // Open RW session
                using (Session session = slot.OpenSession(SessionType.ReadWrite))
                {
                    // Login as normal user
                    session.Login(CKU.CKU_USER, Settings.NormalUserPin);

                    // Generate asymetric key pair
                    ObjectHandle publicKey  = null;
                    ObjectHandle privateKey = null;
                    Helpers.GenerateKeyPair(session, out publicKey, out privateKey);

                    // Specify signing mechanism
                    Mechanism signingMechanism = new Mechanism(CKM.CKM_SHA1_RSA_PKCS);

                    // Generate symetric key
                    ObjectHandle secretKey = Helpers.GenerateKey(session);

                    // Generate random initialization vector
                    byte[] iv = session.GenerateRandom(8);

                    // Specify encryption mechanism with initialization vector as parameter
                    Mechanism encryptionMechanism = new Mechanism(CKM.CKM_DES3_CBC, iv);

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

                    // Sign and encrypt data
                    byte[] signature     = null;
                    byte[] encryptedData = null;
                    session.SignEncrypt(signingMechanism, privateKey, encryptionMechanism, secretKey, sourceData, out signature, out encryptedData);

                    // Do something interesting with signature and encrypted data

                    // Decrypt data and verify signature of data
                    byte[] decryptedData = null;
                    bool   isValid       = false;
                    session.DecryptVerify(signingMechanism, publicKey, encryptionMechanism, secretKey, encryptedData, signature, out decryptedData, out isValid);

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

                    session.DestroyObject(privateKey);
                    session.DestroyObject(publicKey);
                    session.DestroyObject(secretKey);
                    session.Logout();
                }
            }
        }
        public void _02_SignAndVerifyMultiPartTest()
        {
            if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1)
            {
                Assert.Inconclusive("Test cannot be executed on this platform");
            }

            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
            {
                // Find first slot with token present
                Slot slot = Helpers.GetUsableSlot(pkcs11);

                // Open RW session
                using (Session session = slot.OpenSession(false))
                {
                    // Login as normal user
                    session.Login(CKU.CKU_USER, Settings.NormalUserPin);

                    // Generate key pair
                    ObjectHandle publicKey  = null;
                    ObjectHandle privateKey = null;
                    Helpers.GenerateKeyPair(session, out publicKey, out privateKey);

                    // Specify signing mechanism
                    Mechanism mechanism = new Mechanism(CKM.CKM_SHA1_RSA_PKCS);

                    byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world");
                    byte[] signature  = null;
                    bool   isValid    = false;

                    // Multipart signing can be used i.e. for signing of streamed data
                    using (MemoryStream inputStream = new MemoryStream(sourceData))
                    {
                        // Sign data
                        // Note that in real world application we would rather use bigger read buffer i.e. 4096
                        signature = session.Sign(mechanism, privateKey, inputStream, 8);
                    }

                    // Do something interesting with signature

                    // Multipart verification can be used i.e. for signature verification of streamed data
                    using (MemoryStream inputStream = new MemoryStream(sourceData))
                    {
                        // Verify signature
                        // Note that in real world application we would rather use bigger read buffer i.e. 4096
                        session.Verify(mechanism, publicKey, inputStream, signature, out isValid, 8);
                    }

                    // Do something interesting with verification result
                    Assert.IsTrue(isValid);

                    session.DestroyObject(privateKey);
                    session.DestroyObject(publicKey);
                    session.Logout();
                }
            }
        }
Beispiel #25
0
        internal IReactionSet Initiate(IChemObjectSet <IAtomContainer> reactants, IChemObjectSet <IAtomContainer> agents, bool isReverse, CheckReactantAtom checkReactantAtom, CheckAtom checkAtom, CheckBond checkBond)
        {
            CheckInitiateParams(reactants, agents);

            IReactionSet   setOfReactions = reactants.Builder.NewReactionSet();
            IAtomContainer reactant       = reactants[0];

            // if the parameter hasActiveCenter is not fixed yet, set the active centers
            IParameterReaction ipr = base.GetParameterClass(typeof(SetReactionCenter));

            if (ipr != null && !ipr.IsSetParameter)
            {
                SetActiveCenters(reactant, checkReactantAtom, checkAtom, checkBond);
            }

            foreach (var atomi in reactant.Atoms)
            {
                if (atomi.IsReactiveCenter && checkReactantAtom(reactant, atomi))
                {
                    foreach (var bondi in reactant.GetConnectedBonds(atomi))
                    {
                        if (bondi.IsReactiveCenter && checkBond(bondi))
                        {
                            IAtom atomj = bondi.GetOther(atomi);
                            if (atomj.IsReactiveCenter && checkAtom(atomj) && !reactant.GetConnectedSingleElectrons(atomj).Any())
                            {
                                IAtom[] atomList;
                                if (isReverse)
                                {
                                    atomList = new[] { atomj, atomi }
                                }
                                ;
                                else
                                {
                                    atomList = new[] { atomi, atomj }
                                };
                                var bondList = new[] { bondi };

                                IChemObjectSet <IAtomContainer> moleculeSet = reactant.Builder.NewChemObjectSet <IAtomContainer>();

                                moleculeSet.Add(reactant);
                                IReaction reaction = Mechanism.Initiate(moleculeSet, atomList, bondList);
                                if (reaction == null)
                                {
                                    continue;
                                }
                                else
                                {
                                    setOfReactions.Add(reaction);
                                }
                            }
                        }
                    }
                }
            }
            return(setOfReactions);
        }
Beispiel #26
0
        /// <summary>
        ///     Initialize the processor
        /// </summary>
        /// <returns>An auth tag to start the authentication process</returns>
        public override Tag Initialize(string id, string password)
        {
            base.Initialize(id, password);

            var tag = TagRegistry.GetTag <Auth>("auth", Namespaces.Sasl);

            tag.Mechanism = Mechanism.GetMechanism(MechanismType.DigestMd5);
            return(tag);
        }
Beispiel #27
0
        public void _01_BasicWrapAndUnwrapKeyTest()
        {
            if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
            {
                Assert.Inconclusive("Test cannot be executed on this platform");
            }

            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.AppType))
            {
                // Find first slot with token present
                Slot slot = Helpers.GetUsableSlot(pkcs11);

                // Open RW session
                using (Session session = slot.OpenSession(SessionType.ReadWrite))
                {
                    // Login as normal user
                    session.Login(CKU.CKU_USER, Settings.NormalUserPin);

                    // Generate asymetric key pair
                    ObjectHandle publicKey  = null;
                    ObjectHandle privateKey = null;
                    Helpers.GenerateKeyPair(session, out publicKey, out privateKey);

                    // Generate symetric key
                    ObjectHandle secretKey = Helpers.GenerateKey(session);

                    // Specify wrapping mechanism
                    Mechanism mechanism = new Mechanism(CKM.CKM_RSA_PKCS);

                    // Wrap key
                    byte[] wrappedKey = session.WrapKey(mechanism, publicKey, secretKey);

                    // Do something interesting with wrapped key
                    Assert.IsNotNull(wrappedKey);

                    // Define attributes for unwrapped key
                    List <ObjectAttribute> objectAttributes = new List <ObjectAttribute>();
                    objectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY));
                    objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3));
                    objectAttributes.Add(new ObjectAttribute(CKA.CKA_ENCRYPT, true));
                    objectAttributes.Add(new ObjectAttribute(CKA.CKA_DECRYPT, true));
                    objectAttributes.Add(new ObjectAttribute(CKA.CKA_DERIVE, true));
                    objectAttributes.Add(new ObjectAttribute(CKA.CKA_EXTRACTABLE, true));

                    // Unwrap key
                    ObjectHandle unwrappedKey = session.UnwrapKey(mechanism, privateKey, wrappedKey, objectAttributes);

                    // Do something interesting with unwrapped key
                    Assert.IsTrue(unwrappedKey.ObjectId != CK.CK_INVALID_HANDLE);

                    session.DestroyObject(privateKey);
                    session.DestroyObject(publicKey);
                    session.DestroyObject(secretKey);
                    session.Logout();
                }
            }
        }
Beispiel #28
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public override Tag Initialize()
        {
            base.Initialize();

            var tag = TagRegistry.GetTag <Auth>("auth", Namespaces.SASL);

            tag.Mechanism = Mechanism.GetMechanism(MechanismType.DigestMD5);
            return(tag);
        }
Beispiel #29
0
        static void Main(string[] args)
        {
            try
            {
                // Инициализировать библиотеку
                Console.WriteLine("Library initialization");
                using (var pkcs11 = new Pkcs11(Settings.RutokenEcpDllDefaultPath, Settings.OsLockingDefault))
                {
                    // Получить доступный слот
                    Console.WriteLine("Checking tokens available");
                    Slot slot = Helpers.GetUsableSlot(pkcs11);

                    // Определение поддерживаемых токеном механизмов
                    Console.WriteLine("Checking mechanisms available");
                    List <CKM> mechanisms = slot.GetMechanismList();
                    Errors.Check(" No mechanisms available", mechanisms.Count > 0);
                    bool isGost28147_89Supported = mechanisms.Contains((CKM)Extended_CKM.CKM_GOST28147_KEY_GEN);
                    Errors.Check(" CKM_GOST28147_KEY_GEN isn`t supported!", isGost28147_89Supported);

                    // Открыть RW сессию в первом доступном слоте
                    Console.WriteLine("Opening RW session");
                    using (Session session = slot.OpenSession(false))
                    {
                        // Выполнить аутентификацию Пользователя
                        Console.WriteLine("User authentication");
                        session.Login(CKU.CKU_USER, SampleConstants.NormalUserPin);

                        try
                        {
                            // Определить механизм генерации ключа
                            Console.WriteLine("Generating GOST 28147-89 secret key...");
                            var mechanism = new Mechanism((uint)Extended_CKM.CKM_GOST28147_KEY_GEN);

                            // Сгенерировать секретный ключ ГОСТ 28147-89
                            ObjectHandle symmetricKey = session.GenerateKey(mechanism, SymmetricKeyAttributes);
                            Errors.Check("Invalid key handle", symmetricKey.ObjectId != CK.CK_INVALID_HANDLE);
                            Console.WriteLine("Generating has been completed successfully");
                        }
                        finally
                        {
                            // Сбросить права доступа как в случае исключения,
                            // так и в случае успеха.
                            // Сессия закрывается автоматически.
                            session.Logout();
                        }
                    }
                }
            }
            catch (Pkcs11Exception ex)
            {
                Console.WriteLine($"Operation failed [Method: {ex.Method}, RV: {ex.RV}]");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Operation failed [Message: {ex.Message}]");
            }
        }
Beispiel #30
0
        /// <summary>
        /// Derives a CryptoKey object with the specified key algorithm and key attribute template
        /// </summary>
        /// <param name="mechanism">The Cryptoki session context.</param>
        /// <param name="template">The key attribute template.</param>
        /// <returns></returns>
        public CryptoKey DeriveKey(Mechanism mechanism, CryptokiAttribute[] template)
        {
            if (m_isDisposed) throw new ObjectDisposedException();
            
            CryptoKey ret = DeriveKeyInternal(mechanism, template);

            m_session.AddSessionObject(ret);

            return ret;
        }
Beispiel #31
0
 public Level(int levelID, string name, string difficulty, Color32 backgroundColor, char[,] groundLayout, Entity[,] entityLayout, Mechanism[,] mechanismLayout)
 {
     _levelID = levelID;
     _name = name;
     _difficulty = difficulty;
     _backgroundColor = backgroundColor;
     _groundLayout = groundLayout;
     _entityLayout = entityLayout;
     _mechanismLayout = mechanismLayout;
 }
Beispiel #32
0
        public static byte[] DeriveSecret(EcIdentifier ecIdentifier, EcKeyPair publicKeyPair, string password)
        {
            using (Pkcs11 pk = new Pkcs11(LibraryPath, false))
            {
                var slot = pk.GetSlotList(false)
                           .First(s =>
                {
                    try
                    {
                        bool found;
                        using (Session session = s.OpenSession(true))
                        {
                            found = s.GetTokenInfo().SerialNumber == ecIdentifier.TokenSerialNumber;
                        }
                        return(found);
                    }
                    catch
                    {
                        return(false);
                    }
                });

                using (Session session = slot.OpenSession(false))
                {
                    session.Login(CKU.CKU_USER, password);

                    var objectPrivate = GetObjectHandle(ecIdentifier.KeyLabel, session, CKO.CKO_PRIVATE_KEY);

                    var publicKey = publicKeyPair.ToDre();

                    byte[] data      = session.GenerateRandom(32);
                    var    mechanism = new Mechanism(CKM.CKM_ECDH1_DERIVE, new CkEcdh1DeriveParams(0, null, publicKey));

                    var deriveAttributes = new List <ObjectAttribute>
                    {
                        new ObjectAttribute(CKA.CKA_TOKEN, false),
                        new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY),
                        new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_GENERIC_SECRET),
                        new ObjectAttribute(CKA.CKA_SENSITIVE, false),
                        new ObjectAttribute(CKA.CKA_EXTRACTABLE, true),
                        new ObjectAttribute(CKA.CKA_ENCRYPT, true),
                        new ObjectAttribute(CKA.CKA_DECRYPT, true),
                        new ObjectAttribute(CKA.CKA_WRAP, true),
                        new ObjectAttribute(CKA.CKA_UNWRAP, true),
                        new ObjectAttribute(CKA.CKA_VALUE_LEN, 320 / 8),
                    };

                    var derivedKey = session.DeriveKey(mechanism, objectPrivate, deriveAttributes);

                    var derivedSecret = GetDataFromObject(derivedKey, session, CKA.CKA_VALUE);

                    return(SHA512.Create().ComputeHash(derivedSecret));
                }
            }
        }
Beispiel #33
0
    void Breakage()
    {
        int randomNum;
        randomNum = Random.Range(0, mechanisms.Length);
        brokenMech = mechanisms[randomNum];
        if (brokenMech.isBroken)
            Breakage();

        if (!brokenMech.isBroken)
        {
            brokenMech.BreakMechanism();
            breakageText.text = "The " + mechanisms[randomNum].deviceName + " has broken!";
            breakageText.enabled = true;
            brokenMech.icon.SetTarget(brokenMech.gameObject);
            currentBreaks++;
        }
    }
        public void _01_DisposeMechanismTest()
        {
            byte[] parameter = new byte[8];
            System.Random rng = new Random();
            rng.NextBytes(parameter);

            // Unmanaged memory for mechanism parameter stored in low level CK_MECHANISM struct
            // is allocated by constructor of Mechanism class.
            Mechanism mechanism1 = new Mechanism(CKM.CKM_DES_CBC, parameter);

            // Do something interesting with mechanism

            // This unmanaged memory is freed by Dispose() method.
            mechanism1.Dispose();


            // Mechanism class can be used in using statement which defines a scope 
            // at the end of which an object will be disposed (and unmanaged memory freed).
            using (Mechanism mechanism2 = new Mechanism(CKM.CKM_DES_CBC, parameter))
            {
                // Do something interesting with mechanism
            }


            #pragma warning disable 0219

            // Explicit calling of Dispose() method can also be ommitted
            // and this is the prefered way how to use Mechanism class.
            Mechanism mechanism3 = new Mechanism(CKM.CKM_DES_CBC, parameter);

            // Do something interesting with mechanism

            // Dispose() method will be called (and unmanaged memory freed) by GC eventually
            // but we cannot be sure when will this occur.

            #pragma warning restore 0219
        }
 /// <summary>
 /// Creates and Resets a new timer in Time TimeMode.
 /// </summary>
 /// <param name="mechanism">The directional mechanism to use.</param>
 public UTimer(Mechanism mechanism)
     : this(mechanism, TimeMode.Time)
 {
 }
	//Load Level from JSON
	public static Level LoadFromJSON(Dictionary<string, object> levelData, int index, bool calledFromEditor)
	{
		#region Throw Exceptions If JSON Data Does Not Contain All Neccessary Fields
		if(!levelData.ContainsKey("id"))
			throw new Exception("ID not present in level file!");
		if(!levelData.ContainsKey("name"))
			throw new Exception("Name not present in level file!");
        if(!levelData.ContainsKey("difficulty"))
            throw new Exception("Difficulty not present in level file!");
        if(!levelData.ContainsKey("creator"))
			throw new Exception("creator not present in level file!");
		if(!levelData.ContainsKey("colour"))
			throw new Exception("Colour not present in level file!");
		if(!levelData.ContainsKey("dimensions"))
			throw new Exception("Dimensions not present in level file!");
		if(!levelData.ContainsKey("groundlayer"))
			throw new Exception("Ground layout not present in level file!");
		if(!levelData.ContainsKey("entitylayer"))
			throw new Exception("Entity layout not present in level file!");
		if(!levelData.ContainsKey("mechanismlayer"))
			throw new Exception("Mechanism layout not present in level file!");
        if(!levelData.ContainsKey("mechanisms"))
            throw new Exception("Mechanism data not present in level file!");
        #endregion

        string name = (string)levelData["name"];
        string difficulty = (string)levelData["difficulty"];
        int levelWidth = int.Parse(((string)levelData["dimensions"]).Substring(0,2));
		int levelHeight = int.Parse(((string)levelData["dimensions"]).Substring(2,2));
		Color backgroundColor = (Color)new Color32(byte.Parse(((string)levelData["colour"]).Substring(0,3)), byte.Parse(((string)levelData["colour"]).Substring(3,3)), byte.Parse(((string)levelData["colour"]).Substring(6,3)), 1);
		string rawGroundLayer = Crypto.Decompress((string)levelData["groundlayer"]);
		string rawEntityLayer = Crypto.Decompress((string)levelData["entitylayer"]);
		string rawMechanismLayer = Crypto.Decompress((string)levelData["mechanismlayer"]);
        string rawMechanismData = (string)levelData["mechanisms"];

        char[,] groundLayer = new char[levelWidth, levelHeight];
		char[,] entityLayer = new char[levelWidth, levelHeight];
		char[,] mechanismLayer = new char[levelWidth, levelHeight];
		Entity[,] entities = new Entity[levelWidth, levelHeight];
		Mechanism[,] mechanisms = new Mechanism[levelWidth, levelHeight];
		int[] mechanismInputs = new int[3]{0,0,0};
        int mechanismCount = 0;

		GameObject currentObject;
		int filePlayerCount = 0;

		#region More Exceptions For Level Data That Has Been Corrupted/Tampered With
		for(int x = 0; x < (levelWidth * levelHeight); x++)
		{
			if(rawEntityLayer[x] == 'P')
				filePlayerCount++;
		}

        //Allow players to load unfinished levels into the editor
        if (!calledFromEditor)
        {
            if (!rawGroundLayer.Contains("X"))
                throw new Exception("There Must Be Atleast One Finish Block");

            if (filePlayerCount != 1)
                throw new Exception("Invalid Player Object Count");
        }

		if(((string)levelData["colour"]).Length != 9)
			throw new Exception("Invalid Background Colour");

        if (rawMechanismData.Length != rawMechanismLayer.Replace("Z", "").Length * 2)
            throw new Exception("Invalid Mechanism Data");

		if(rawGroundLayer.Length != levelHeight * levelWidth || rawEntityLayer.Length != levelHeight * levelWidth || rawMechanismLayer.Length != levelHeight * levelWidth)
			throw new Exception("Invalid Block Count");
        #endregion

        //Change the background color instantly if loading into level edior, or tween it if not
        if (Application.loadedLevel == 3)
            Camera.main.backgroundColor = backgroundColor;
        else
		    Camera.main.GetComponent<CameraControl>().ChangeBackgroundColour(backgroundColor);

		for(int y = 0; y < levelHeight; y++)
		{
			for(int x = 0; x < levelWidth; x++)
			{
				groundLayer[x,y] = rawGroundLayer[x + (levelWidth * y)];
				if(groundLayer[x,y] != 'Z')
				{
					currentObject = Instantiate(GameData.GroundTypes[groundLayer[x,y]], new Vector3(x*2, index == -1? -1 : -2, y*2), Quaternion.identity) as GameObject;
					currentObject.transform.parent = GameObject.Find("Level Objects").transform;
                    currentObject.name = 'G' + x.ToString("00") + y.ToString("00");
                    currentObject.GetComponent<Block>().Spawn(x, groundLayer[x, y]);
				}

				entityLayer[x,y] = rawEntityLayer[x + (levelWidth * y)];
				if(entityLayer[x,y] != 'Z')
				{
					if(entityLayer[x,y] != 'P' || Application.loadedLevel == 2)
					{
						currentObject = Instantiate(GameData.EntityTypes[entityLayer[x,y]], new Vector3(x*2, (index == -1)? 1 : 0, y*2), Quaternion.identity) as GameObject;
						currentObject.transform.parent = GameObject.Find("Level Objects").transform;
                        currentObject.name = 'E' + x.ToString("00") + y.ToString("00");
                        currentObject.GetComponent<Block>().Spawn(x, entityLayer[x, y]);
					}
					else
					{
						currentObject = GameObject.Find("Player");
						currentObject.transform.position = new Vector3(x*2, (index == -1)? 1 : 0, y*2);
					}
					currentObject.GetComponent<Entity>().SetDimensions((byte)x, (byte)y);
					entities[x,y] = currentObject.GetComponent<Entity>();

					if(groundLayer[x,y] == 'P' || groundLayer[x,y] == 'Z')
						throw new Exception("Entities Cannot Spawn Over Nothing");

					if(groundLayer[x,y] == 'X')
						throw new Exception("Entities Cannot Spawn Over A Finish Block");
				}

				mechanismLayer[x,y] = rawMechanismLayer[x + (levelWidth * y)];
				if(mechanismLayer[x,y] != 'Z')
				{
					currentObject = Instantiate(GameData.MechanismTypes[mechanismLayer[x,y]], new Vector3(x*2, (index == -1)? 1 : 0, y*2), Quaternion.Euler(new Vector3(-90,0,0))) as GameObject;
					currentObject.transform.parent = GameObject.Find("Level Objects").transform;
                    currentObject.name = 'M' + x.ToString("00") + y.ToString("00");
                    currentObject.GetComponent<Block>().Spawn(x, mechanismLayer[x, y]);
					mechanisms[x,y] = currentObject.GetComponent<Mechanism>();

                    //Setup mechanism data from level file                    
                    currentObject.GetComponent<Mechanism>().group = byte.Parse(rawMechanismData[mechanismCount * 2].ToString());
                    if(currentObject.GetComponent<Mechanism>().receivesInput)
                        currentObject.GetComponent<Mechanism>().startOpen = (byte.Parse(rawMechanismData[(mechanismCount * 2) + 1].ToString()) == 0? false : true);
                    currentObject.GetComponent<Renderer>().material.mainTexture = Resources.Load("Textures\\" + GameData.MechanismTypes[mechanismLayer[x, y]].name + currentObject.GetComponent<Mechanism>().group.ToString()) as Texture;

                    for (int g = 0; g < 3; g++)
					{
						if(!mechanisms[x,y].receivesInput && mechanisms[x,y].group == g)
							mechanismInputs[g] += 1;
					}

					if(groundLayer[x,y] == 'P' || groundLayer[x,y] == 'Z')
						throw new Exception("Mechanisms Cannot Spawn Over Nothing");

					if(groundLayer[x,y] == 'X')
						throw new Exception("Mechanisms Cannot Spawn On A Finish Block");

					if(!mechanisms[x,y].receivesInput && entityLayer[x,y] != 'Z')
						throw new Exception("Input mechanisms cannot spawn on entities");

					if(mechanisms[x,y].receivesInput && entityLayer[x,y] != 'Z' && !entities[x,y].moveable)
						throw new Exception("Only moveable entities can spawn inside mechanisms that receive input");

                    mechanismCount++;
				}
			}
		}

		foreach(Mechanism m in mechanisms)
		{
			if(m != null && m.receivesInput)
				m.inputRequired = mechanismInputs[m.group];
		}

        return new Level(index, name, difficulty, backgroundColor, groundLayer, entities, mechanisms);
	}
Beispiel #37
0
 public void HasBeenFixed()
 {
     breakageText.enabled = false;
     brokenMech = null;
     currentBreaks--;
 }
	void Update () {
        if (!selectionPanel.activeSelf)
            return;
         
        if(tooltipPanel.activeSelf)
            tooltipPanel.GetComponent<RectTransform>().anchoredPosition = new Vector2(Input.mousePosition.x + (GameObject.Find("Tooltip Panel").GetComponent<RectTransform>().rect.width / 2), Input.mousePosition.y - Screen.height - (GameObject.Find("Tooltip Panel").GetComponent<RectTransform>().rect.height / 2));

        if (levelComplete && levelChanged)
            levelComplete = false;

		if(Input.GetKeyDown(KeyCode.U))
			StartCoroutine(GetUserFromSession());
        
		//Reset Selected arrow each frame
		if(currentArrow)
			currentArrow.GetComponent<Renderer>().material.color = Color.white;

		#region Allow User To Clear Entire Level
		//if(Input.GetKeyDown(KeyCode.Backspace))
		//{
        //    ClearLevel();
		//}
		#endregion

		Ray mouseRay = Camera.main.ScreenPointToRay (Input.mousePosition);

        //Destroy the cursor this frame if one is present, so the next can be spawned
        if (cursor)
            Destroy(cursor);

        //Check if mouse is being hovered over valid level space and allow to user to create or destroy aspects of the level
        if (ground.Raycast(mouseRay, out hitDist) && ValidMousePos() && !helpEnabled)
		{
			#region Create Appropriate Cursor If Mouse Is Within Bounds Of Level
			mouseVector = mouseRay.GetPoint(hitDist);
			mouseVector = new Vector3(Mathf.Round(mouseRay.GetPoint(hitDist).x / 2) * 2,0,Mathf.Round(mouseRay.GetPoint(hitDist).z / 2) * 2);

			if((int)(mouseVector.x / 2) >= 0 && (int)(mouseVector.z / 2) >= 0 && (int)(mouseVector.x / 2) < currentWidth && (int)(mouseVector.z / 2) < currentLength)
			{
				cursorOOB = false;
				if(selectedLayer == 'G' && groundLayout[(int)(mouseVector.x / 2), (int)(mouseVector.z / 2)] == null ||
                   selectedLayer == 'E' && entityLayout[(int)(mouseVector.x / 2), (int)(mouseVector.z / 2)] == null && groundLayout[(int)(mouseVector.x / 2), (int)(mouseVector.z / 2)] != null && groundLayout[(int)(mouseVector.x / 2), (int)(mouseVector.z / 2)] != 'P' && mechanismLayout[(int)(mouseVector.x / 2), (int)(mouseVector.z / 2)] == null && groundLayout[(int)(mouseVector.x / 2), (int)(mouseVector.z / 2)] != 'X' ||
                   selectedLayer == 'M' && selectedBlock != 'T' && mechanismLayout[(int)(mouseVector.x / 2), (int)(mouseVector.z / 2)] == null && groundLayout[(int)(mouseVector.x / 2), (int)(mouseVector.z / 2)] != null && groundLayout[(int)(mouseVector.x / 2), (int)(mouseVector.z / 2)] != 'P' && entityLayout[(int)(mouseVector.x / 2), (int)(mouseVector.z / 2)] == null && groundLayout[(int)(mouseVector.x / 2), (int)(mouseVector.z / 2)] != 'X' ||
                   selectedLayer == 'M' && selectedBlock == 'T' && mechanismLayout[(int)(mouseVector.x / 2), (int)(mouseVector.z / 2)] != null)
				{
					validChoice = true;
				}
				else
				{
					validChoice = false;
				}
			}
			else
			{
				cursorOOB = true;
			}

			if(!cursorOOB)
			{
				if(validChoice)
				{
					cursor = Instantiate(Resources.Load("ValidChoice"), (selectedLayer == 'G') ? mouseVector - new Vector3(0,1,0) : mouseVector + new Vector3(0,1,0), Quaternion.identity) as GameObject;
				}
				else
				{
					cursor = Instantiate(Resources.Load("InvalidChoice"), (selectedLayer == 'G') ? mouseVector - new Vector3(0,1,0) : mouseVector + new Vector3(0,1,0), Quaternion.identity) as GameObject;
				}
			}
			#endregion

			#region Instantiate Or Destroy A Level Object Based On Users Input
			if(Input.GetMouseButton(0) && validChoice && !cursorOOB)
			{
				if(selectedLayer == 'G')
				{
					currentObject = Instantiate(GameData.GroundTypes[selectedBlock], mouseVector - new Vector3(0, 1, 0), Quaternion.identity) as GameObject;
					groundLayout[(int)(mouseVector.x / 2), (int)(mouseVector.z / 2)] = selectedBlock;
                    levelChanged = true;
                }
				else if(selectedLayer == 'E')
				{
					currentObject = Instantiate(GameData.EntityTypes[selectedBlock], mouseVector + new Vector3(0, 1, 0), Quaternion.identity) as GameObject;
					entityLayout[(int)(mouseVector.x / 2), (int)(mouseVector.z / 2)] = selectedBlock;
                    levelChanged = true;

                    if (selectedBlock == 'P')
                    {
                        if(playerX != -1)
                            StartCoroutine(DeleteBlock('E', playerX, playerY));
                        playerX = (int)(mouseVector.x / 2);
                        playerY = (int)(mouseVector.z / 2);
                    }
				}
				else if(selectedLayer == 'M')
				{
                    //If tinker is not selected, spawn in selected mechanism as usual
                    if (selectedBlock != 'T')
                    {
                        currentObject = Instantiate(GameData.MechanismTypes[selectedBlock], mouseVector + new Vector3(0, 1, 0), Quaternion.Euler(new Vector3(-90, 0, 0))) as GameObject;
                        mechanismLayout[(int)(mouseVector.x / 2), (int)(mouseVector.z / 2)] = selectedBlock;
                        mechanisms[(int)(mouseVector.x / 2), (int)(mouseVector.z / 2)] = currentObject.GetComponent<Mechanism>();
                        levelChanged = true;
                    }
                    else
                    {
                        Destroy(selectedMechObject);
                        selectedMechObject = Instantiate(Resources.Load("SelectedMechanism"), mouseVector + new Vector3(0, 1, 0), Quaternion.Euler(new Vector3(-90, 0, 0))) as GameObject;
                        selectedMechanism = mechanisms[(int)(mouseVector.x / 2), (int)(mouseVector.z / 2)];
                        OpenTinker();
                    }
                }

                if (!(selectedLayer == 'M' && selectedBlock == 'T'))
                {
                    currentObject.transform.parent = levelObjects.transform;
                    currentObject.name = selectedLayer + ((int)(mouseVector.x / 2)).ToString("00") + ((int)(mouseVector.z / 2)).ToString("00");
                    currentObject.GetComponent<Block>().Spawn(0, selectedBlock);
                }
			}
			else if(Input.GetMouseButton(1) && !validChoice && !cursorOOB)
			{
				//Stop the user from deleting ground if there is another object resting on it
				if(selectedLayer == 'G' && (entityLayout[(int)(mouseVector.x / 2), (int)(mouseVector.z / 2)] != null || mechanismLayout[(int)(mouseVector.x / 2), (int)(mouseVector.z / 2)] != null))
					return;

                //Stop the user from deleting mechanisms if they have selected an entity
                if(selectedLayer == 'E' && mechanismLayout[(int)(mouseVector.x / 2),(int)(mouseVector.z / 2)] != null)
                    return;

                //Stop the user from deleting entities if they have selected a mechanism
                if (selectedLayer == 'M' && entityLayout[(int)(mouseVector.x / 2), (int)(mouseVector.z / 2)] != null)
                    return;

                //If deleting a player entity, reset the player position variable
                if (selectedLayer == 'E' && entityLayout[(int)(mouseVector.x / 2), (int)(mouseVector.z / 2)] == 'P')
                    playerX = -1;

                StartCoroutine(DeleteBlock(selectedLayer, (int)(mouseVector.x / 2), (int)(mouseVector.z / 2)));
			}
			#endregion
		}

		#region Level Size Control Via Arrows
		//Check if user is hovering cursor over the resizable level arrows
		if(Physics.Raycast(mouseRay, out hit) && hit.collider.gameObject.tag == "EditorArrow" && ValidMousePos())
		{
			currentArrow = hit.collider.gameObject;
			currentArrow.GetComponent<Renderer>().material.color = Color.yellow;

			//Resize level depending on which arrow clicked
			if(Input.GetMouseButtonDown(0))
			{
				int sizeModifier = (currentArrow.name.Contains("Increase")) ? 1 : -1;
				if(currentArrow.transform.parent.gameObject == lengthArrows && (sizeModifier == 1 && currentLength < 29 || sizeModifier == -1 && currentLength > 4))
				{
					currentLength += sizeModifier;
					iTween.MoveTo(lengthArrows, iTween.Hash("position", new Vector3(currentWidth - 3,0,(currentLength * 2) + 1), "time", .5f));
					iTween.MoveTo(widthArrows, iTween.Hash("position", new Vector3((currentWidth * 2) + 1,0,currentLength + 1), "time", .5f));
					Camera.main.GetComponent<Grid>().ChangeGridSize(false, sizeModifier * 2);

					if(sizeModifier == -1)
						ClearLine(true, currentLength, currentWidth);

					Camera.main.GetComponent<CameraControl>().ChangePivotPoint(new Vector3(0,0, sizeModifier));
					CheckArrows();
				}
				else if(currentArrow.transform.parent.gameObject == widthArrows && (sizeModifier == 1 && currentWidth < 29 || sizeModifier == -1 && currentWidth > 4))
				{
					currentWidth += sizeModifier;
					iTween.MoveTo(lengthArrows, iTween.Hash("position", new Vector3(currentWidth - 3,0,(currentLength * 2) + 1), "time", .5f));
					iTween.MoveTo(widthArrows, iTween.Hash("position", new Vector3((currentWidth * 2) + 1,0,currentLength + 1), "time", .5f));
					Camera.main.GetComponent<Grid>().ChangeGridSize(true, sizeModifier * 2);

					if(sizeModifier == -1)
						ClearLine(false, currentWidth, currentLength);

					Camera.main.GetComponent<CameraControl>().ChangePivotPoint(new Vector3(sizeModifier,0, 0));
					CheckArrows();
				}
                levelChanged = true;
            }
        }
		#endregion
	}
        public void _03_ByteArrayParameterTest()
        {
            byte[] parameter = new byte[16];
            System.Random rng = new Random();
            rng.NextBytes(parameter);

            // Create mechanism with the byte array parameter
            Mechanism mechanism = new Mechanism(CKM.CKM_AES_CBC, parameter);
            Assert.IsTrue(mechanism.Type == (ulong)CKM.CKM_AES_CBC);

            // We access private members here just for the testing purposes
            if (Platform.UnmanagedLongSize == 4)
            {
                if (Platform.StructPackingSize == 0)
                {
                    HLA40.Mechanism mechanism40 = (HLA40.Mechanism)typeof(Mechanism).GetField("_mechanism40", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism);
                    LLA40.CK_MECHANISM ckMechanism40 = (LLA40.CK_MECHANISM)typeof(HLA40.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism40);
                    Assert.IsTrue(ckMechanism40.Mechanism == (uint)CKM.CKM_AES_CBC);
                    Assert.IsTrue(ckMechanism40.Parameter != IntPtr.Zero);
                    Assert.IsTrue(Convert.ToInt32(ckMechanism40.ParameterLen) == parameter.Length);
                }
                else
                {
                    HLA41.Mechanism mechanism41 = (HLA41.Mechanism)typeof(Mechanism).GetField("_mechanism41", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism);
                    LLA41.CK_MECHANISM ckMechanism41 = (LLA41.CK_MECHANISM)typeof(HLA41.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism41);
                    Assert.IsTrue(ckMechanism41.Mechanism == (uint)CKM.CKM_AES_CBC);
                    Assert.IsTrue(ckMechanism41.Parameter != IntPtr.Zero);
                    Assert.IsTrue(Convert.ToInt32(ckMechanism41.ParameterLen) == parameter.Length);
                }
            }
            else
            {
                if (Platform.StructPackingSize == 0)
                {
                    HLA80.Mechanism mechanism80 = (HLA80.Mechanism)typeof(Mechanism).GetField("_mechanism80", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism);
                    LLA80.CK_MECHANISM ckMechanism80 = (LLA80.CK_MECHANISM)typeof(HLA80.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism80);
                    Assert.IsTrue(ckMechanism80.Mechanism == (ulong)CKM.CKM_AES_CBC);
                    Assert.IsTrue(ckMechanism80.Parameter != IntPtr.Zero);
                    Assert.IsTrue(Convert.ToInt32(ckMechanism80.ParameterLen) == parameter.Length);
                }
                else
                {
                    HLA81.Mechanism mechanism81 = (HLA81.Mechanism)typeof(Mechanism).GetField("_mechanism81", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism);
                    LLA81.CK_MECHANISM ckMechanism81 = (LLA81.CK_MECHANISM)typeof(HLA81.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism81);
                    Assert.IsTrue(ckMechanism81.Mechanism == (ulong)CKM.CKM_AES_CBC);
                    Assert.IsTrue(ckMechanism81.Parameter != IntPtr.Zero);
                    Assert.IsTrue(Convert.ToInt32(ckMechanism81.ParameterLen) == parameter.Length);
                }
            }

            parameter = null;

            // Create mechanism with null byte array parameter
            mechanism = new Mechanism(CKM.CKM_AES_CBC, parameter);
            Assert.IsTrue(mechanism.Type == (ulong)CKM.CKM_AES_CBC);

            // We access private members here just for the testing purposes
            if (Platform.UnmanagedLongSize == 4)
            {
                if (Platform.StructPackingSize == 0)
                {
                    HLA40.Mechanism mechanism40 = (HLA40.Mechanism)typeof(Mechanism).GetField("_mechanism40", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism);
                    LLA40.CK_MECHANISM ckMechanism40 = (LLA40.CK_MECHANISM)typeof(HLA40.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism40);
                    Assert.IsTrue(ckMechanism40.Mechanism == (uint)CKM.CKM_AES_CBC);
                    Assert.IsTrue(ckMechanism40.Parameter == IntPtr.Zero);
                    Assert.IsTrue(ckMechanism40.ParameterLen == 0);
                }
                else
                {
                    HLA41.Mechanism mechanism41 = (HLA41.Mechanism)typeof(Mechanism).GetField("_mechanism41", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism);
                    LLA41.CK_MECHANISM ckMechanism41 = (LLA41.CK_MECHANISM)typeof(HLA41.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism41);
                    Assert.IsTrue(ckMechanism41.Mechanism == (uint)CKM.CKM_AES_CBC);
                    Assert.IsTrue(ckMechanism41.Parameter == IntPtr.Zero);
                    Assert.IsTrue(ckMechanism41.ParameterLen == 0);
                }
            }
            else
            {
                if (Platform.StructPackingSize == 0)
                {
                    HLA80.Mechanism mechanism80 = (HLA80.Mechanism)typeof(Mechanism).GetField("_mechanism80", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism);
                    LLA80.CK_MECHANISM ckMechanism80 = (LLA80.CK_MECHANISM)typeof(HLA80.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism80);
                    Assert.IsTrue(ckMechanism80.Mechanism == (ulong)CKM.CKM_AES_CBC);
                    Assert.IsTrue(ckMechanism80.Parameter == IntPtr.Zero);
                    Assert.IsTrue(ckMechanism80.ParameterLen == 0);
                }
                else
                {
                    HLA81.Mechanism mechanism81 = (HLA81.Mechanism)typeof(Mechanism).GetField("_mechanism81", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism);
                    LLA81.CK_MECHANISM ckMechanism81 = (LLA81.CK_MECHANISM)typeof(HLA81.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism81);
                    Assert.IsTrue(ckMechanism81.Mechanism == (ulong)CKM.CKM_AES_CBC);
                    Assert.IsTrue(ckMechanism81.Parameter == IntPtr.Zero);
                    Assert.IsTrue(ckMechanism81.ParameterLen == 0);
                }
            }
        }
Beispiel #40
0
        internal void OnStreamElement(object sender, Node e)
        {
            if (m_XmppClient == null) return;
            if ( m_XmppClient.XmppConnectionState == XmppConnectionState.Securing
                || m_XmppClient.XmppConnectionState == XmppConnectionState.StartCompression)
                return;

            if (e is Features)
            {
                Features f = e as Features;
                if (!m_XmppClient.Authenticated)
                {
                    // RECV: <stream:features><mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>
                    //			<mechanism>DIGEST-MD5</mechanism><mechanism>PLAIN</mechanism>
                    //			</mechanisms>
                    //			<register xmlns='http://jabber.org/features/iq-register'/>
                    //		</stream:features>
                    // SENT: <auth mechanism="DIGEST-MD5" xmlns="urn:ietf:params:xml:ns:xmpp-sasl"/>
                    // Select a SASL mechanism

                    SaslEventArgs args = new SaslEventArgs(f.Mechanisms);

                    if (OnSaslStart != null)
                        OnSaslStart(this, args);

                    if (args.Auto)
                    {
                        // Library handles the Sasl stuff
                        if (f.Mechanisms!=null)
                        {
                            if (m_XmppClient.UseStartTLS == false && m_XmppClient.UseSSL == false
                                && f.Mechanisms.SupportsMechanism(MechanismType.X_GOOGLE_TOKEN) )
                            {
                                // This is the only way to connect to GTalk on a unsecure Socket for now
                                // Secure authentication is done over https requests to pass the
                                // authentication credentials on a secure connection
                                args.Mechanism = protocol.sasl.Mechanism.GetMechanismName(MechanismType.X_GOOGLE_TOKEN);
                            }
            #if !(CF || CF_2)
                            else if (m_XmppClient.UseSso && f.Mechanisms.SupportsMechanism(MechanismType.GSSAPI))
                            {
                                args.Mechanism = protocol.sasl.Mechanism.GetMechanismName(MechanismType.GSSAPI);

                                string kerbPrinc = f.Mechanisms.GetMechanism(MechanismType.GSSAPI).KerberosPrincipal;
                                if (kerbPrinc != null)
                                m_XmppClient.KerberosPrincipal =
                                    f.Mechanisms.GetMechanism(MechanismType.GSSAPI).KerberosPrincipal;
                            }
            #endif
                            else if (f.Mechanisms.SupportsMechanism(MechanismType.SCRAM_SHA_1))
                            {
                                args.Mechanism = protocol.sasl.Mechanism.GetMechanismName(MechanismType.SCRAM_SHA_1);
                            }
                            else if (f.Mechanisms.SupportsMechanism(MechanismType.DIGEST_MD5))
                            {
                                args.Mechanism = protocol.sasl.Mechanism.GetMechanismName(MechanismType.DIGEST_MD5);
                            }
                            else if (f.Mechanisms.SupportsMechanism(MechanismType.PLAIN))
                            {
                                args.Mechanism = protocol.sasl.Mechanism.GetMechanismName(MechanismType.PLAIN);
                            }
                            else
                            {
                                args.Mechanism = null;
                            }
                        }
                        else
                        {
                            // Hack for Google
                            // TODO: i don't think we need this anymore. This was in an very early version of the gtalk server.
                            args.Mechanism = null;
                            //args.Mechanism = agsXMPP.protocol.sasl.Mechanism.GetMechanismName(agsXMPP.protocol.sasl.MechanismType.PLAIN);
                        }
                    }
                    if (args.Mechanism != null)
                    {
                        m_Mechanism = Factory.SaslFactory.GetMechanism(args.Mechanism);
                        // Set properties for the SASL mechanism
                        m_Mechanism.Username = m_XmppClient.Username;
                        m_Mechanism.Password = m_XmppClient.Password;
                        m_Mechanism.Server = m_XmppClient.Server;

                        m_Mechanism.ExtentedData = args.ExtentedData;
                        // Call Init Method on the mechanism
                        m_Mechanism.Init(m_XmppClient);
                    }
                    else
                    {
                        m_XmppClient.RequestLoginInfo();
                    }
                }
                else if(!m_XmppClient.Binded)
                {
                    if (f.SupportsBind)
                    {
                        m_XmppClient.DoChangeXmppConnectionState(XmppConnectionState.Binding);

                        BindIq bIq = string.IsNullOrEmpty(m_XmppClient.Resource) ? new BindIq(IqType.set) : new BindIq(IqType.set, m_XmppClient.Resource);

                        m_XmppClient.IqGrabber.SendIq(bIq, BindResult, null);
                    }
                }

            }
            else if (e is Challenge)
            {
                if (m_Mechanism != null && !m_XmppClient.Authenticated)
                {
                    m_Mechanism.Parse(e);
                }
            }
            else if (e is Success)
            {
                // SASL authentication was successfull
                if (OnSaslEnd!=null)
                    OnSaslEnd(this);

                m_XmppClient.DoChangeXmppConnectionState(XmppConnectionState.Authenticated);

                m_Mechanism = null;

                m_XmppClient.Reset();
            }
            else if (e is Failure)
            {
                // Authentication failure
                m_XmppClient.FireOnAuthError(e as Element);
            }
        }
Beispiel #41
0
        // Dispose(bool disposing) executes in two distinct scenarios.
        // If disposing equals true, the method has been called directly
        // or indirectly by a user's code. Managed and unmanaged resources
        // can be disposed.
        // If disposing equals false, the method has been called by the
        // runtime from inside the finalizer and you should not reference
        // other objects. Only unmanaged resources can be disposed.
        private void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if(!m_Disposed)
            {
                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if(disposing)
                {
                    // Dispose managed resources.
                    // Remove the event handler or we will be in trouble with too many events
                    m_XmppClient.StreamParser.OnStreamElement -= OnStreamElement;
                    m_XmppClient	= null;
                    m_Mechanism		= null;
                }

                // Call the appropriate methods to clean up
                // unmanaged resources here.
                // If disposing is false,
                // only the following code is executed.

            }
            m_Disposed = true;
        }
        public void _04_ObjectParameterTest()
        {
            byte[] data = new byte[24];
            System.Random rng = new Random();
            rng.NextBytes(data);

            // Specify mechanism parameters
            HLA.MechanismParams.CkKeyDerivationStringData parameter = new HLA.MechanismParams.CkKeyDerivationStringData(data);

            // Create mechanism with the object as parameter
            Mechanism mechanism = new Mechanism(CKM.CKM_XOR_BASE_AND_DATA, parameter);
            Assert.IsTrue(mechanism.Type == (ulong)CKM.CKM_XOR_BASE_AND_DATA);

            // We access private Mechanism member here just for the testing purposes
            if (Platform.UnmanagedLongSize == 4)
            {
                if (Platform.StructPackingSize == 0)
                {
                    HLA40.Mechanism mechanism40 = (HLA40.Mechanism)typeof(Mechanism).GetField("_mechanism40", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism);
                    LLA40.CK_MECHANISM ckMechanism40 = (LLA40.CK_MECHANISM)typeof(HLA40.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism40);
                    Assert.IsTrue(ckMechanism40.Mechanism == (uint)CKM.CKM_XOR_BASE_AND_DATA);
                    Assert.IsTrue(ckMechanism40.Parameter != IntPtr.Zero);
                    Assert.IsTrue(Convert.ToInt32(ckMechanism40.ParameterLen) == UnmanagedMemory.SizeOf(typeof(LLA40.MechanismParams.CK_KEY_DERIVATION_STRING_DATA)));
                }
                else
                {
                    HLA41.Mechanism mechanism41 = (HLA41.Mechanism)typeof(Mechanism).GetField("_mechanism41", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism);
                    LLA41.CK_MECHANISM ckMechanism41 = (LLA41.CK_MECHANISM)typeof(HLA41.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism41);
                    Assert.IsTrue(ckMechanism41.Mechanism == (uint)CKM.CKM_XOR_BASE_AND_DATA);
                    Assert.IsTrue(ckMechanism41.Parameter != IntPtr.Zero);
                    Assert.IsTrue(Convert.ToInt32(ckMechanism41.ParameterLen) == UnmanagedMemory.SizeOf(typeof(LLA41.MechanismParams.CK_KEY_DERIVATION_STRING_DATA)));
                }
            }
            else
            {
                if (Platform.StructPackingSize == 0)
                {
                    HLA80.Mechanism mechanism80 = (HLA80.Mechanism)typeof(Mechanism).GetField("_mechanism80", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism);
                    LLA80.CK_MECHANISM ckMechanism80 = (LLA80.CK_MECHANISM)typeof(HLA80.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism80);
                    Assert.IsTrue(ckMechanism80.Mechanism == (ulong)CKM.CKM_XOR_BASE_AND_DATA);
                    Assert.IsTrue(ckMechanism80.Parameter != IntPtr.Zero);
                    Assert.IsTrue(Convert.ToInt32(ckMechanism80.ParameterLen) == UnmanagedMemory.SizeOf(typeof(LLA80.MechanismParams.CK_KEY_DERIVATION_STRING_DATA)));
                }
                else
                {
                    HLA81.Mechanism mechanism81 = (HLA81.Mechanism)typeof(Mechanism).GetField("_mechanism81", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism);
                    LLA81.CK_MECHANISM ckMechanism81 = (LLA81.CK_MECHANISM)typeof(HLA81.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism81);
                    Assert.IsTrue(ckMechanism81.Mechanism == (ulong)CKM.CKM_XOR_BASE_AND_DATA);
                    Assert.IsTrue(ckMechanism81.Parameter != IntPtr.Zero);
                    Assert.IsTrue(Convert.ToInt32(ckMechanism81.ParameterLen) == UnmanagedMemory.SizeOf(typeof(LLA81.MechanismParams.CK_KEY_DERIVATION_STRING_DATA)));
                }
            }
        }
        public void _02_EmptyParameterTest()
        {
            // Create mechanism without the parameter
            Mechanism mechanism = new Mechanism(CKM.CKM_RSA_PKCS);
            Assert.IsTrue(mechanism.Type == (ulong)CKM.CKM_RSA_PKCS);

            // We access private Mechanism member just for the testing purposes
            if (Platform.UnmanagedLongSize == 4)
            {
                if (Platform.StructPackingSize == 0)
                {
                    HLA40.Mechanism mechanism40 = (HLA40.Mechanism)typeof(Mechanism).GetField("_mechanism40", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism);
                    LLA40.CK_MECHANISM ckMechanism40 = (LLA40.CK_MECHANISM)typeof(HLA40.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism40);
                    Assert.IsTrue(ckMechanism40.Mechanism == (uint)CKM.CKM_RSA_PKCS);
                    Assert.IsTrue(ckMechanism40.Parameter == IntPtr.Zero);
                    Assert.IsTrue(ckMechanism40.ParameterLen == 0);
                }
                else
                {
                    HLA41.Mechanism mechanism41 = (HLA41.Mechanism)typeof(Mechanism).GetField("_mechanism41", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism);
                    LLA41.CK_MECHANISM ckMechanism41 = (LLA41.CK_MECHANISM)typeof(HLA41.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism41);
                    Assert.IsTrue(ckMechanism41.Mechanism == (uint)CKM.CKM_RSA_PKCS);
                    Assert.IsTrue(ckMechanism41.Parameter == IntPtr.Zero);
                    Assert.IsTrue(ckMechanism41.ParameterLen == 0);
                }
            }
            else
            {
                if (Platform.StructPackingSize == 0)
                {
                    HLA80.Mechanism mechanism80 = (HLA80.Mechanism)typeof(Mechanism).GetField("_mechanism80", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism);
                    LLA80.CK_MECHANISM ckMechanism80 = (LLA80.CK_MECHANISM)typeof(HLA80.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism80);
                    Assert.IsTrue(ckMechanism80.Mechanism == (ulong)CKM.CKM_RSA_PKCS);
                    Assert.IsTrue(ckMechanism80.Parameter == IntPtr.Zero);
                    Assert.IsTrue(ckMechanism80.ParameterLen == 0);
                }
                else
                {
                    HLA81.Mechanism mechanism81 = (HLA81.Mechanism)typeof(Mechanism).GetField("_mechanism81", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism);
                    LLA81.CK_MECHANISM ckMechanism81 = (LLA81.CK_MECHANISM)typeof(HLA81.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism81);
                    Assert.IsTrue(ckMechanism81.Mechanism == (ulong)CKM.CKM_RSA_PKCS);
                    Assert.IsTrue(ckMechanism81.Parameter == IntPtr.Zero);
                    Assert.IsTrue(ckMechanism81.ParameterLen == 0);
                }
            }
        }
 public NArticulatedPlanarController(Mechanism robot)
 {
     this.robot = robot;
     pointList = new List<double[]>();
 }