I'm writing a java code to generate keys and save them in files, I am using BouncyCastle
library to write the privatekey into .pem file using pemwriter(if it is in PKCS#1) and using a regular FileOutputStream to export it into PKCS#8.
Now when exporting into DER, the problem come when trying to export it in PKCS#1.
I searched a lot but cannot find a suitable way to encode the privatekey in PKCS#1 or to convert the regular encoding of java privatekey's (PKCS#8) to PKCS#1, or if you can guide me to convert PrivateKey
to RSAPrivateKey
or DSAPrivateKey
or ECPrivateKey
. Here is a snippet of my code to export
JcePEMEncryptorBuilder builder = new JcePEMEncryptorBuilder("DES-EDE3-CBC");
PEMEncryptor enc = builder.build(password);
FileOutputStream fis = new FileOutputStream(new File(privatekey.der));
if (isPKCS8) {
if (!encrypt) {
fis.write(privateKeyBytes);
} else {
fis.write(enc.encrypt(privateKeyBytes));
}
fis.flush();
fis.close();
where privateKeyBytes are the returned bytes of PrivateKey.getEncoded().
they are in PKCS#8 and if I can convert PrivateKey to RSAPrivateKey or DSAPrivateKey they represent the private key in PKCS#1
format
Apparently you can use type information and perform class casting
PrivateKey privKey = ...;
if (privKey instance of RSAPrivateKey) {
RSAPrivateKey rsaPrivKey = (RSAPrivateKey)privKey;
if (privKey instance of DSAPrivateKey) {
DSAPrivateKey dsaPrivKey = (DSAPrivateKey)privKey;
if (privKey instance of ECPrivateKey) {
ECPrivateKey ecPrivKey = (ECPrivateKey)privKey;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.