10

Abstract: when using JCA over PKCS11 over OpenSC, the PIN is requested when extracting certificates.

I have got an application that needs to sign using a smartcard. The smartcard is supported by OpenSC, so I am using the Java-built-in pkcs11 wrapper provider to use it. For functional reasons, I need to obtain the certificates in the card without a PIN requested. If the user finally signs, then, of course, the PIN is needed.

I see I can do it from command line without providing a PIN:

pkcs11-tool --module C:\WINDOWS\system32\opensc-pkcs11.dll -r -a 50-MDS_Signature -y cert -o p.cer
Using slot 1 with a present token (0x1)

So far, so good.

The documentation from Oracle clearly says "The builder will prompt for a password as needed using the previously configured callback handler" (http://docs.oracle.com/javase/6/docs/technotes/guides/security/p11guide.html#Login). However, my code does always request the pin as son as I call KeyStore ks0 = ksbuilder0.getKeyStore(); even while only extracting public info (such as certificates).

Follows an extract of the code:

private static final String PKCS11_LIB = "C:\\WINDOWS\\system32\\opensc-pkcs11.dll";
private static final String NAME = "OpenSCpkcs11";
private static final String SLOT = "1";
private static final String PIN = "11111111";
private static final String ALIAS = "myCert";

[...]

private static CallbackHandler myCallbackHandler = new CallbackHandler() {
    @Override
    public void handle(Callback[] callbacks) throws IOException,
            UnsupportedCallbackException {
        for (Callback callback : callbacks) {
            if (callback instanceof PasswordCallback) {
                PasswordCallback passwordCallback = (PasswordCallback) callback;
                System.out.println(passwordCallback.getPrompt() + PIN);
                passwordCallback.setPassword(PIN.toCharArray());
            }
        }
    }
};

[...]

String configString = "name = "
  + NAME.replace(' ', '_')
  + "\n"
  + "library = "
  + PKCS11_LIB
  + "\n slot = "
  + SLOT
  + " "
  + "\n attributes = compatibility \n"
  + "attributes(*,*,*)=\n{\nCKA_TOKEN=true\nCKA_LOCAL=true\n}";
ByteArrayInputStream configStream = new ByteArrayInputStream(
    configString.getBytes());
SunPKCS11 pkcs11Provider0 = new SunPKCS11(configStream);
pkcs11Provider0.login(null, myCallbackHandler);
Security.addProvider(pkcs11Provider0);
KeyStore.CallbackHandlerProtection chp = new KeyStore.CallbackHandlerProtection(
    myCallbackHandler);
KeyStore.Builder ksbuilder0 = KeyStore.Builder.newInstance(
    "PKCS11", pkcs11Provider0, chp);
KeyStore ks0 = ksbuilder0.getKeyStore();
X509Certificate cert0 = (X509Certificate) ks0.getCertificate(ALIAS);
// System.out.println("Cert " + cert0.toString());
Principal p = cert0.getSubjectDN();
System.out.println("I am: " + cert0.getSubjectDN().getName());

It results on:

Contraseña de la tarjeta de claves PKCS11 [SunPKCS11-OpenSCpkcs11]: 11111111
2014-01-16 17:48:11.275 cannot lock memory, sensitive data may be paged to disk
I am: CN=pepe perez, SURNAME=pepe, L=qwerty

As you can see, the password is requested before the certificate is got. By means of debugging I can see that the password is requested in the line KeyStore ks0 = ksbuilder0.getKeyStore();

Any idea? Is there no way to configure it as I want? Any further idea or test?

Furthermore: do you know of any other way to access smartcards, for example directly through a JAVA2OpenSC wrapper or the like?

Thanks,

4 Answers 4

9

SOLVED

I have found a way to get the public certificate from the smart card.

    String pkcs11Config = "name = SmartCard\nlibrary = /path/to/libraby.so";
    ByteArrayInputStream confStream = new ByteArrayInputStream(pkcs11Config.getBytes());
    Provider prov = new sun.security.pkcs11.SunPKCS11(confStream);
    Security.addProvider(prov);
    KeyStore cc = null;
    String pin = "";
    try {
        cc = KeyStore.getInstance("PKCS11",prov);
        KeyStore.PasswordProtection pp = new KeyStore.PasswordProtection(pin.toCharArray());
        cc.load(null ,  pp.getPassword() );
        Enumeration aliases = cc.aliases();
        while (aliases.hasMoreElements()) {
            Object alias = aliases.nextElement();
            try {
                X509Certificate cert0 = (X509Certificate) cc.getCertificate(alias.toString());
                System.out.println("I am: " + cert0.getSubjectDN().getName());
            } catch (Exception e) {
                continue;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

The KeyStore.load() should be provided with PaswordProtection object with empty pin. This allows me to read the public certificate and extract the data from it.

I have tested this with 3 different types of smart cards and it is working on all of them

1
  • error: package sun.security.pkcs11 is not visible Provider sunPKCS11 = new sun.security.pkcs11.SunPKCS11(); ^ (package sun.security.pkcs11 is declared in module jdk.crypto.cryptoki, which is not in the module graph) I get this error when I try your code :'(
    – AurysVrV
    Dec 8, 2023 at 14:08
0

Well, what i've once done was something like

    Provider prov = new sun.security.pkcs11.SunPKCS11("pkcs.cfg");
    Security.addProvider(prov);
    KeyStore cc = null;
    try {
        cc = KeyStore.getInstance("PKCS11");
        cc.load(null, null);
        cc.getCertificate("CITIZEN AUTHENTICATION CERTIFICATE")
    } catch (Exception ex) {
        ex.printStackTrace();
    }

The pkcs.cfg is a file pointing to the "libpteidpkcs11.so" library, and you should be able to adapt it to your code. Mine reads:

name = SmartCard
library = /usr/local/lib/libpteidpkcs11.so
8
  • Sorry, it did not work: load(null, null) raises javax.security.auth.login.LoginException: no password provided, and no callback handler available for retrieving password Jan 28, 2014 at 9:11
  • try adding a char[] as the password to the load method
    – BlueMoon93
    Jan 28, 2014 at 15:36
  • EDIT: your problem was that you didn't want to request a password, right. I'm not sure then. With the portuguese citizen cards, this works. maybe your cards have different arquitectures or your lib is not appropriate
    – BlueMoon93
    Jan 28, 2014 at 16:02
  • 1
    the card itself allows getting the certificates without password (see the example with opensc pkcs11-tool in the question). I guess the Java JCA wrapping is the one that is causing it, either because I missconfigured it, or because it does not support such behaviour (the doc says it does, though), or something else that I am not understanding. Maybe the "attributes" section? Do you have a sample code of how to initialize it for such portuguesse cards? Jan 28, 2014 at 16:15
  • I did exactly what i have shown you here and it works. Don't know what could be wrong. Maybe someone with more experience can figure it out
    – BlueMoon93
    Jan 28, 2014 at 20:16
0

Finally, there was no solution using JCA. The final solution was to directly attack the PKCS11 driver. I have used jacknji11 (https://github.com/joelhockey/jacknji11) and the PKCS11 spec (http://www.emc.com/emc-plus/rsa-labs/standards-initiatives/pkcs-11-cryptographic-token-interface-standard.htm).

1
  • (Notice I am the original writter of the question). The answer from Plasmen Valisev seems a good approach. I have not marked it as accepted answer because I have not personally tested it, but it seems a very reasonable approach and is much simpler than my solution. Sep 6, 2017 at 15:34
0

Another way is use IAIK PKCS#11 Wrapper. JavaDoc here. Example code below.

/**
 * list certificates
 * 
 * @param module - PKCS#11 (.dll or .so) module path
 * for example: "C:\Program Files (x86)\ENCARD\enigmap11.dll"
 * 
 * @throws Exception
 */
public void listCertificates(String module) throws Exception {
    Module pkcs11Module = Module.getInstance(module);
    pkcs11Module.initialize(null);
    
    Slot[] slotsWithToken = pkcs11Module.getSlotList(Module.SlotRequirement.TOKEN_PRESENT);
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    
    for(Slot s: slotsWithToken) {
        Session session = s.getToken().openSession(Token.SessionType.SERIAL_SESSION, Token.SessionReadWriteBehavior.RO_SESSION, null, null);
        session.findObjectsInit(new X509PublicKeyCertificate());
        Object[] objects = null;
        while((objects = session.findObjects(1)).length > 0) {
            for(Object c: objects) {
                X509PublicKeyCertificate cert = (X509PublicKeyCertificate) c;
                byte[] certValue = cert.getValue().getByteArrayValue();
                Certificate cc = certFactory.generateCertificate(new ByteArrayInputStream(certValue));
                if(cc instanceof X509Certificate) {
                    X509Certificate x509 = (X509Certificate) cc;
                    log.info(x509.getNotBefore() + " - " + x509.getNotAfter());
                }                       
            }
        }
        session.findObjectsFinal();
    }           
    pkcs11Module.finalize(null);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.