Java – load the keystore on OSX lion from the file created using keytool

I have a keystore whose key pairs are generated by the following command:

keytool -genkeypair -v -alias test-agent -keypass test-agent -storepass 123456.ABC -keystore test-agent.keystore -storetype JKS

I fill in the requested certificate information and correctly generate the key pair store

The following commands:

keytool -list -keystore test-agent.keystore -storepass 123456.ABC -storetype JKS

return:

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

test-agent,Jul 13,2012,PrivateKeyEntry,Certificate fingerprint (MD5): 7B:8F:D7:25:FF:34:D0:EF:44:87:46:E5:BF:18:C6:BF

Now I add the keystore file to my build path and try to load it using the following java code running on OSX lion:

public void loadKeyStore() {
  try {
    final Provider p = Security.getProvider("SUN"); 
    final KeyStore keystore = KeyStore.getInstance("JKS",p);

    final InputStream keyStoreInStream = this.getClass().getClassLoader().getResourceAsStream("test-agent.keystore");
    if ( keyStoreInStream == null ) throw new RuntimeException("No keystore found!");

    final char[] password = "123456.ABC".tocharArray();
    try {
      keystore.load(keyStoreInStream,password);
    } catch (Exception e) {
      log.error(String.format("Security library error! [%s]",e.getCause()),e);
    }
  } catch (KeyStoreException e) {
    log.error("Can't initialize security library!",e);
  }
}

Throw the following exception:

java.io.IOException: Invalid keystore format
at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:633)
at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:38)
at java.security.KeyStore.load(KeyStore.java:1185)

I have tried to use pkcs12 (set for keytool and code at the same time. In this case, the provider should be sunjsse), which will cause another exception:

java.io.IOException: DerInputStream.getLength(): lengthTag=111,too big.
at sun.security.util.DerInputStream.getLength(DerInputStream.java:544)
at sun.security.util.DerValue.init(DerValue.java:347)
at sun.security.util.DerValue.<init>(DerValue.java:303)
at com.sun.net.ssl.internal.pkcs12.PKCS12KeyStore.engineLoad(PKCS12KeyStore.java:1200)
at java.security.KeyStore.load(KeyStore.java:1185)

I don't know what the problem is Can anyone give me a hint?

Solution

I found a solution In fact, there is a problem with my project deployment I use maven, whose resource plug-in uses utf8 to encode all files in the resource folder This encoding corrupted the keystore The solution is to add the ignore filter option to the POM file and tell Maven not to encode the keystore file

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>