我正在使用Pkcs#11和NCryptoki dll来使用我们的HSM并管理密钥。
为什么这段代码有时会给我错误145(CKR_OPERATION_NOT_INITIALIZED)?我试图避免它,但我仍然遗漏了一些东西......这个错误在调用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;
}
}
openSessionTupla是
的地方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);
}
答案 0 :(得分:0)
对session.EncryptInit(mech,key)的调用可能会返回错误。 这就是后续对Encrypt的调用返回CKR_OPERATION_NOT_INITIALIZED
的原因你应该写:
long nRes = session.EncryptInit(mech, key);
if(nRer != 0) {
// manage the error
}
else {
byte[] enc = session.Encrypt(input);
session.EncryptFinal();
}