我创建了一个密钥库(.jks),我使用以下代码在IDE中访问它
KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream ksfis = new FileInputStream(keyStorePath);
BufferedInputStream ksbufin = new BufferedInputStream(ksfis);
ks.load(ksbufin, spass.toCharArray());
但是当我制作JAR文件时它出错了。在搜索问题之后,我开始知道我必须使用
InputStream is = this.getClass().getClassLoader().getResourceAsStream(FilePath);
但是此代码为我提供了InputStream
,我的代码希望ksfis
为FileInputStream
。有人可以建议我替代期望FileInputStream
的代码。
更新 - MCVE
package com.token;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
public class test {
static final String keyStorePath = "Keys/keystore_pkcs8.jks";
static final String alias = "mykey";
static final String spass = "passwordhere";
static final String kpass = "passwordhere";
private static KeyPair getKeyPairFromKeyStore() throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
//problem with this part of code
Config conf = new Config();
InputStream ksfis = conf.getFileInputStream(keyStorePath);
BufferedInputStream ksbufin = new BufferedInputStream(ksfis);
ks.load(ksbufin, spass.toCharArray());
PrivateKey privateKey = (PrivateKey) ks.getKey(alias, kpass.toCharArray());
java.security.cert.Certificate cert = ks.getCertificate(alias);
PublicKey publicKey = cert.getPublicKey();
return new KeyPair(publicKey, privateKey);
}
public static void main(String[] args) {
try {
KeyPair ks = getKeyPairFromKeyStore();
}
catch(Exception e) {
System.out.println(e.toString());
}
}
}
配置类 -
package com.token;
import java.io.InputStream;
class Config {
public InputStream getFileInputStream(String FilePath) throws Exception{
InputStream is = this.getClass().getClassLoader().getResourceAsStream(FilePath);
return is;
}
}
UPDATE - stackTrace错误
java.io.IOException: Stream closed
java.io.IOException: Stream closed
at java.io.BufferedInputStream.getInIfOpen(BufferedInputStream.java:159)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:284)
at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read(BufferedInputStream.java:265)
at java.security.DigestInputStream.read(DigestInputStream.java:124)
at java.io.DataInputStream.readInt(DataInputStream.java:387)
at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:653)
at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:56)
at sun.security.provider.KeyStoreDelegator.engineLoad(KeyStoreDelegator.java:224)
at sun.security.provider.JavaKeyStore$DualFormatJKS.engineLoad(JavaKeyStore.java:70)
at java.security.KeyStore.load(KeyStore.java:1445)
at com.token.test.getKeyPairFromKeyStore(test.java:25)
at com.token.test.main(test.java:36)