2

Does anybody know how to write an attribute certificate to a file. As well as to read the byte[] and turn that into an attribute certificate?

2 Answers2

0

It is possible to use the encoding of the certificate:

X509V2AttributeCertificate certitificate = new X509V2AttributeCertificate(attributeCertificateHolder.getEncoded());

// Store to file
String fileName = "test.txt";
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(certitificate.getEncoded());
fos.close();

// Read from file
byte[] readCertificate = Files.readAllBytes(new File(fileName).toPath());
X509V2AttributeCertificate decodedCertificate = new X509V2AttributeCertificate(readCertificate);

There exists another option to read the byte array and decode it to a certificate:

X509AttrCertParser parser = new X509AttrCertParser();
parser.engineInit(new FileInputStream(fileName));
X509AttributeCertificate certificate = (X509AttributeCertificate) parser.engineRead();

After all there is a problem with the X509AttributeCertificate because it is deprecated. I have not found any solution for it up to now. Hints for this solution are taken from Bouncycastle: X509CertificateHolder to X509Certificate?.

wake-0
  • 3,918
  • 5
  • 28
  • 45
0

If you are generating the attribute certificate yourself using bouncy-castle, you are most probably using X509AttributeCertificateHolder. In that case you can write the attribute certificate in PEM format using JcaPEMWriter.

// create the attrCertHolder
X509AttributeCertificateHolder attrCertHolder = ...

// write as pem format
JcaPEMWriter pemWriter = new JcaPEMWriter(new FileWriter("<directory-path>/attribute_cert.pem"));
pemWriter.writeObject(attrCertHolder);
pemWriter.flush();

To retrive the certificate from file, use PEMParser:

PEMParser pemParser = new PEMParser(new FileReader("<directory-path>/attribute_cert.pem"));
X509AttributeCertificateHolder attrCertHolderRetrived = (X509AttributeCertificateHolder) pemParser.readObject();

Compare they are equal:

// Compare the encoded byte arrays and not with equals() method
boolean equals = Arrays.equals(attrCertHolder.getEncoded(), attrCertHolderRetrived.getEncoded());
Preconditions.checkArgument(equals, "original and retrived attribute certs do not match");
Chayan Ghosh
  • 718
  • 5
  • 18