从Java访问Firefox的证书信任库

时间:2012-05-03 16:48:34

标签: java firefox cryptography nss pkcs#11

我几乎失去了对这个的希望。 我正试图通过PKCS#11使用Firefox安装附带的NSS库从Java 7访问Firefox信任库。

以下是代码:

import java.security.KeyStore;
import java.security.Security;
import java.util.Enumeration;
import sun.security.pkcs11.SunPKCS11;

public class Test {

    public static void main(String[] args) throws Exception {
        String configName = "pkcs11.cfg";
        SunPKCS11 p = new SunPKCS11(configName);
        Security.addProvider(p);
        KeyStore ks = KeyStore.getInstance("PKCS11", p);
        ks.load(null,  "apassword".toCharArray());
        System.out.println("Size: " + ks.size());
        Enumeration<String> aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            System.out.println(aliases.nextElement());
        }
    }
}

以下是PKCS#11配置的内容:

name = NSS
nssLibraryDirectory = /usr/lib/firefox/
nssSecmodDirectory = "/home/bogdan/.mozilla/firefox/x5d8wol9.default/"
nssModule =trustanchors
showInfo = true

当我运行应用程序时,我还设置了属性-Djava.library.path=/usr/lib/firefox/

当我运行应用程序时,我得到以下内容:

NSS modules: [NSS Internal PKCS #11 Module (CRYPTO, /usr/lib/firefox/libsoftokn3.so, slot 0), NSS Internal PKCS #11 Module (KEYSTORE, /usr/lib/firefox/libsoftokn3.so, slot 1)]
Exception in thread "main" java.security.ProviderException: NSS module not available: trustanchors
    at sun.security.pkcs11.SunPKCS11.<init>(SunPKCS11.java:271)
    at sun.security.pkcs11.SunPKCS11.<init>(SunPKCS11.java:103)
    at Test.main(Test.java:11)

您实际上可以看到“trustanchors”模块未在初始化步骤中加载,但我不知道为什么。 这里的文档:http://docs.oracle.com/javase/6/docs/technotes/guides/security/p11guide.html#NSS表示

  

trustanchors模块允许访问NSS信任锚   如果已配置secmod.db,则通过PKCS11 KeyStore获取证书   包括信任锚库。

但我不知道这意味着什么。 值得注意的是,我对Windows XP 32位和Ubuntu 11.10 64位都有相同的行为。 看来pkcs11.cfg是正确的,好像我改变了应用程序因其他错误而失败的任何路径。

有什么好主意吗?

1 个答案:

答案 0 :(得分:1)

我最终通过使用JSS4 Mozilla库设法解决了这个问题。如果要使用它,请确保下载JSS4 JAR以及本机库实现及其具有的其他依赖项 - NSPR和NSS本机库。

确保在Linux上本机库的位置在LD_LIBRARY_PATH中,在Windows上,它们的位置在%PATH%变量中。 您可能想要使用Firefox发行版附带的DLL / SO。 这在我发现的Windows上不起作用(与我认为是为WIN95平台编译的事实有关)

其余信息在JSS4库的文档中,但您基本上需要使用org.mozilla.jss.CryptoManager类。

相关问题