简体   繁体   中英

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

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

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();

Try this one...

Certificate certificate = keyStore.getCertificate(alias);

keyStore.setCertificateEntry(alias, certificate);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM