How to extract a DES secret key

Modified on 2012/02/02 13:41 by Administrator — Categorized as: CSharp

Secret (simmetric) keys can be extracted from the token if the token allows extractions and/or the key is marked as extractable. This is a snippet to extract the value of a DES secret key:

// Searchs for an DES private key object
CryptokiCollection template = new CryptokiCollection();
template.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS, CryptokiObject.CKO_SECRET_KEY));
template.Add(new ObjectAttribute(ObjectAttribute.CKA_KEY_TYPE, Key.CKK_DES)); // this may be: Key.CKK_DES2, Key.CKK_DES3, Key.CKK_AES, etc.
            
// Launches the search specifying the template just created
CryptokiCollection objects = session.Objects.Find(template, 1);

if(objects.count == 0)
{
     // KEY NOT FOUND
     return false;
}

// takes the first object as key
SecretKey secretKey = (SecretKey)objects[0];

// check if extractable
if(!secretKey.Extractable)
{
    // NOT EXTRACTABLE    
    return false;
}

// Extracts the key value
byte[] keyValue= secretKey.KeyValue;