Search code examples
javadecodeencodebouncycastleattributecertificate

X509AttributeCertificateHolder encode and decode


Does someone know how to encode/decode a X509AttributeCertificateHolder?

I tried the following code (att is the created X509AttributeCertificateHolder):

byte[] arr = att.getEncoded();
X509AttributeCertificateHolder holder = new X509AttributeCertificateHolder(arr);

And the problem is: the attributes from holder and att are not the same.

I used the following simple test:

for (int i = 0; i < holder.getAttributes().length; i++) {
    Attribute attr1 = holder.getAttributes()[i];
    Attribute attr2 = att.getAttributes()[i];

    System.out.println("Holder value after decode: " + attr1.getAttrValues());
    System.out.println("Holder value before encode: " + attr2.getAttrValues());
}

And the result of the test is:

Holder value after decode: [[[1][6]#69643a2f2f444155313233343536373839]]

Holder value before encode: [Name: id://DAU123456789 - Auth: N/A]

That's the structure in base64:

MIIBvzCCASgCAQEwZ6BlMGCkXjBcMQswCQYDVQQGEwJBVTEoMCYGA1UECgwfVGhl
IExlZ2lvbiBvZiB0aGUgQm91bmN5IENhc3RsZTEjMCEGA1UECwwaQm91bmN5IFBy
aW1hcnkgQ2VydGlmaWNhdGUCAQKgYjBgpF4wXDELMAkGA1UEBhMCQVUxKDAmBgNV
BAoMH1RoZSBMZWdpb24gb2YgdGhlIEJvdW5jeSBDYXN0bGUxIzAhBgNVBAsMGkJv
dW5jeSBQcmltYXJ5IENlcnRpZmljYXRlMA0GCSqGSIb3DQEBBQUAAgEBMCIYDzIw
MTcwNjIwMTQ1MDIyWhgPMjAxNzA2MjAxNDUyMDJaMCAwHgYDVQRIMRcwFaEThhFp
ZDovL0RBVTEyMzQ1Njc4OTANBgkqhkiG9w0BAQUFAAOBgQBJ3qTRoIugVaP0KSyd
jcMV3crYjuVGapxe6TTJtDqHc8xXreGhoqvSZv/r6hc6D0Fkjc45fZN4iDml3aLy
E7EsGsRFEm+6cLP4/8s8kgkbPk8ZjslxuQz+IScTXHQABv/5gVzjCC+4cTZ/BccM
KtbQwhNz+aIiJM60uVcW+hfC0w==

Solution

  • To check what's going on, I've used your code and did the following:

    Attribute attr1 = holder.getAttributes()[i];
    Attribute attr2 = att.getAttributes()[i];
    
    ASN1Set values1 = attr1.getAttrValues();
    System.out.println(values1.getObjectAt(0).getClass());
    ASN1Set values2 = attr2.getAttrValues();
    System.out.println(values2.getObjectAt(0).getClass());
    

    The output is:

    class org.bouncycastle.asn1.DLSequence
    class org.bouncycastle.asn1.x509.RoleSyntax

    So, before the encoding (in att variable), the attribute value is a RoleSyntax. And if you take a look at its toString() method, it prints the values in the format Name: [value] - Auth: [value].

    But after the encoding (in holder variable), for some reason, BouncyCastle loses this information and the attribute value becomes just a DLSequence.

    To fix this, you need to use this sequence to create a RoleSyntax object:

    Attribute attr1 = holder.getAttributes()[i];
    
    ASN1Set values1 = attr1.getAttrValues();
    
    RoleSyntax rl = RoleSyntax.getInstance(attr1.getAttrValues().getObjectAt(0));
    System.out.println(rl);
    

    The output will be:

    Name: id://DAU123456789 - Auth: N/A