Your .key
and .crt
files may be in PEM format. To check this open them with a text editor and check whether the content looks like ------BEGIN CERTIFICATE------
(or "begin RSA private key"...). This is generally the default format used by OpenSSL, unless you've explicitly specified DER.
It's probably not required (see below), but if your certificate is in DER format (a binary format), you can convert them in PEM format using:
openssl x509 -inform DER -in cert.crt -outform PEM -out cert.pem
(Check the help for openssl rsa
for doing something similar with the private key if needed.)
You then get two options:
You can then use it directly from Java as a keystore of type "PKCS12". Most Java applications should allow you to specify a keystore type in addition to the file location. For the default system properties, this is done with javax.net.ssl.keyStoreType
(but the application you're using might not be using this). Otherwise, if you want to load it explicitly, use something like this:
KeyStore ks = KeyStore.getInstance("PKCS12");
FileInputStream fis =
new FileInputStream("/path/to/myhost.p12");
ks.load(fis, "password".toCharArray()); // There are other ways to read the password.
fis.close();
(Then, you should be able to iterate through the aliases()
of the KeyStore
and use getCertificate
(and then getPublicKey()
for the public key) and getKey()
.
Use BouncyCastle's PEMReader
.
FileReader fr = ... // Create a FileReader for myhost.crt
PEMReader pemReader = new PEMReader(fr);
X509Certificate cert = (X509Certificate)pemReader.readObject();
PublicKey pk = cert.getPublicKey();
// Close reader...
For the private key, you'll need to implement a PasswordFinder
(see link from PEMReader doc) for constructing the PEMReader
if the private key is password-protected. (You'll need to cast the result of readObject()
into a Key
or PrivateKey
.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…