How to generate an RSA Key Pair

Modified on 2017/05/15 10:33 by Administrator — Categorized as: CSharp

This is the snippet to generate an RSA Key Pair

CryptokiCollection templatePub = new CryptokiCollection();

templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS, CryptokiObject.CKO_PUBLIC_KEY));

templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_DERIVE,false));

templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_ENCRYPT,true));

templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_KEY_TYPE, Key.CKK_RSA));

templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_LOCAL, true));

templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_MODIFIABLE,true));

templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_MODULUS_BITS,1024));  // 1024 bit key pair

templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_PRIVATE,false));

templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_TOKEN, true));

templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_VERIFY, true));

templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_VERIFY_RECOVER, false));

templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_WRAP, true));

templatePub.Add(new ObjectAttribute(ObjectAttribute.CKA_LABEL, "jina's pubkey"));

CryptokiCollection templatePri = new CryptokiCollection();

templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS, CryptokiObject.CKO_PRIVATE_KEY));

templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_DECRYPT, true));

templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_DERIVE, false));

templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_EXTRACTABLE, true));

templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_KEY_TYPE, Key.CKK_RSA));

templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_LOCAL,true));

templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_MODIFIABLE, true));

templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_NEVER_EXTRACTABLE, false));

templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_PRIVATE, true));

templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_SENSITIVE, true));

templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_SIGN, true));

templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_SIGN_RECOVER, false));

templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_TOKEN, true));

templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_UNWRAP, true));

templatePri.Add(new ObjectAttribute(ObjectAttribute.CKA_LABEL, "jina's priKey"));



Key[] keys = session.GenerateKeyPair(Mechanism.RSA_PKCS_KEY_PAIR_GEN, templatePub, templatePri);

MessageBox.Show(keys.Length.ToString());