I'm using Pkcs#11 with the NCryptoki dll to use our HSM and manage the keys.
Why is this code giving me, sometimes, the error 145 (CKR_OPERATION_NOT_INITIALIZED)? I'm trying to avoid it, but I am still missing something... This error happens randomly when calling the session.Encrypt().
static public byte[] Crypto(Key key, byte[] input, bool encrypt, Mechanism mech, string command)
{
//Session session = openSession();
var tupla = openSessionTupla();
var session = tupla.Item1;
try
{
Utility.Logger("Crypto encrypt " + encrypt.ToSafeString() + " mech " + mech.ToSafeString(), command);
if (encrypt)
{
session.EncryptInit(mech, key);
byte[] enc = session.Encrypt(input);
session.EncryptFinal();
session.Logout();
session.Close();
tupla.Item2.Finalize(IntPtr.Zero);
return enc;
}
else
{
session.DecryptInit(mech, key);
byte[] decriptata = session.Decrypt(input);
session.DecryptFinal();
session.Logout();
session.Close();
tupla.Item2.Finalize(IntPtr.Zero);
return decriptata;
}
}
catch (Exception e)
{
session.Logout();
session.Close();
tupla.Item2.Finalize(IntPtr.Zero);
Utility.Logger("Crypto " + e.ToSafeString(), command);
return null;
}
}
Where openSessionTupla is
public static Tuple<Session, Cryptoki> openSessionTupla()
{
Cryptoki.Licensee = Settings.LICENSEE;
Cryptoki.ProductKey = Settings.PRODUCTKEY;
Cryptoki cryptoki = new Cryptoki(Settings.PATH);
//Console.WriteLine(Settings.PATH);
//Console.WriteLine(Settings.SessionKey);
cryptoki.Initialize();
SlotList slots = cryptoki.Slots;
if (slots.Count == 0)
{
//Console.WriteLine("No slot available");
return null;
}
// Gets the first slot available
Slot slot = slots[0];
if (!slot.IsTokenPresent)
{
//Console.WriteLine("No token inserted in the slot: " + slots[0].Info.Description);
return null;
}
Token token = slot.Token;
var flags = token.Info.Flags;
//token.Info.Flags = 1609;
Session session = token.OpenSession(Session.CKF_SERIAL_SESSION | Session.CKF_RW_SESSION,
null,
null);
int nRes = session.Login(Session.CKU_USER, Settings.SessionKey);
return new Tuple<Session, Cryptoki>(session, cryptoki);
}
Maybe the call to session.EncryptInit(mech, key) returns an error. this is why the subsequent call to Encrypt returns CKR_OPERATION_NOT_INITIALIZED
You should write: