0

我正在使用带有 NCryptoki dll 的 Pkcs#11 来使用我们的 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);
}
4

1 回答 1

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();
}
于 2018-05-24T16:18:58.390 回答