I'm having trouble with reading a PEM file of a certificate that I generated and wrote to disk with SpongyCastle.
I'm saving my certificate with the following function
private static void saveCertificate(Context context, X509CertificateHolder certificateHolder) throws Exception {
JcaPEMWriter pemWriter = new JcaPEMWriter(new FileWriter(new File(context.getFilesDir(), "certificate.pem")));
PEMEncryptor encryptor = new JcePEMEncryptorBuilder("DES-EDE3-CBC").setProvider("BC").build("myPass".toCharArray());
pemWriter.writeObject(certificate, encryptor);
pemWriter.close();
}
This seems to be working like it should.
Now when I try to read this file using `PEMParser, an exception gets raised. I'm using the following function to read the file.
private static X509CertificateHolder loadCertificate(Context context) throws Exception {
PEMParser pemParser = new PEMParser(new FileReader(new File(context.getFilesDir(), "certificate.pem")));
Object object = pemParser.readObject(); // -- exception raised here --
JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider("BC");
PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build("myPass".toCharArray());
X509CertificateHolder certificateHolder;
//still need to convert 'object' to my certificate
pemParser.close();
return (X509CertificateHolder) object;
}
Most of the time the reason for the exception is
org.spongycastle.openssl.PEMException: problem parsing cert: org.spongycastle.cert.CertIOException: malformed data: unknown object in getInstance: org.spongycastle.asn1.DERApplicationSpecific
But sometimes I get this
org.spongycastle.openssl.PEMException: problem parsing cert: java.io.IOException: DER length more than 4 bytes: 25
I don't have a clue about what I'm doing wrong. The file output looks OK. It's formatted like this
-----BEGIN CERTIFICATE-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,3C6C...
2mFGwwz...
-----END CERTIFICATE-----
What am I doing wrong?
EDIT
If I read the file into a String using BufferedReader
, this is the output
-----BEGIN CERTIFICATE-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,3C6C...
2mFGwwz...
-----END CERTIFICATE-----
So I suppose the data which is read is correct.