如何将一个.der文件的私钥加载到java私钥对象中 [英] how to load the private key from a .der file into java private key object

查看:903
本文介绍了如何将一个.der文件的私钥加载到java私钥对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个Java程序来从文件系统中的文件导入私钥,并使用java创建一个私钥对象...
我可以在中为文件做这件事。但是,使用.der格式,我不知道该怎么做,因为我无法首先检测用于生成密钥的算法。
.pem 文件中我可以从 PKCS#1 的头文件中确定算法,像

-----开始RSA PRIVATE KEY ----

格式并使用bouncycastle pem 读者在PKCS#8中有一个标头

----- BEGIN PRIVATE KEY -----
,但是那些.der格式的不知道:(

也是如果有人对 .key 格式tell如果你的DER文件是PKCS#8格式的话,你可以使用Java KeyFactory 并执行如下操作: p>

  //读取文件到一个字节数组
String privateKeyFileName =C:\\myPrivateKey.der;
Path path = Paths.get(privateKeyFileName);
byte [] privKeyByteArray = Files.readAllBytes(path);

PKCS8EncodedKeyS pec keySpec = new PKCS8EncodedKeySpec(privKeyByteArray);

KeyFactory keyFactory = KeyFactory.getInstance(RSA);

PrivateKey myPrivKey = keyFactory.generatePrivate(keySpec);

System.out.println(Algorithm:+ myPrivKey.getAlgorithm());

您提到您可能不知道密钥使用什么算法。我确信有一个比这更优雅的解决方案,但你可以创建几个 KeyFactory 对象(每个可能的算法一个),并尝试 generatePrivate (),直到你没有得到 InvalidKeySpecException


I'm writing a java program to import private keys from files within the file system and make a private key object, using java... I could do it for files in .pem format but, with .der format, I had no idea what to do, since I couldnt firstly detect the algorithm used to generate the keys. within .pem files I could determine the algorithm from the header for PKCS#1 which have a header like
-----BEGIN RSA PRIVATE KEY----
formats and used the bouncycastle pem reader for those in PKCS#8 which have a header
-----BEGIN PRIVATE KEY----- but with those in .der format no idea :(
also if anyone have an idea about .key format tell me
thanx

解决方案

If your DER files are in PKCS#8 format, you can use the Java KeyFactory and do something like this:

// Read file to a byte array.
String privateKeyFileName = "C:\\myPrivateKey.der";   
Path path = Paths.get(privateKeyFileName);
byte[] privKeyByteArray = Files.readAllBytes(path);

PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privKeyByteArray);

KeyFactory keyFactory = KeyFactory.getInstance("RSA");

PrivateKey myPrivKey = keyFactory.generatePrivate(keySpec);

System.out.println("Algorithm: " + myPrivKey.getAlgorithm());

You mentioned that you may not know what algorithm the key is using. I'm sure there is a more elegant solution than this, but you could create several KeyFactory objects (one for each possible algorithm) and try to generatePrivate() on each one until you do not get an InvalidKeySpecException.

这篇关于如何将一个.der文件的私钥加载到java私钥对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆