How to extract an RSA private key

Modified on 2017/07/20 12:21 by Administrator — Categorized as: CSharp

Private 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 modulus and the prìvate exponent of an RSA private key:  
// Searchs for an RSA private key object
CryptokiCollection template = new CryptokiCollection();
template.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS, CryptokiObject.CKO_PRIVATE_KEY));
template.Add(new ObjectAttribute(ObjectAttribute.CKA_KEY_TYPE, Key.CKK_RSA));
            
// Launches the search specifying the template just created
CryptokiCollection objects = session.Objects.Find(template, 1);

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

// takes the first object as key
RSAPrivateKey privateKey = (RSAPrivateKey)objects[0];

// checks if extractable
if(!privateKey.Extractable)
{
    // NOT EXTRACTABLE    
    return false;
}

// Extracts modulus and private exponent
byte[] modulus = privateKey.Modulus;
byte[] privateExponent = privateKey.PrivateExponent;