How to extract an RSA public key

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

Public 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 public exponent of an RSA public key:  
// Searchs for an RSA public key object
CryptokiCollection template = new CryptokiCollection();
template.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS, CryptokiObject.CKO_PUBLIC_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)
{
     // PUBLIC KEY NOT FOUND
     return false;
}

// takes the first object as key
RSAPublicKey publicKey = (RSAPublicKey )objects[0];

// Extracts modulus and public exponent
byte[] modulus = publicKey .Modulus;
byte[] publicExponent = publicKey .PublicExponent;