Java 为什么加载文件时RSA私钥无效?
用ClassLoader.class加载密钥时出错,为什么 单元测试路径=/…../resource/…/key.der 版本部署路径=classLoader.getResourceAESKeyPath aESKeyPath=key.derJava 为什么加载文件时RSA私钥无效?,java,encryption,aes,rsa,classloader,Java,Encryption,Aes,Rsa,Classloader,用ClassLoader.class加载密钥时出错,为什么 单元测试路径=/…../resource/…/key.der 版本部署路径=classLoader.getResourceAESKeyPath aESKeyPath=key.der private void loadKey(final String AESKeyPath, final String privateKeyFileDerPath) { Properties prop = new Properties();
private void loadKey(final String AESKeyPath, final String privateKeyFileDerPath) {
Properties prop = new Properties();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("foo.properties");
prop.load(input);
final String classpath = prop.getProperty("test.foo");
File aESKeyFile = null;
File privateKeyFile = null;
// My version deployed using the if.
if (classpath.equals("local")) {
URL aesKeyPath = classLoader.getResource(AESKeyPath);
if (aesKeyPath != null) {
aESKeyFile = new File(aesKeyPath.toURI());
}
URL privateKeyURL = classLoader.getResource(privateKeyFileDerPath);
if (privateKeyURL != null) {
privateKeyFile = new File(privateKeyURL.toURI());
}
// The tests used the else
} else {
aESKeyFile = new File(AESKeyPath);
privateKeyFile = new File(privateKeyFileDerPath);
}
byte[] encodedKey = new byte[(int) privateKeyFile.length()];
new FileInputStream(privateKeyFile).read(encodedKey);
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey pk = kf.generatePrivate(privateKeySpec); <---- Error
pkCipher.init(Cipher.DECRYPT_MODE, pk);
aesKey = new byte[AES_Key_Size / 8];
CipherInputStream is = new CipherInputStream(new FileInputStream(AESKeyFile), pkCipher);
is.read(aesKey);
aeskeySpec = new SecretKeySpec(aesKey, "AES");
}
我的问题是Maven。Maven给我的钥匙编码。我在pom.xml中为资源添加了一个过滤器,从而解决了我的问题。我改变了我的密码
<resources>
<resource>
<directory>src/main/resources/foo</directory>
<filtering>true</filtering>
<excludes>
<exclude>**/key/*</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources/foo/key</directory>
</resource>
</resources>
openssl genrsa -out private.pem 2048
openssl pkcs8 -topk8 -in private.pem -outform DER -out private.der -nocrypt
openssl rsa -in private.pem -pubout -outform DER -out public.der
<resources>
<resource>
<directory>src/main/resources/foo</directory>
<filtering>true</filtering>
<excludes>
<exclude>**/key/*</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources/foo/key</directory>
</resource>
</resources>
String keyDerPath = getClass().getResource(privateKeyFileDerPath).getFile();
String AESKeyPathResource = getClass().getResource(AESKeyPath).getFile();
aESKeyFile = new File(AESKeyPathResource );
privateKeyFile = new File(keyDerPath );