How to extract a private key object

One of our customers asked an interesting questions:- "Is it possible to export a private key using NCryptoki?"

The answer is yes if, and only if, the private key is extractable (some tokens may not allow to extract a private key).
Below there is a snippet to export a 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));
            
// Launchs 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];

// check if extractable
if(!privateKey.Extractable)
{
    // NOT EXTRACTABLE    
    return false;
}
// Extract modulus and private exponent
byte[] modulus = privateKey.Modulus;
byte[] privateExponent = privateKey.PrivateExponent; 

Gravatar
Posted by Ugo Chirico Sunday, November 20, 2011 3:58:00 PM Categories: PKCS#11
2011 by Ugo Chirico

Comments

Comments are closed on this post.