Net.Pkcs11Interop.HighLevelAPI81.Session.GenerateKey C# (CSharp) Method

GenerateKey() public method

Generates a secret key or set of domain parameters, creating a new object
public GenerateKey ( Mechanism mechanism, List attributes ) : ObjectHandle
mechanism Mechanism Generation mechanism
attributes List Attributes of the new key or set of domain parameters
return ObjectHandle
        public ObjectHandle GenerateKey(Mechanism mechanism, List<ObjectAttribute> attributes)
        {
            if (this._disposed)
                throw new ObjectDisposedException(this.GetType().FullName);

            if (mechanism == null)
                throw new ArgumentNullException("mechanism");

            CK_MECHANISM ckMechanism = mechanism.CkMechanism;

            CK_ATTRIBUTE[] template = null;
            ulong templateLength = 0;
            
            if (attributes != null)
            {
                templateLength = Convert.ToUInt64(attributes.Count);
                template = new CK_ATTRIBUTE[templateLength];
                for (int i = 0; i < Convert.ToInt32(templateLength); i++)
                    template[i] = attributes[i].CkAttribute;
            }

            ulong keyId = CK.CK_INVALID_HANDLE;
            CKR rv = _p11.C_GenerateKey(_sessionId, ref ckMechanism, template, templateLength, ref keyId);
            if (rv != CKR.CKR_OK)
                throw new Pkcs11Exception("C_GenerateKey", rv);

            return new ObjectHandle(keyId);
        }

Usage Example

Example #1
0
 /// <summary>
 /// Generates symetric key.
 /// </summary>
 /// <param name='session'>Read-write session with user logged in</param>
 /// <returns>Object handle</returns>
 public static ObjectHandle GenerateKey(Session session)
 {
     // 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));
     objectAttributes.Add(new ObjectAttribute(CKA.CKA_DERIVE, true));
     objectAttributes.Add(new ObjectAttribute(CKA.CKA_EXTRACTABLE, true));
     
     // Specify key generation mechanism
     Mechanism mechanism = new Mechanism(CKM.CKM_DES3_KEY_GEN);
     
     // Generate key
     return session.GenerateKey(mechanism, objectAttributes);
 }