如何使用bouncycastle解析ASN1数据

时间:2013-12-04 11:19:51

标签: java bouncycastle

我有asn1格式的字节数组..现在我想解析这些数据以获取所需信息。这是他们为c ++编写的代码..现在我想做同样的事情java.could任何一个帮助。

ASN1 asn1(in);

 int startPos = in.tellg();
 asn1.enterObject(asn1.getTag());
 int endPos = asn1.getCurrentLength() + in.tellg();

 ubytearray acctId, valData;

 while (in.tellg() < endPos) {
     asn1.enterObject(0x30); //0x30 TAG_SEQ

     // read the name
     ubytearray nameData = asn1.getContent(ASN1_TAG_UTF8_STRING);
     ubytearray octstr =  asn1.getContent(ASN1_TAG_OCTET_STRING);

ASN1 asn2(octstr);          asn2.enterObject(的0x30);          ustring urlstr(asn2.getContent(ASN1_TAG_UTF8_STRING));          ustring nameStr(asn2.getContent(ASN1_TAG_UTF8_STRING));          asn2.enterObject(的0x30);          ubytearray certs = asn2.getContent(ASN1_TAG_OCTET_STRING);

     if ((urlstr.length() > 0)  && (nameStr.length() > 0) && (certs.length() > 0)) {
         printf("url %s\n", urlstr.c_str());
         printf("name %s\n", nameStr.c_str());
         printf("certs len:%d\n", certs.length());  

} }

3 个答案:

答案 0 :(得分:12)

您应该能够使用org.bouncycastle.asn1中的类(从ASN1InputStream开始)从InputStream或byte []中读取ASN.1结构。遵循您的示例代码有点困难,但这样的事情可能会帮助您入门:

    byte[] data = null; // obviously need to supply real data here
    ASN1InputStream input = new ASN1InputStream(data);

    ASN1Primitive p;
    while ((p = input.readObject()) != null) {
        ASN1Sequence asn1 = ASN1Sequence.getInstance(p);

        DERUTF8String nameData = DERUTF8String.getInstance(asn1.getObjectAt(0));
        ASN1OctetString octstr = ASN1OctetString.getInstance(asn1.getObjectAt(1));

        ASN1Sequence asn2 = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(octstr.getOctets()));

        // ... and so on
    }

如果您发现数据结构难以理解,org.bouncycastle.asn1.util.ASN1Dump类可能会有所帮助:

    byte[] data = null; // obviously need to supply real data here
    ASN1InputStream input = new ASN1InputStream(data);

    ASN1Primitive p;
    while ((p = input.readObject()) != null) {
        System.out.println(ASN1Dump.dumpAsString(p));
    }

答案 1 :(得分:0)

对于PEM编码的签名,您可以使用

String signaturePem = "-----BEGIN PKCS7-----\n...";
PEMParser parser = new PEMParser(new StringReader(signaturePem));
ContentInfo contentInfo = (ContentInfo) parser.readObject();
CMSSignedData signedData = new CMSSignedData(contentInfo);
...

答案 2 :(得分:-6)

您可以像这样解码byteArray

String base64String = "Here is your byte array data";
byte[] data  = Base64.decode(base64String, Base64.DEFAULT);
String result= new String(data , "UTF-8");