Search code examples
javapkcs#11nssiaik-jce

How to initialize provider for pkcs11?


I want to use nss as a provider for pkcs11 and I'm coding in java, on oracle JRE and ubuntu 64bit. I tried 2 different wrappers, iaik and SunPKCS11 but in both I had the same problem. For my provider, I first tried to use libnss3.so and each time I got IOException in instancing module. Then I use libsoftokn3.so and I succeeded instancing a module. But now I face this exception on initializing: "CKR_ARGUMENTS_BAD"

Here is my codes, first using iaik and the second one using SunPKCS11

iaiak:

        Module pkcs11Module = Module.getInstance("libsoftokn.so");
        pkcs11Module.initialize(null);      //Here Throws the Excption:"iaik.pkcs.pkcs11.wrapper.PKCS11Exception: CKR_ARGUMENTS_BAD"
        Info info = pkcs11Module.getInfo();
        System.out.println(info);
        pkcs11Module.finalize(null);

SunPKCS11:

    String configName = "cfg";
    Provider p = new sun.security.pkcs11.SunPKCS11(configName);  //Here Throws the Excption:"sun.security.pkcs11.wrapper.PKCS11Exception: CKR_ARGUMENTS_BAD"
    Security.addProvider(p);

and the file "cfg":

name = nss
library = /usr/lib/libsoftokn3.so

Solution

  • Instead of specifying the library, you can specify the directory like this.

    Properties props = new Properties();
     props.put("name", "nss");
     props.put("nssLibraryDirectory", libDir);
     props.put("nssSecmodDirectory", dbDir);
     props.put("nssModule", "fips");
     props.put("nssDbMode", "readWrite");
    
     ByteArrayOutputStream out = new ByteArrayOutputStream();
     props.store(out, null);
     ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    
     Provider ret = new sun.security.pkcs11.SunPKCS11(in);