/// <summary> /// Loads all Cryptoki certificates for the specified certificate store (if supported). /// </summary> /// <param name="session">The Cryptoki session context.</param> /// <param name="storeName">The certificate store moniker.</param> /// <returns>The loaded cryptoki certificate object array</returns> public static CryptokiCertificate[] LoadCertificates(Session session, string storeName) { CryptokiCertificate[] certs; CryptokiAttribute[] attribs = new CryptokiAttribute[] { new CryptokiAttribute(CryptokiAttribute.CryptokiType.Class, Utility.ConvertToBytes((int)CryptokiClass.CERTIFICATE)), new CryptokiAttribute(CryptokiAttribute.CryptokiType.Label, UTF8Encoding.UTF8.GetBytes(storeName)), }; FindObjectEnum objEnum = new FindObjectEnum(session, attribs); if (objEnum.Count == 0) { certs = new CryptokiCertificate[0]; } else { Array ar = objEnum.GetNext(objEnum.Count); certs = ar as CryptokiCertificate[]; } objEnum.Close(); return(certs); }
/// <summary> /// Creates a object in the given Cryptoki session context with specified object atrributes. /// </summary> /// <param name="session">The Cryptoki session context.</param> /// <param name="template">The object attribute template.</param> /// <returns>The cryptoki object created.</returns> public static CryptokiObject CreateObject(Session session, CryptokiAttribute[] template) { CryptokiObject ret = CreateObjectInternal(session, template); session.AddSessionObject(ret); return ret; }
/// <summary> /// Copies the cryptoki object. /// </summary> /// <param name="template">The object attribute template.</param> /// <returns>The new cryptoki object.</returns> public CryptokiObject Copy(CryptokiAttribute[] template) { CryptokiObject ret = CopyInternal(template); m_session.AddSessionObject(ret); return ret; }
/// <summary> /// Creates a CryptoKey in the specfied session context with the specified key attribute template. /// </summary> /// <param name="session">The Cryptoki session context.</param> /// <param name="keyTemplate">The Cryptoki attribute template that specifies key properties.</param> /// <returns></returns> public static CryptoKey LoadKey(Session session, CryptokiAttribute[] keyTemplate) { CryptoKey key = CryptokiObject.CreateObject(session, keyTemplate) as CryptoKey; key.m_keyType = KeyType.INVALID; return key; }
/// <summary> /// Deletes the Cryptoki object from the specified storage location. /// </summary> /// <param name="location">The storage location.</param> /// <returns>true if the delete was successful, false otherwise.</returns> public virtual bool Delete(string location) { CryptokiAttribute[] attribs = new CryptokiAttribute[] { new CryptokiAttribute(CryptokiAttribute.CryptokiType.Label, UTF8Encoding.UTF8.GetBytes(location)), new CryptokiAttribute(CryptokiAttribute.CryptokiType.Persist, Utility.ConvertToBytes(0)), }; return(this.SetAttributeValues(attribs)); }
/// <summary> /// Deletes the Cryptoki object from the specified storage location. /// </summary> /// <param name="location">The storage location.</param> /// <returns>true if the delete was successful, false otherwise.</returns> public virtual bool Delete(string location) { CryptokiAttribute[] attribs = new CryptokiAttribute[] { new CryptokiAttribute(CryptokiAttribute.CryptokiType.Label, UTF8Encoding.UTF8.GetBytes(location)), new CryptokiAttribute(CryptokiAttribute.CryptokiType.Persist, Utility.ConvertToBytes(0)), }; return this.SetAttributeValues(attribs); }
/// <summary> /// Saves the Cryptoki object as the given name to the specified store location. /// </summary> /// <param name="name">Name to save the crypto object as.</param> /// <param name="location">Location to store the object.</param> /// <param name="level">Secure storage priority level.</param> /// <returns>true if the save was successful, false otherwise.</returns> public virtual bool Save(string name, string location, SecureStorageLevel level) { CryptokiAttribute[] attribs = new CryptokiAttribute[] { new CryptokiAttribute(CryptokiAttribute.CryptokiType.Label, UTF8Encoding.UTF8.GetBytes(location)), new CryptokiAttribute(CryptokiAttribute.CryptokiType.ObjectID, UTF8Encoding.UTF8.GetBytes(name)), new CryptokiAttribute(CryptokiAttribute.CryptokiType.Persist, Utility.ConvertToBytes(1)), }; return this.SetAttributeValues(attribs); }
/// <summary> /// Saves the Cryptoki object as the given name to the specified store location. /// </summary> /// <param name="name">Name to save the crypto object as.</param> /// <param name="location">Location to store the object.</param> /// <param name="level">Secure storage priority level.</param> /// <returns>true if the save was successful, false otherwise.</returns> public virtual bool Save(string name, string location, SecureStorageLevel level) { CryptokiAttribute[] attribs = new CryptokiAttribute[] { new CryptokiAttribute(CryptokiAttribute.CryptokiType.Label, UTF8Encoding.UTF8.GetBytes(location)), new CryptokiAttribute(CryptokiAttribute.CryptokiType.ObjectID, UTF8Encoding.UTF8.GetBytes(name)), new CryptokiAttribute(CryptokiAttribute.CryptokiType.Persist, Utility.ConvertToBytes(1)), }; return(this.SetAttributeValues(attribs)); }
/// <summary> /// Generates a random symmetric key for use in the signing process. /// </summary> /// <param name="keySize">Size of the symmetric key in bits</param> private void GenerateKey(int keySize) { CryptokiAttribute[] attribs = new CryptokiAttribute[] { new CryptokiAttribute(CryptokiAttribute.CryptokiType.ValueLen, Utility.ConvertToBytes( keySize )) }; KeyValue = CryptoKey.GenerateKey(m_session, new Mechanism(MechanismType.GENERIC_SECRET_KEY_GEN), attribs); OwnsKey = true; m_mechanism.Parameter = KeyValue.Handle; Initialize(); }
/// <summary> /// Creates a Cryptoki certificate object with the specified byte array and password. /// </summary> /// <param name="session">The Cryptoki session context.</param> /// <param name="certData">The certificate data in PEM, P12, DER, etc. format.</param> /// <param name="password">The string password for decrypting the certificate</param> /// <returns>The loaded cryptoki certificate object</returns> public static CryptokiCertificate LoadCertificate( Session session, //CertificateType type, //CertificateCategory category, //string name, byte[] certData, string password ) { CryptokiAttribute[] attribs = new CryptokiAttribute[] { new CryptokiAttribute(CryptokiAttribute.CryptokiType.Class, Utility.ConvertToBytes((int)CryptokiClass.CERTIFICATE)), //new CryptokiAttribute(CryptokiAttribute.CryptokiType.CertificateType , Utility.ConvertToBytes((int)type )), //new CryptokiAttribute(CryptokiAttribute.CryptokiType.CertficateCategory, Utility.ConvertToBytes((int)category )), //new CryptokiAttribute(CryptokiAttribute.CryptokiType.Label , UTF8Encoding.UTF8.GetBytes(name )), new CryptokiAttribute(CryptokiAttribute.CryptokiType.Password, UTF8Encoding.UTF8.GetBytes(password)), new CryptokiAttribute(CryptokiAttribute.CryptokiType.Value, certData), }; return(CreateCertificate(session, attribs)); }
/// <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; }
/// <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; }
public MFTestResults HmacTest_Compare() { bool testResult = false; if (!m_isEmulator) return MFTestResults.Skip; try { CryptokiAttribute[] secretKey = new CryptokiAttribute[] { new CryptokiAttribute(CryptokiAttribute.CryptokiType.Class , new byte[] { 4, 0, 0, 0}), new CryptokiAttribute(CryptokiAttribute.CryptokiType.KeyType, new byte[] { 0x10, 0, 0, 0}), new CryptokiAttribute(CryptokiAttribute.CryptokiType.Value , new byte[20]) }; Mechanism mech = new Mechanism(MechanismType.SHA_1_HMAC); using (Session openSession = new Session("", mech.Type)) { using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(openSession)) { rng.GetBytes(secretKey[2].Value); } using (CryptoKey keyOpen = CryptoKey.LoadKey(openSession, secretKey)) { string dataToSign = "This is a simple message to be encrypted"; byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(dataToSign); using (KeyedHashAlgorithm hmacOpenSSL = new KeyedHashAlgorithm(KeyedHashAlgorithmType.HMACSHA1, keyOpen)) { byte[] hmac1 = hmacOpenSSL.ComputeHash(data); using (Session emuSession = new Session("Emulator_Crypto", mech.Type)) { using (CryptoKey keyEmu = CryptoKey.LoadKey(emuSession, secretKey)) { using (KeyedHashAlgorithm hmacEmu = new KeyedHashAlgorithm(KeyedHashAlgorithmType.HMACSHA1, keyEmu)) { byte[] hmac2 = hmacEmu.ComputeHash(data); testResult = true; for (int i = 0; i < hmac1.Length; i++) { if (hmac1[i] != hmac2[i]) { testResult = false; break; } } } } } } } } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); }
/// <summary> /// Exports the key in standard Windows KeyBlob format. /// </summary> /// <param name="fIncludePrivate"></param> /// <returns></returns> public byte[] ExportKey(bool fIncludePrivate) { byte[] keyData = new byte[(Size + 7)/8]; CryptokiAttribute[] keyImport = new CryptokiAttribute[] { new CryptokiAttribute(CryptokiAttribute.CryptokiType.Private, Utility.ConvertToBytes((int)(fIncludePrivate? 1 : 0))), new CryptokiAttribute(CryptokiAttribute.CryptokiType.Value, keyData), }; if (GetAttributeValues(ref keyImport)) { return keyData; } return null; }
/// <summary> /// Creates a Cryptoki certificate object with the specified byte array and password. /// </summary> /// <param name="session">The Cryptoki session context.</param> /// <param name="certData">The certificate data in PEM, P12, DER, etc. format.</param> /// <param name="password">The string password for decrypting the certificate</param> /// <returns>The loaded cryptoki certificate object</returns> public static CryptokiCertificate LoadCertificate( Session session, //CertificateType type, //CertificateCategory category, //string name, byte[] certData, string password ) { CryptokiAttribute[] attribs = new CryptokiAttribute[] { new CryptokiAttribute(CryptokiAttribute.CryptokiType.Class , Utility.ConvertToBytes((int)CryptokiClass.CERTIFICATE)), //new CryptokiAttribute(CryptokiAttribute.CryptokiType.CertificateType , Utility.ConvertToBytes((int)type )), //new CryptokiAttribute(CryptokiAttribute.CryptokiType.CertficateCategory, Utility.ConvertToBytes((int)category )), //new CryptokiAttribute(CryptokiAttribute.CryptokiType.Label , UTF8Encoding.UTF8.GetBytes(name )), new CryptokiAttribute(CryptokiAttribute.CryptokiType.Password , UTF8Encoding.UTF8.GetBytes(password )), new CryptokiAttribute(CryptokiAttribute.CryptokiType.Value , certData ), }; return CreateCertificate(session, attribs); }
/// <summary> /// Gets the property value given the specified property name. /// </summary> /// <param name="propName">The property name</param> /// <returns>The property value object</returns> public object GetProperty(CertificateProperty propName) { object retVal = null; if (m_propertyBag == null) m_propertyBag = new Hashtable(); if (m_propertyBag.Contains(propName)) { retVal = m_propertyBag[propName] as Byte[]; } else { byte[] propValue = new byte[2048]; byte[] propLen = new byte[4]; CryptokiAttribute[] props = new CryptokiAttribute[] { new CryptokiAttribute((CryptokiAttribute.CryptokiType)propName, propValue), new CryptokiAttribute( CryptokiAttribute.CryptokiType.ValueLen, propLen ), }; if(GetAttributeValues(ref props)) { switch(propName) { case CertificateProperty.KeyType: retVal = (KeyType)Utility.ConvertToInt32(propValue); break; case CertificateProperty.SignatureAlgorithm: retVal = (MechanismType)Utility.ConvertToInt32(propValue); break; case CertificateProperty.Issuer: case CertificateProperty.Subject: retVal = new string(UTF8Encoding.UTF8.GetChars(propValue)); break; case CertificateProperty.SerialNumber: case CertificateProperty.RawBytes: { int len = Utility.ConvertToInt32(propLen); if (len < propValue.Length) { byte[] tmp = new byte[len]; Array.Copy(propValue, tmp, len); propValue = tmp; } } retVal = propValue; break; case CertificateProperty.EffectiveDate: case CertificateProperty.ExpirationDate: DATE_TIME_INFO dti = new DATE_TIME_INFO(propValue); retVal = new DateTime(dti.year, dti.month, dti.day, dti.hour, dti.minute, dti.second, dti.msec); break; } } if (retVal != null) { m_propertyBag[propName] = retVal; } } return retVal; }
/// <summary> /// Unwraps the specified key data with the given wrapping key and mechanism. /// </summary> /// <param name="session">The Cryptoki session context.</param> /// <param name="mechanism">The key wrapping mechanism or algorithm.</param> /// <param name="wrappingKey">The key that will be used to unwrap the specifed keyData.</param> /// <param name="keyData">The encrypted key data.</param> /// <param name="keyTemplate">The key attribute template.</param> /// <returns>The unwrapped key object.</returns> public static CryptoKey UnwrapKey(Session session, Mechanism mechanism, CryptoKey wrappingKey, byte[] keyData, CryptokiAttribute[] keyTemplate) { CryptoKey ret = UnwrapKeyInternal(session, mechanism, wrappingKey, keyData, keyTemplate); if (ret != null) { session.AddSessionObject(ret); } return ret; }
private extern CryptokiObject CopyInternal(CryptokiAttribute[] template);
private static extern CryptoKey GenerateKeyPairInternal(Session session, Mechanism mechanism, CryptokiAttribute[] publicKeyTemplate, CryptokiAttribute[] privateKeyTemplate);
private static extern CryptoKey UnwrapKeyInternal(Session session, Mechanism mechanism, CryptoKey unwrappingKey, byte[] wrappedKey, CryptokiAttribute[] keyTemplate);
private static extern CryptoKey GenerateKeyInternal(Session session, Mechanism mechanism, CryptokiAttribute[] template);
private extern CryptoKey DeriveKeyInternal(Mechanism mechanism, CryptokiAttribute[] template);
private void GetKeyAttribs() { byte[] keyType = new byte[4]; byte[] length = new byte[4]; CryptokiAttribute[] keyTypeAttr = new CryptokiAttribute[] { new CryptokiAttribute(CryptokiAttribute.CryptokiType.KeyType, keyType), new CryptokiAttribute(CryptokiAttribute.CryptokiType.ValueBits, length), }; GetAttributeValues(ref keyTypeAttr); m_keyType = (KeyType)Utility.ConvertToInt32(keyType); m_length = Utility.ConvertToInt32(length); }
/// <summary> /// Gets the property value given the specified property name. /// </summary> /// <param name="propName">The property name</param> /// <returns>The property value object</returns> public object GetProperty(CertificateProperty propName) { object retVal = null; if (m_propertyBag == null) { m_propertyBag = new Hashtable(); } if (m_propertyBag.Contains(propName)) { retVal = m_propertyBag[propName] as Byte[]; } else { byte[] propValue = new byte[2048]; byte[] propLen = new byte[4]; CryptokiAttribute[] props = new CryptokiAttribute[] { new CryptokiAttribute((CryptokiAttribute.CryptokiType)propName, propValue), new CryptokiAttribute(CryptokiAttribute.CryptokiType.ValueLen, propLen), }; if (GetAttributeValues(ref props)) { switch (propName) { case CertificateProperty.KeyType: retVal = (KeyType)Utility.ConvertToInt32(propValue); break; case CertificateProperty.SignatureAlgorithm: retVal = (MechanismType)Utility.ConvertToInt32(propValue); break; case CertificateProperty.Issuer: case CertificateProperty.Subject: retVal = new string(UTF8Encoding.UTF8.GetChars(propValue)); break; case CertificateProperty.SerialNumber: case CertificateProperty.RawBytes: { int len = Utility.ConvertToInt32(propLen); if (len < propValue.Length) { byte[] tmp = new byte[len]; Array.Copy(propValue, tmp, len); propValue = tmp; } } retVal = propValue; break; case CertificateProperty.EffectiveDate: case CertificateProperty.ExpirationDate: DATE_TIME_INFO dti = new DATE_TIME_INFO(propValue); retVal = new DateTime(dti.year, dti.month, dti.day, dti.hour, dti.minute, dti.second, dti.msec); break; } } if (retVal != null) { m_propertyBag[propName] = retVal; } } return(retVal); }
public extern bool GetAttributeValues(ref CryptokiAttribute[] template);
private static extern CryptokiObject CreateObjectInternal(Session session, CryptokiAttribute[] template);
public extern bool SetAttributeValues(CryptokiAttribute[] template);
/// <summary> /// Creates a Cryptoki certificate object with the specified attribute array template and session context. /// </summary> /// <param name="session">The Cryptoki session context.</param> /// <param name="template">The attribute template that defines the certificate properties.</param> /// <returns>The created cryptoki certificate object</returns> public static CryptokiCertificate CreateCertificate(Session session, CryptokiAttribute[] template) { CryptokiCertificate ret = CreateObject(session, template) as CryptokiCertificate; ret.m_propertyBag = new Hashtable(); session.AddSessionObject(ret); return ret; }
/// <summary> /// Creates a FindObjectEnum object with the specified session context and object attribute template. /// </summary> /// <param name="session">The Cryptoki session context.</param> /// <param name="template">The object attribute search criteria.</param> public FindObjectEnum(Session session, CryptokiAttribute[] template) { m_session = session; FindObjectsInit(template); }
/// <summary> /// Loads all Cryptoki certificates for the specified certificate store (if supported). /// </summary> /// <param name="session">The Cryptoki session context.</param> /// <param name="storeName">The certificate store moniker.</param> /// <returns>The loaded cryptoki certificate object array</returns> public static CryptokiCertificate[] LoadCertificates(Session session, string storeName) { CryptokiCertificate[] certs; CryptokiAttribute[] attribs = new CryptokiAttribute[] { new CryptokiAttribute(CryptokiAttribute.CryptokiType.Class, Utility.ConvertToBytes((int)CryptokiClass.CERTIFICATE)), new CryptokiAttribute(CryptokiAttribute.CryptokiType.Label, UTF8Encoding.UTF8.GetBytes(storeName)), }; FindObjectEnum objEnum = new FindObjectEnum(session, attribs); if (objEnum.Count == 0) { certs = new CryptokiCertificate[0]; } else { Array ar = objEnum.GetNext(objEnum.Count); certs = ar as CryptokiCertificate[]; } objEnum.Close(); return certs; }
protected extern void FindObjectsInit(CryptokiAttribute[] template);
/// <summary> /// Initializes a new instance of the X509Certificate2 class from a Cryptoki attribute array /// </summary> /// <param name="session"></param> /// <param name="template"></param> public X509Certificate2(Session session, CryptokiAttribute[] template) { m_cert = CryptokiCertificate.CreateCertificate(session, template); Init(); }
/// <summary> /// Opens a CryptoKey with the specified key name from the underlying key store. /// </summary> /// <param name="session">The Cryptoki session context.</param> /// <param name="keyName">The name of the key to be opened.</param> /// <returns>The CryptoKey for the specifed key name.</returns> public static CryptoKey OpenKey(Session session, string keyName, string keyStore="") { CryptokiAttribute[] template = new CryptokiAttribute[] { new CryptokiAttribute(CryptokiAttribute.CryptokiType.Class, Utility.ConvertToBytes((int)CryptokiClass.OTP_KEY)), new CryptokiAttribute(CryptokiAttribute.CryptokiType.Label, System.Text.UTF8Encoding.UTF8.GetBytes(keyStore)), new CryptokiAttribute(CryptokiAttribute.CryptokiType.ObjectID, System.Text.UTF8Encoding.UTF8.GetBytes(keyName)) }; using (FindObjectEnum objects = new FindObjectEnum(session, template)) { CryptokiObject[] objs = objects.GetNext(1); if (objs != null && objs.Length == 1 && objs[0] is CryptoKey) { return (CryptoKey)objs[0]; } } return null; }
public static MFTestResults Test_EncryptCsp(SymmetricAlgorithm csp1, SymmetricAlgorithm csp2, CryptokiAttribute[] keyTemplate) { bool testResult = false; try { string dataToEncrypt = "This is a simple message to be encrypted dfjdfh "; byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(dataToEncrypt); byte[] encData = null; byte[] newData = null; csp2.Key = CryptoKey.CreateObject(csp2.Session, keyTemplate) as CryptoKey; csp1.Key = CryptoKey.CreateObject(csp1.Session, keyTemplate) as CryptoKey; csp2.IV = csp1.IV; using (ICryptoTransform encr = csp1.CreateEncryptor()) { encData = encr.TransformFinalBlock(data, 0, data.Length); } using (ICryptoTransform decr = csp2.CreateDecryptor()) { newData = decr.TransformFinalBlock(encData, 0, encData.Length); } string res = new string(System.Text.UTF8Encoding.UTF8.GetChars(newData)); //Debug.Print(dataToEncrypt); //Debug.Print(res); testResult = string.Compare(dataToEncrypt, res) == 0; } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); }
/// <summary> /// Imports a key of specifed type given the raw key bytes and key class. /// </summary> /// <param name="session">The Cryptoki session context.</param> /// <param name="keyData">The raw key data bytes.</param> /// <param name="keyClass">The class of key represented by the raw bytes.</param> /// <param name="keyType">The type of key represented by the raw bytes.</param> /// <param name="canBeExported">true if the key can be exported, false other wise.</param> /// <returns>The key created from the specified bytes.</returns> public static CryptoKey ImportKey(Session session, byte[] keyData, KeyClass keyClass, KeyType keyType, bool canBeExported) { CryptokiAttribute[] keyImport = new CryptokiAttribute[] { new CryptokiAttribute(CryptokiAttribute.CryptokiType.Class , Utility.ConvertToBytes((int)keyClass)), new CryptokiAttribute(CryptokiAttribute.CryptokiType.KeyType, Utility.ConvertToBytes((int)keyType)), new CryptokiAttribute(CryptokiAttribute.CryptokiType.Value, keyData), new CryptokiAttribute(CryptokiAttribute.CryptokiType.Extractable, Utility.ConvertToBytes(canBeExported ? 1 : 0)), }; CryptoKey ret = LoadKey(session, keyImport); session.AddSessionObject(ret); return ret; }