org.bouncycastle.openssl.PEMReader可以读取java.security.PrivateKey吗?

时间:2011-11-24 17:02:40

标签: java cryptography openssl bouncycastle public-key-encryption

我有以下代码:

PrivateKey key = null;
X509Certificate cert = null;
KeyPair keyPair = null;

final Reader reader = new StringReader(pem);
try {
    final PEMReader pemReader = new PEMReader(reader, new PasswordFinder() {
        @Override
        public char[] getPassword() {
            return password == null ? null : password.toCharArray();
        }
    });

    Object obj;
    while ((obj = pemReader.readObject()) != null) {
        if (obj instanceof X509Certificate) {
            cert = (X509Certificate) obj;
        } else if (obj instanceof PrivateKey) {
            key = (PrivateKey) obj;
        } else if (obj instanceof KeyPair) {
            keyPair = (KeyPair) obj;
        }
    }
} finally {
    reader.close();
}

它会读私钥吗?换句话说,任何PEM文件只能包含纯私钥吗?如果是的话,你能给我一个样本PEM文件吗?

先谢谢。

1 个答案:

答案 0 :(得分:6)

文件可以只包含一个私钥,它可以是加密的或明文。 OpenSSL一直这样做。

然而,我查看了PEMReader的代码,看起来它将从RSA私钥返回KeyPair(私钥文件包含相应公钥的所有必要信息) 。它似乎永远不会从PrivateKey返回readObject()

这是来自OpenSSL的未加密的1024 RSA私钥。

-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQC/oBTZGo0cgHHdZD8LgDpUVOPjsI58PrTJPtrlVT7kyznmzFEt
TW9cqxlw6EOo09tTTrjikLDA2M5xzejbLGPb8sa7AzVhuHkChgGh9eZmphsnvq1W
LjuXCk5yWOR9ziaBKKFeNXOsdvDp3eMDM+wz3vzn1wrGrg00jMvKP5kcpwIDAQAB
AoGBAI9oJ/IKEszfu1cqLJxYzE5McXf2q8uDyhxJs9upHjZveNem1KGIr+y0B4gd
6nSwiBUidu7nxb+tAWLd7IQKBnhKC3AtGNT7qTwnXelKsJhaok2+kEEuzjQYnmsP
AreEsAi/FlHj/kAyjGBoQ4QLrx1sp2cDcBTP78PeJfZvm/RxAkEA7zVuumjrz3ui
zmBzQI1pwD9F0REyE5zJfgUz5iDQbK2RRPhcQ9LCZdEJRU0vdWTBmmgadYwpg0uG
hYFwCy7PWwJBAM0Tk+pMRwke0m4oiI4mKh0u4enHXE2RFMUtTMjGILHt8+m4Q7rd
KGfO9/ylK82LhbT0Z/BeszbnneaAefkxFaUCQQDephVSXKZgkOuQvCWKSBXOYxZQ
6nh52M2TBrSv1ospHMTCNYlrd5iJvG+smZM66XVqistV7ggVtQ6Y5Umsnv1RAkBW
l/K4V1cTcdFXNIRcyZ60zewUw9qk4iMME1G94XNCzoBU6zqmN+Zs1wb9xlzVoRln
TGBrLgGsqGaTQyK9500FAkBuKohFvOgFHSKOskiVu/swByWZANEZsoEPUx7V6vXH
Tk+qftY64tt4AazHPVyVtsj1oqOv3zbulfnotFvU1nmp
-----END RSA PRIVATE KEY-----

这是相应的公钥:

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC/oBTZGo0cgHHdZD8LgDpUVOPj
sI58PrTJPtrlVT7kyznmzFEtTW9cqxlw6EOo09tTTrjikLDA2M5xzejbLGPb8sa7
AzVhuHkChgGh9eZmphsnvq1WLjuXCk5yWOR9ziaBKKFeNXOsdvDp3eMDM+wz3vzn
1wrGrg00jMvKP5kcpwIDAQAB
-----END PUBLIC KEY-----

KeyStore用于在Java应用程序中传输公钥,私钥和对称密钥。大多数Java应用程序以PKCS#8编码(不是the same as the OpenSSL format)存储私钥,公钥用SubjectPublicKeyInfo结构表示( 与OpenSSL相同) )。