我使用OpenSSL生成公共和私人DSA
键和运行以下命令:无法获取读取DSA钥匙从.PEM文件
openssl dsaparam -out dsaparam.pem 1024
openssl gendsa -out dsaprivkey.pem dsaparam.pem
openssl req -new -x509 -key dsaprivkey.pem -out dsacert.pem
,并使用以下两种方法来加载这些键:
public static PrivateKey loadPrivateKey() throws Exception {
String privateKeyPEM = FileUtils.readFileToString(new File("/Keys/dsaprivkey.pem"), StandardCharsets.UTF_8);
// strip of header, footer, newlines, whitespaces
privateKeyPEM = privateKeyPEM
.replace("-----BEGIN DSA PRIVATE KEY-----", "")
.replace("-----END DSA PRIVATE KEY-----", "")
.replaceAll("\\s", "");
// decode to get the binary DER representation
byte[] privateKeyDER = Base64.getDecoder().decode(privateKeyPEM);
KeyFactory keyFactory = KeyFactory.getInstance("DSA");
PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyDER));
return privateKey;
}
public static PublicKey loadPublicKey() throws Exception {
String publicKeyPEM = FileUtils.readFileToString(new File("/Keys/dsacert.pem"), StandardCharsets.UTF_8);
// strip of header, footer, newlines, whitespaces
publicKeyPEM = publicKeyPEM
.replace("-----BEGIN CERTIFICATE-----", "")
.replace("-----END CERTIFICATE-----", "")
.replaceAll("\\s", "");
// decode to get the binary DER representation
byte[] publicKeyDER = Base64.getDecoder().decode(publicKeyPEM);
KeyFactory keyFactory = KeyFactory.getInstance("DSA");
PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyDER));
return publicKey;
}
但是,我无法读取公钥和私钥。
当我尝试读取的公钥,我得到:
java.security.spec.InvalidKeySpecException: Inappropriate key specification: IOException: ObjectIdentifier() -- data isn't an object ID (tag = -96)
当我尝试读取私钥,我得到:
Exception in thread "main" java.security.spec.InvalidKeySpecException: Inappropriate key specification: IOException : algid parse error, not a sequence
如果有人遇到同样的情况,我会真的很感谢关于这个问题的任何帮助
你应该猫的公共或私人的关键之一。我怀疑它是“公钥”和“主题公钥信息”之间的区别,后者具有算法和OID。另请参阅[如何读取.pem文件以获取私钥和公钥](https://stackoverflow.com/q/11787571/608639),[从文件加载RSA公钥](https://stackoverflow.com/q/11410770/608639),[Android上的PEM文件中的PublicKey,Java](https://stackoverflow.com/q/45464949/608639)等。只需将RSA交换为DSA即可。 – jww