Encrypt and Decrypt with a DES3 key

Modified on 2013/04/09 20:13 by Administrator — Categorized as: CSharp

This is the snippet to Encrypt and Decrypt with a DES3 key:

// Search a DES3 secret key
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_DES3));

// Launchs the search specifying the template just created
CryptokiCollection objects = session.Objects.Find(template, 1);
SecretKey secretKey = (SecretKey)objects[0];  

// encrypt
session. EncryptInit(Mechanism.DES3_ECB, secretKey);
byte[] ciphertext = session.Encrypt(plaintext);

// decrypt
session.DecryptInit(Mechanism.DES3_ECB, secretKey);
byte[] plaintext1 = session.Decrypt(ciphertext);