Search code examples
javajkspkcs#11e-tokenx509securitytokenmanager

Is there a way to extract a certificate from an etoken


Is there a way to extract a certificate from an etoken programmatically using java?

If so, can it be converted to a Java KeyStore(.jks) file?

This is my code

    String alias;
    SunPKCS11 sunpkcs11;
    Key privateKey;


    String cfgFile = "D:\\cfgFile.cfg";

    sunpkcs11 = new SunPKCS11(cfgFile);

    Security.addProvider(sunpkcs11);
    alias = "myAlias";
KeyStore.Builder builderRunning = KeyStore.Builder.newInstance("PKCS11", sunpkcs11,new KeyStore.CallbackHandlerProtection(new CallbackHandler() {
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {

          }}));

KeyStore keyStore = builder.getKeyStore();

        // get my private key

            KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias,
                    new KeyStore.PasswordProtection("password".toCharArray()));
            privateKey = pkEntry.getPrivateKey();

It returns a null pointer Exception. I am new to this and don't know how to proceed further.


Solution

  • Do you need a certificate or a private key? Certificates are extractable, private keys in most cases are not. That's why you get an exception.