java keytool with opensc pkcs#11 provider only works with debug option enabled

心已入冬 提交于 2019-11-27 12:30:58

I got the same problem today and I digged onto the java sources until I found the source of the problem. I know this question is quite old and already have an accepted answer, but that one is not a real answer.

Basically, the SunPKCS11 provider does list all available slots, then, get the slot you specified in your config, and give the error (since you do not specified any slot and fot its default value).

When in debug, after listing all available slots, it does list all slots with a smartcard inserted. After having print all these information about the slot list, it does initialise its slotid variable overwriting what you wrote (or forget to write) in your config. The new value is a correct one since it is read from the opensc defaults.

This is the relevant code from SunPKCS11.java from openjdk project:

    long slotID = config.getSlotID();
    // ....
        if ((slotID < 0) || showInfo) {
            long[] slots = p11.C_GetSlotList(false);
            if (showInfo) {
                System.out.println("All slots: " + toString(slots));
                slots = p11.C_GetSlotList(true);
                System.out.println("Slots with tokens: " + toString(slots));
            }
            if (slotID < 0) {
                if ((slotListIndex < 0) || (slotListIndex >= slots.length)) {
                    throw new ProviderException("slotListIndex is " + slotListIndex
                        + " but token only has " + slots.length + " slots");
                }
                slotID = slots[slotListIndex];
            }
        }
        this.slotID = slotID;

So, a workaround is to always include in your config a negative value like slot = -1, so that the provider will always look for the right one.

Adding the debug flag to the command line worked for me:

keytool -providerClass sun.security.pkcs11.SunPKCS11 \
  -providerArg /home/hans/Desktop/smartcards/opensc-java.cfg \
  -providerName SunPKCS11-OpenSC -keystore NONE -storetype PKCS11 \
  -list \
  -J-Djava.security.debug=sunpkcs11

Or manually specifying the slot in the cfg file:

name = OpenSC
description = SunPKCS11 w/ OpenSC Smart card Framework
library = /usr/lib/x86_64-linux-gnu/opensc-pkcs11.so
slot = 2

I can confirm this behavior using java JDK 1.6.0_20

Even a simple java program only works with -Djava.security.debug=sunpkcs11 set.

String configName = "/etc/pkcs11_java.cfg";
Provider p = new sun.security.pkcs11.SunPKCS11(configName);
keyStore = KeyStore.getInstance("PKCS11", p);

with /etc/pkcs11_java.cfg

name=OpenSC
description = SunPKCS11 via OpenSC
library=/usr/local/lib/opensc-pkcs11.so
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!