How do I import a trusted certificate into an existing keystore programmatically?

爱⌒轻易说出口 提交于 2019-12-08 13:46:34

问题


I need to import a trusted certificate into an already existing keystore, here is my code but its throwing me an EOFException, what could be wrong?

public void importTrustedCertificate( String alias, byte [] trustedCertificate )
        throws Exception
    {
        KeyStore keyStore = KeyStore.getInstance( "JKS" );
        FileInputStream fileInputStream = new FileInputStream( "keystore" + File.separator + "ClientRegistrarKeyStore.jks" );
        FileOutputStream fileOutputStream = new FileOutputStream( "keystore" + File.separator + "ClientRegistrarKeyStore.jks" );

        keyStore.load( fileInputStream, "keystore".toCharArray() );
        keyStore.setCertificateEntry( alias, new X509Certificate( trustedCertificate ) );

        keyStore.store( fileOutputStream, "keystore".toCharArray() );
        fileInputStream.close();
        fileOutputStream.close();

        return;
    }

The Error:

Exception in thread "main" java.io.EOFException
    at java.io.DataInputStream.readInt(DataInputStream.java:375)
    at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:628)
    at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:38)
    at java.security.KeyStore.load(KeyStore.java:1185)
    at com.netrust.passportverification.clientregistrar.setup.IniFileGenerator.importTrustedCertificate(IniFileGenerator.java:107)
    at com.netrust.passportverification.clientregistrar.setup.IniFileGenerator.processZipFile(IniFileGenerator.java:165)
    at com.netrust.passportverification.clientregistrar.setup.IniFileGenerator.main(IniFileGenerator.java:180)

Java Result: 1

回答1:


Are you sure the file at this location is not empty? Can keytool list its contents? This EOFException doesn't look specific to keystores, but it seems that the initial file you're trying to load from is shorter than it should be.

In addition, your FileInputStream and FileOutputStream refer to the same file. I'd suggest closing the one your read from before writing to the other one, to avoid conflicts:

FileInputStream fileInputStream = new FileInputStream( "keystore" + File.separator + "ClientRegistrarKeyStore.jks" );
keyStore.load( fileInputStream, "keystore".toCharArray() );
fileInputStream.close();
keyStore.setCertificateEntry( alias, new X509Certificate( trustedCertificate ) );

FileOutputStream fileOutputStream = new FileOutputStream( "keystore" + File.separator + "ClientRegistrarKeyStore.jks" );
keyStore.store( fileOutputStream, "keystore".toCharArray() );
fileOutputStream.close();



回答2:


Try this one...

Certificate certificate = keyStore.getCertificate(alias);

keyStore.setCertificateEntry(alias, certificate);



来源:https://stackoverflow.com/questions/8415267/how-do-i-import-a-trusted-certificate-into-an-existing-keystore-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!