Signing documents with SunMSCAPI and suppressing the “Enter PIN” dialog

前端 未结 2 1312
星月不相逢
星月不相逢 2021-02-03 15:46

I am developing a java code that signs documents using a certificate token. So far, everything works great, but I want to suppress the \"enter pin\" dialog because I am storing

2条回答
  •  佛祖请我去吃肉
    2021-02-03 16:50

    I implemented something similar to this once, but unfortunately the smart card driver was buggy and so the driver tried to bring up the native PIN callback implemented in the driver itself at times. But let's assume your driver does better at that.

    First of all, you need to implement a CallbackHandler, the documentation gives a good overview of the concept. In your case, it's the PasswordCallback case that's interesting to handle.

    Next, create your KeyStore as follows (exception handling omitted)

    Provider provider = Security.getProvider("SunMSCAPI");
    CallbackHandler cbh = // your implementation
    KeyStore.ProtectionParameter protection = new KeyStore.CallbackHandlerProtection(cbh);
    //get a handle of the CAPI KeyStore as before
    KeyStore.Builder keystoreBuilder = KeyStore.Builder.newInstance("Windows-MY",
                                                                    provider, 
                                                                    protection);
    KeyStore store = keystoreBuilder.getKeyStore();
    

    Then, to access the private key, do this:

    KeyStore.Entry ke = store.getEntry(alias, null);
    if (!(ke instanceof KeyStore.PrivateKeyEntry))
        throw new RuntimeException("The entry is not a private key.");
    PrivateKey key = ((KeyStore.PrivateKeyEntry) ke).getPrivateKey();
    

    The provider will automatically generate the appropriate PasswordCallbacks to be sent to your CallbackHandler. When handling the callback, you would simply pass your cached password.

    Needless to say that password caching is generally frowned upon ;)

提交回复
热议问题