public void _02_SignAndVerifyMultiPartTest() { using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11Library); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate key pair IObjectHandle publicKey = null; IObjectHandle privateKey = null; Helpers.GenerateKeyPair(session, out publicKey, out privateKey); // Specify signing mechanism IMechanism mechanism = Settings.Factories.MechanismFactory.Create(CKM.CKM_SHA1_RSA_PKCS); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); byte[] signature = null; bool isValid = false; // Multipart signing can be used i.e. for signing of streamed data using (MemoryStream inputStream = new MemoryStream(sourceData)) { // Sign data // Note that in real world application we would rather use bigger read buffer i.e. 4096 signature = session.Sign(mechanism, privateKey, inputStream, 8); } // Do something interesting with signature // Multipart verification can be used i.e. for signature verification of streamed data using (MemoryStream inputStream = new MemoryStream(sourceData)) { // Verify signature // Note that in real world application we would rather use bigger read buffer i.e. 4096 session.Verify(mechanism, publicKey, inputStream, signature, out isValid, 8); } // Do something interesting with verification result Assert.IsTrue(isValid); session.DestroyObject(privateKey); session.DestroyObject(publicKey); session.Logout(); } } }
private void LoosenOrganSurgeryCallback(IMechanism target, IBodyPartContainer container, ISurgeon surgeon, IEntity performer) { if (target == null || !Parent.Mechanisms.Contains(target)) { return; } performer.PopupMessage(Loc.GetString("Loosen the organ...")); // TODO do_after: Delay _disconnectedOrgans.Add(target); }
private void RemoveOrganSurgeryCallback(IMechanism target, IBodyPartContainer container, ISurgeon surgeon, IEntity performer) { if (target == null || !Parent.Mechanisms.Contains(target)) { return; } performer.PopupMessage(Loc.GetString("Remove the organ...")); // TODO do_after: Delay Parent.TryDropMechanism(performer, target, out _); _disconnectedOrgans.Remove(target); }
public void _01_BasicDigestEncryptAndDecryptDigestTest() { using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11Library); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate symetric key IObjectHandle generatedKey = Helpers.GenerateKey(session); // Generate random initialization vector byte[] iv = session.GenerateRandom(8); // Specify encryption mechanism with initialization vector as parameter IMechanism encryptionMechanism = session.Factories.MechanismFactory.Create(CKM.CKM_DES3_CBC, iv); // Specify digesting mechanism IMechanism digestingMechanism = session.Factories.MechanismFactory.Create(CKM.CKM_SHA_1); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password"); // Encrypt and digest data byte[] digest1 = null; byte[] encryptedData = null; session.DigestEncrypt(digestingMechanism, encryptionMechanism, generatedKey, sourceData, out digest1, out encryptedData); // Do something interesting with encrypted data and digest // Decrypt and digest data byte[] digest2 = null; byte[] decryptedData = null; session.DecryptDigest(digestingMechanism, encryptionMechanism, generatedKey, encryptedData, out digest2, out decryptedData); // Do something interesting with decrypted data and digest Assert.IsTrue(ConvertUtils.BytesToBase64String(sourceData) == ConvertUtils.BytesToBase64String(decryptedData)); Assert.IsTrue(ConvertUtils.BytesToBase64String(digest1) == ConvertUtils.BytesToBase64String(digest2)); session.DestroyObject(generatedKey); session.Logout(); } } }
public void _03_EncryptAndDecryptSinglePartOaepTest() { using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11Library); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate key pair IObjectHandle publicKey = null; IObjectHandle privateKey = null; Helpers.GenerateKeyPair(session, out publicKey, out privateKey); // Specify mechanism parameters ICkRsaPkcsOaepParams mechanismParams = session.Factories.MechanismParamsFactory.CreateCkRsaPkcsOaepParams( ConvertUtils.UInt64FromCKM(CKM.CKM_SHA_1), ConvertUtils.UInt64FromCKG(CKG.CKG_MGF1_SHA1), ConvertUtils.UInt64FromUInt32(CKZ.CKZ_DATA_SPECIFIED), null ); // Specify encryption mechanism with parameters IMechanism mechanism = session.Factories.MechanismFactory.Create(CKM.CKM_RSA_PKCS_OAEP, mechanismParams); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); // Encrypt data byte[] encryptedData = session.Encrypt(mechanism, publicKey, sourceData); // Do something interesting with encrypted data // Decrypt data byte[] decryptedData = session.Decrypt(mechanism, privateKey, encryptedData); // Do something interesting with decrypted data Assert.IsTrue(ConvertUtils.BytesToBase64String(sourceData) == ConvertUtils.BytesToBase64String(decryptedData)); session.DestroyObject(privateKey); session.DestroyObject(publicKey); session.Logout(); } } }
public Servo(MuMechToggle rawServo) { this.rawServo = rawServo; controlGroup = new ControlGroup(rawServo); input = new ServoInput(rawServo); if (rawServo.rotateJoint) { mechanism = new RotatingMechanism(rawServo); } else { mechanism = new TranslateMechanism(rawServo); } preset = new ServoPreset(rawServo, this); }
public override void Interact() { foreach (GameObject obj in mechanisms) { IMechanism mech = obj.GetComponent <IMechanism>(); if (mech != null) { mech.ActivateMechanism(); } } activated = !activated; if (anim != null) { anim.Play(activated ? "Active" : "Inactive"); } }
public void _02_EmptyParameterTest() { // Create mechanism without the parameter IMechanism mechanism = Settings.Factories.MechanismFactory.Create(CKM.CKM_RSA_PKCS); Assert.IsTrue(mechanism.Type == ConvertUtils.UInt64FromCKM(CKM.CKM_RSA_PKCS)); // We access private Mechanism member just for the testing purposes if (Platform.NativeULongSize == 4) { if (Platform.StructPackingSize == 0) { HLA40.Mechanism mechanism40 = (HLA40.Mechanism)mechanism; LLA40.CK_MECHANISM ckMechanism40 = (LLA40.CK_MECHANISM) typeof(HLA40.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism40); Assert.IsTrue(ckMechanism40.Mechanism == ConvertUtils.UInt32FromCKM(CKM.CKM_RSA_PKCS)); Assert.IsTrue(ckMechanism40.Parameter == IntPtr.Zero); Assert.IsTrue(ckMechanism40.ParameterLen == 0); } else { HLA41.Mechanism mechanism41 = (HLA41.Mechanism)mechanism; LLA41.CK_MECHANISM ckMechanism41 = (LLA41.CK_MECHANISM) typeof(HLA41.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism41); Assert.IsTrue(ckMechanism41.Mechanism == ConvertUtils.UInt32FromCKM(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)mechanism; LLA80.CK_MECHANISM ckMechanism80 = (LLA80.CK_MECHANISM) typeof(HLA80.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism80); Assert.IsTrue(ckMechanism80.Mechanism == ConvertUtils.UInt64FromCKM(CKM.CKM_RSA_PKCS)); Assert.IsTrue(ckMechanism80.Parameter == IntPtr.Zero); Assert.IsTrue(ckMechanism80.ParameterLen == 0); } else { HLA81.Mechanism mechanism81 = (HLA81.Mechanism)mechanism; LLA81.CK_MECHANISM ckMechanism81 = (LLA81.CK_MECHANISM) typeof(HLA81.Mechanism).GetField("_ckMechanism", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(mechanism81); Assert.IsTrue(ckMechanism81.Mechanism == ConvertUtils.UInt64FromCKM(CKM.CKM_RSA_PKCS)); Assert.IsTrue(ckMechanism81.Parameter == IntPtr.Zero); Assert.IsTrue(ckMechanism81.ParameterLen == 0); } } }
/// <summary> /// Generates symetric key. /// </summary> /// <param name='session'>Read-write session with user logged in</param> /// <returns>Object handle</returns> public static IObjectHandle GenerateKey(ISession session) { // Prepare attribute template of new key List <IObjectAttribute> objectAttributes = new List <IObjectAttribute>(); objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY)); objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3)); objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_ENCRYPT, true)); objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_DECRYPT, true)); objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_DERIVE, true)); objectAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_EXTRACTABLE, true)); // Specify key generation mechanism IMechanism mechanism = Settings.Factories.MechanismFactory.CreateMechanism(CKM.CKM_DES3_KEY_GEN); // Generate key return(session.GenerateKey(mechanism, objectAttributes)); }
public Servo(ModuleIRServo rawServo) { this.rawServo = rawServo; controlGroup = new ControlGroup(rawServo); input = new ServoInput(rawServo); if (rawServo.rotateJoint) { mechanism = new RotatingMechanism(rawServo); } else { mechanism = new TranslateMechanism(rawServo); } motor = new ServoMotor(rawServo); preset = new ServoPreset(rawServo, this); }
public static byte[] Sign(this ISession session, IMechanism mechanism, IObjectHandle objectHandle, SecureString securePin, byte[] data) { if (mechanism == null) { throw new ArgumentNullException(nameof(mechanism)); } if (objectHandle == null) { throw new ArgumentNullException(nameof(objectHandle)); } if (data == null) { throw new ArgumentNullException(nameof(data)); } return(SecureStringHelper.ExecuteWithSecureString <byte[]>(securePin, Encoding.UTF8, pin => session.Sign(mechanism, objectHandle, pin, data))); }
/// <summary> /// Verifies a digital signature against the specified hash value /// </summary> /// <param name="hash">The hash value of a block of data</param> /// <param name="signature">The digital signature to be verified</param> /// <returns>True if the hash value equals the decrypted signature, false otherwise</returns> public override bool VerifyHash(byte[] hash, byte[] signature) { if (hash == null || hash.Length == 0) { throw new ArgumentNullException(nameof(hash)); } if (signature == null || signature.Length == 0) { throw new ArgumentNullException(nameof(signature)); } using (ISession session = _certContext.TokenContext.SlotContext.Slot.OpenSession(SessionType.ReadOnly)) using (IMechanism mechanism = session.Factories.MechanismFactory.Create(CKM.CKM_ECDSA)) { session.Verify(mechanism, _certContext.PubKeyHandle, hash, signature, out bool isValid); return(isValid); } }
public void ActivateMechanism() { if (activated) { foreach (GameObject obj in mechanisms) { IMechanism mech = obj.GetComponent <IMechanism>(); if (mech != null) { mech.ActivateMechanism(); } } activated = false; if (anim != null) { anim.Play("Inactive"); } } }
public void _01_BasicSignAndVerifyRecoverTest() { using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11Library); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate key pair IObjectHandle publicKey = null; IObjectHandle privateKey = null; Helpers.GenerateKeyPair(session, out publicKey, out privateKey); // Specify signing mechanism IMechanism mechanism = Settings.Factories.MechanismFactory.Create(CKM.CKM_RSA_PKCS); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); // Sign data byte[] signature = session.SignRecover(mechanism, privateKey, sourceData); // Do something interesting with signature // Verify signature bool isValid = false; byte[] recoveredData = session.VerifyRecover(mechanism, publicKey, signature, out isValid); // Do something interesting with verification result and recovered data Assert.IsTrue(isValid); Assert.IsTrue(ConvertUtils.BytesToBase64String(sourceData) == ConvertUtils.BytesToBase64String(recoveredData)); session.DestroyObject(privateKey); session.DestroyObject(publicKey); session.Logout(); } } }
/// <summary> /// Generates a digital signature for the specified hash value /// </summary> /// <param name="hash">The hash value of the data that is being signed</param> /// <returns>A digital signature that consists of the given hash value encrypted with the private key</returns> public override byte[] SignHash(byte[] hash) { if (hash == null || hash.Length == 0) { throw new ArgumentNullException(nameof(hash)); } using (ISession session = _certContext.TokenContext.SlotContext.Slot.OpenSession(SessionType.ReadOnly)) using (IMechanism mechanism = session.Factories.MechanismFactory.Create(CKM.CKM_ECDSA)) { if (_certContext.KeyUsageRequiresLogin) { return(session.Sign(mechanism, _certContext.PrivKeyHandle, PinProviderUtils.GetKeyPin(_certContext), hash)); } else { return(session.Sign(mechanism, _certContext.PrivKeyHandle, hash)); } } }
public void _01_EncryptAndDecryptSinglePartTest() { using (IPkcs11 pkcs11 = Settings.Factories.Pkcs11Factory.CreatePkcs11(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate symetric key IObjectHandle generatedKey = Helpers.GenerateKey(session); // Generate random initialization vector byte[] iv = session.GenerateRandom(8); // Specify encryption mechanism with initialization vector as parameter IMechanism mechanism = Settings.Factories.MechanismFactory.CreateMechanism(CKM.CKM_DES3_CBC, iv); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password"); // Encrypt data byte[] encryptedData = session.Encrypt(mechanism, generatedKey, sourceData); // Do something interesting with encrypted data // Decrypt data byte[] decryptedData = session.Decrypt(mechanism, generatedKey, encryptedData); // Do something interesting with decrypted data Assert.IsTrue(ConvertUtils.BytesToBase64String(sourceData) == ConvertUtils.BytesToBase64String(decryptedData)); session.DestroyObject(generatedKey); session.Logout(); } } }
/// <summary> /// Игрок нажал на плиту /// </summary> public virtual void OnTriggerEnter2D(Collider2D other) { if (!activated) { if (other.gameObject == SpecialFunctions.player) { activated = true; if (anim != null) { anim.Play("Active"); } foreach (GameObject obj in mechanisms) { IMechanism mech = obj.GetComponent <IMechanism>(); if (mech != null) { mech.ActivateMechanism(); } } } } }
/// <summary> /// Generates asymetric key pair. /// </summary> /// <param name='session'>Read-write session with user logged in</param> /// <param name='publicKeyHandle'>Output parameter for public key object handle</param> /// <param name='privateKeyHandle'>Output parameter for private key object handle</param> public static void GenerateKeyPair(ISession session, out IObjectHandle publicKeyHandle, out IObjectHandle privateKeyHandle) { // The CKA_ID attribute is intended as a means of distinguishing multiple key pairs held by the same subject byte[] ckaId = session.GenerateRandom(20); // Prepare attribute template of new public key List <IObjectAttribute> publicKeyAttributes = new List <IObjectAttribute>(); publicKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_TOKEN, true)); publicKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_PRIVATE, false)); publicKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_LABEL, Settings.ApplicationName)); publicKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_ID, ckaId)); publicKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_ENCRYPT, true)); publicKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_VERIFY, true)); publicKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_VERIFY_RECOVER, true)); publicKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_WRAP, true)); publicKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_MODULUS_BITS, 1024)); publicKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_PUBLIC_EXPONENT, new byte[] { 0x01, 0x00, 0x01 })); // Prepare attribute template of new private key List <IObjectAttribute> privateKeyAttributes = new List <IObjectAttribute>(); privateKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_TOKEN, true)); privateKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_PRIVATE, true)); privateKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_LABEL, Settings.ApplicationName)); privateKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_ID, ckaId)); privateKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_SENSITIVE, true)); privateKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_DECRYPT, true)); privateKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_SIGN, true)); privateKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_SIGN_RECOVER, true)); privateKeyAttributes.Add(Settings.Factories.ObjectAttributeFactory.CreateObjectAttribute(CKA.CKA_UNWRAP, true)); // Specify key generation mechanism IMechanism mechanism = Settings.Factories.MechanismFactory.CreateMechanism(CKM.CKM_RSA_PKCS_KEY_PAIR_GEN); // Generate key pair session.GenerateKeyPair(mechanism, publicKeyAttributes, privateKeyAttributes, out publicKeyHandle, out privateKeyHandle); }
public void GenerateSymmetricKey(CKK keyType, List <IObjectAttribute> objectAttributes) { if (objectAttributes == null) { throw new ArgumentNullException("objectAttributes"); } if (!Pkcs11Admin.Instance.Config.SecretKeyAttributes.TypeSpecificAttributes.ContainsKey((ulong)keyType)) { throw new Exception("Unsupported key type"); } CKM?mechanismType = Pkcs11Admin.Instance.Config.SecretKeyAttributes.TypeSpecificAttributes[(ulong)keyType].KeyGenerationMechanism; if (mechanismType == null) { throw new Exception("Key generation mechanism not specified"); } using (ISession session = _slot.OpenSession(SessionType.ReadWrite)) using (IMechanism mechanism = session.Factories.MechanismFactory.Create(mechanismType.Value)) session.GenerateKey(mechanism, objectAttributes); }
public void GenerateCsr(Pkcs11KeyInfo privKeyInfo, Pkcs11KeyInfo pubKeyInfo, DnEntry[] dnEntries, HashAlgorithm hashAlgorithm, out string fileName, out byte[] fileContent) { string signatureAlgorithmOid = hashAlgorithm.SignatureAlgorithmOid[(CKK)privKeyInfo.CkaKeyType]; X509Name x509Name = Utils.CreateX509Name(dnEntries); AsymmetricKeyParameter publicKeyParameters = GetPubKeyParams(privKeyInfo, pubKeyInfo); Pkcs10CertificationRequestDelaySigned pkcs10 = new Pkcs10CertificationRequestDelaySigned(signatureAlgorithmOid, x509Name, publicKeyParameters, null); byte[] dataToSign = pkcs10.GetDataToSign(); byte[] digest = hashAlgorithm.ComputeDigest(dataToSign); byte[] digestInfo = Utils.CreateDigestInfo(digest, hashAlgorithm.Oid); byte[] signature = null; using (ISession session = _slot.OpenSession(SessionType.ReadWrite)) using (IMechanism mechanism = session.Factories.MechanismFactory.Create(CKM.CKM_RSA_PKCS)) signature = session.Sign(mechanism, privKeyInfo.ObjectHandle, digestInfo); pkcs10.SignRequest(new DerBitString(signature)); byte[] csr = pkcs10.GetDerEncoded(); fileName = (!string.IsNullOrEmpty(privKeyInfo.CkaLabel)) ? Utils.NormalizeFileName(privKeyInfo.CkaLabel + ".csr") : "pkcs10.csr"; fileContent = csr; }
public void _01_DigestSinglePartTest() { using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11Library); // Open RO session using (ISession session = slot.OpenSession(SessionType.ReadOnly)) { // Specify digesting mechanism IMechanism mechanism = Settings.Factories.MechanismFactory.Create(CKM.CKM_SHA_1); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); // Digest data byte[] digest = session.Digest(mechanism, sourceData); // Do something interesting with digest value Assert.IsTrue(ConvertUtils.BytesToBase64String(digest) == "e1AsOh9IyGCa4hLN+2Od7jlnP14="); } } }
public void _01_BasicDeriveKeyTest() { using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, Settings.Pkcs11LibraryPath, Settings.AppType)) { // Find first slot with token present ISlot slot = Helpers.GetUsableSlot(pkcs11Library); // Open RW session using (ISession session = slot.OpenSession(SessionType.ReadWrite)) { // Login as normal user session.Login(CKU.CKU_USER, Settings.NormalUserPin); // Generate symetric key IObjectHandle baseKey = Helpers.GenerateKey(session); // Generate random data needed for key derivation byte[] data = session.GenerateRandom(24); // Specify mechanism parameters ICkKeyDerivationStringData mechanismParams = Settings.Factories.MechanismParamsFactory.CreateCkKeyDerivationStringData(data); // Specify derivation mechanism with parameters IMechanism mechanism = Settings.Factories.MechanismFactory.Create(CKM.CKM_XOR_BASE_AND_DATA, mechanismParams); // Derive key IObjectHandle derivedKey = session.DeriveKey(mechanism, baseKey, null); // Do something interesting with derived key Assert.IsTrue(derivedKey.ObjectId != CK.CK_INVALID_HANDLE); session.DestroyObject(baseKey); session.DestroyObject(derivedKey); session.Logout(); } } }
public void _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 class implementing IMechanism interface. IMechanism mechanism1 = Settings.Factories.MechanismFactory.Create(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 (IMechanism mechanism2 = Settings.Factories.MechanismFactory.Create(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. IMechanism mechanism3 = Settings.Factories.MechanismFactory.Create(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 }
public static void Derive_GostR3410_12_Key(ISession session, IObjectHandle publicKeyHandle, IObjectHandle privateKeyHandle, byte[] ukm, out IObjectHandle derivedKeyHandle) { // Шаблон для создания ключа обмена var derivedKeyAttributes = new List <IObjectAttribute> { Settings.Factories.ObjectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY), Settings.Factories.ObjectAttributeFactory.Create(CKA.CKA_LABEL, Settings.DerivedGost28147_89KeyLabel), Settings.Factories.ObjectAttributeFactory.Create(CKA.CKA_KEY_TYPE, CKK.CKK_GOST28147), Settings.Factories.ObjectAttributeFactory.Create(CKA.CKA_TOKEN, false), Settings.Factories.ObjectAttributeFactory.Create(CKA.CKA_MODIFIABLE, true), Settings.Factories.ObjectAttributeFactory.Create(CKA.CKA_PRIVATE, true), Settings.Factories.ObjectAttributeFactory.Create(CKA.CKA_EXTRACTABLE, true), Settings.Factories.ObjectAttributeFactory.Create(CKA.CKA_SENSITIVE, false) }; // Получаем публичный ключ по его Id var attributes = new List <CKA> { CKA.CKA_VALUE }; List <IObjectAttribute> publicKeyAttributes = session.GetAttributeValue(publicKeyHandle, attributes); // Определение параметров механизма наследования ключа var deriveMechanismParams = Settings.Factories.RutokenMechanismParamsFactory.CreateCkGostR3410_12_DeriveParams( (ulong)Extended_CKD.CKD_KDF_GOSTR3411_2012_256, publicKeyAttributes[0].GetValueAsByteArray(), ukm); // Определяем механизм наследования ключа IMechanism deriveMechanism = Settings.Factories.MechanismFactory.Create((CKM)Extended_CKM.CKM_GOSTR3410_12_DERIVE, deriveMechanismParams); // Наследуем ключ derivedKeyHandle = session.DeriveKey(deriveMechanism, privateKeyHandle, derivedKeyAttributes); Assert.IsTrue(derivedKeyHandle.ObjectId != CK.CK_INVALID_HANDLE); }
/// <summary> /// Взаимодействие с рычагом /// </summary> public virtual void Interact() { if (!activated) { foreach (GameObject obj in mechanisms) { IMechanism mech = obj.GetComponent <IMechanism>(); if (mech != null) { mech.ActivateMechanism(); } } activated = !activated; if (anim != null) { anim.Play(activated ? "Active" : "Inactive"); } if (!once) { once = true; SpecialFunctions.statistics.ConsiderStatistics(this); } } }
public IObjectHandle ExtendedUnwrapKey( IMechanism derivationMechanism, IObjectHandle baseKey, IMechanism unwrappingMechanism, byte[] wrappedKey, List <IObjectAttribute> keyAttributes) { if (this._disposed) { throw new ObjectDisposedException(this.GetType().FullName); } if (derivationMechanism == null) { throw new ArgumentNullException(nameof(derivationMechanism)); } if (baseKey == null) { throw new ArgumentNullException(nameof(baseKey)); } if (unwrappingMechanism == null) { throw new ArgumentNullException(nameof(unwrappingMechanism)); } if (wrappedKey == null) { throw new ArgumentNullException(nameof(wrappedKey)); } if (keyAttributes == null) { throw new ArgumentNullException(nameof(keyAttributes)); } var ckDerivationMechanism = new CK_MECHANISM() { Mechanism = (NativeULong)(derivationMechanism.Type) }; var ckUnwrappingMechanism = new CK_MECHANISM() { Mechanism = (NativeULong)(unwrappingMechanism.Type) }; // Преобразование ObjectAttributes в CK_ATTRIBUTES CK_ATTRIBUTE[] ckKeyAttributes = null; NativeULong ckKeyAttributesLen = 0; ckKeyAttributes = new CK_ATTRIBUTE[keyAttributes.Count]; for (int i = 0; i < keyAttributes.Count; i++) { ckKeyAttributes[i] = (CK_ATTRIBUTE)keyAttributes[i].ToMarshalableStructure(); } ckKeyAttributesLen = (NativeULong)(keyAttributes.Count); // Размаскирование ключа NativeULong unwrappedKey = CK.CK_INVALID_HANDLE; CKR rv = ((LowLevelAPI81.RutokenPkcs11Library)_pkcs11Library).C_EX_UnwrapKey(_sessionId, ref ckDerivationMechanism, (NativeULong)(baseKey.ObjectId), ref ckUnwrappingMechanism, wrappedKey, (NativeULong)wrappedKey.Length, ckKeyAttributes, ckKeyAttributesLen, ref unwrappedKey); if (rv != CKR.CKR_OK) { throw new Pkcs11Exception("C_EX_WrapKey", rv); } if (unwrappedKey == CK.CK_INVALID_HANDLE) { throw new InvalidOperationException("C_EX_WrapKey: invalid unwrapped key handle"); } return(new Net.Pkcs11Interop.HighLevelAPI81.ObjectHandle(unwrappedKey)); }
public byte[] ExtendedWrapKey( IMechanism generationMechanism, List <IObjectAttribute> keyAttributes, IMechanism derivationMechanism, IObjectHandle baseKey, IMechanism wrappingMechanism, ref IObjectHandle key) { if (this._disposed) { throw new ObjectDisposedException(this.GetType().FullName); } if (generationMechanism == null) { throw new ArgumentNullException(nameof(generationMechanism)); } if (derivationMechanism == null) { throw new ArgumentNullException(nameof(derivationMechanism)); } if (keyAttributes == null) { throw new ArgumentNullException(nameof(keyAttributes)); } if (baseKey == null) { throw new ArgumentNullException(nameof(baseKey)); } if (wrappingMechanism == null) { throw new ArgumentNullException(nameof(wrappingMechanism)); } var ckGenerationMechanism = new CK_MECHANISM() { Mechanism = (NativeULong)(generationMechanism.Type) }; var ckDerivationMechanism = new CK_MECHANISM() { Mechanism = (NativeULong)(derivationMechanism.Type) }; var ckWrappingMechanism = new CK_MECHANISM() { Mechanism = (NativeULong)(wrappingMechanism.Type) }; // Преобразование ObjectAttributes в CK_ATTRIBUTES CK_ATTRIBUTE[] ckKeyAttributes = null; NativeULong ckKeyAttributesLen = 0; ckKeyAttributes = new CK_ATTRIBUTE[keyAttributes.Count]; for (int i = 0; i < keyAttributes.Count; i++) { ckKeyAttributes[i] = (CK_ATTRIBUTE)keyAttributes[i].ToMarshalableStructure(); } ckKeyAttributesLen = (NativeULong)(keyAttributes.Count); // Получение длины wrapped key NativeULong generatedKey = CK.CK_INVALID_HANDLE; NativeULong wrappedKeyLen = 0; CKR rv = ((LowLevelAPI81.RutokenPkcs11Library)_pkcs11Library).C_EX_WrapKey(_sessionId, ref ckGenerationMechanism, ckKeyAttributes, ckKeyAttributesLen, ref ckDerivationMechanism, (NativeULong)(baseKey.ObjectId), ref ckWrappingMechanism, null, ref wrappedKeyLen, ref generatedKey); if (rv != CKR.CKR_OK) { throw new Pkcs11Exception("C_EX_WrapKey", rv); } if (wrappedKeyLen <= 0) { throw new InvalidOperationException( "C_EX_WrapKey: invalid wrapped key length"); } // Маскирование ключа byte[] wrappedKey = new byte[wrappedKeyLen]; rv = ((LowLevelAPI81.RutokenPkcs11Library)_pkcs11Library).C_EX_WrapKey(_sessionId, ref ckGenerationMechanism, ckKeyAttributes, ckKeyAttributesLen, ref ckDerivationMechanism, (NativeULong)(baseKey.ObjectId), ref ckWrappingMechanism, wrappedKey, ref wrappedKeyLen, ref generatedKey); if (rv != CKR.CKR_OK) { throw new Pkcs11Exception("C_EX_WrapKey", rv); } if (generatedKey == CK.CK_INVALID_HANDLE) { throw new InvalidOperationException("C_EX_WrapKey: invalid generated key handle"); } if ((NativeULong)wrappedKey.Length != wrappedKeyLen) { Array.Resize(ref wrappedKey, Convert.ToInt32(wrappedKeyLen)); } key = new Net.Pkcs11Interop.HighLevelAPI81.ObjectHandle(generatedKey); return(wrappedKey); }
/// <summary> /// Computes the signature for the specified hash value by encrypting it with the private key using the specified padding /// </summary> /// <param name="hash">The hash value of the data to be signed</param> /// <param name="hashAlgorithm">The hash algorithm used to create the hash value of the data</param> /// <param name="padding">The padding</param> /// <returns>The RSA signature for the specified hash value</returns> public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (hash == null || hash.Length == 0) { throw new ArgumentNullException(nameof(hash)); } 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.Name)); } using (ISession session = _certContext.TokenContext.SlotContext.Slot.OpenSession(SessionType.ReadOnly)) using (IMechanism mechanism = session.Factories.MechanismFactory.Create(CKM.CKM_RSA_PKCS)) { if (_certContext.KeyUsageRequiresLogin) { return(session.Sign(mechanism, _certContext.PrivKeyHandle, PinProviderUtils.GetKeyPin(_certContext), pkcs1DigestInfo)); } else { return(session.Sign(mechanism, _certContext.PrivKeyHandle, pkcs1DigestInfo)); } } } else if (padding == RSASignaturePadding.Pss) { IMechanismParamsFactory mechanismParamsFactory = _certContext.TokenContext.SlotContext.Slot.Factories.MechanismParamsFactory; ICkRsaPkcsPssParams pssMechanismParams = CreateCkRsaPkcsPssParams(mechanismParamsFactory, hash, hashAlgorithm); if (pssMechanismParams == null) { throw new NotSupportedException(string.Format("Algorithm {0} is not supported", hashAlgorithm.Name)); } using (ISession session = _certContext.TokenContext.SlotContext.Slot.OpenSession(SessionType.ReadOnly)) using (IMechanism mechanism = session.Factories.MechanismFactory.Create(CKM.CKM_RSA_PKCS_PSS, pssMechanismParams)) { if (_certContext.KeyUsageRequiresLogin) { return(session.Sign(mechanism, _certContext.PrivKeyHandle, PinProviderUtils.GetKeyPin(_certContext), hash)); } else { return(session.Sign(mechanism, _certContext.PrivKeyHandle, hash)); } } } else { throw new NotSupportedException(string.Format("Padding {0} is not supported", padding)); } }
public abstract bool CanAddMechanism(IMechanism mechanism);
/// <summary> /// Break engage. /// </summary> /// <param name="mechanism">Target mechanism.</param> public void BreakEngage(IMechanism mechanism) { engages.Remove(mechanism as Mechanism); }