我使用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