Example usage for org.bouncycastle.asn1 ASN1StreamParser ASN1StreamParser

List of usage examples for org.bouncycastle.asn1 ASN1StreamParser ASN1StreamParser

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1StreamParser ASN1StreamParser.

Prototype

public ASN1StreamParser(byte[] encoding) 

Source Link

Usage

From source file:au.com.nullpointer.gp.der.CardData.java

License:Open Source License

public CardData(byte[] encoded) throws DecodingException {
    try {//from   w  w  w  .  jav a 2s  .com
        DERApplicationSpecific cardRecData = (DERApplicationSpecific) ASN1Sequence.fromByteArray(encoded);

        if (cardRecData.getApplicationTag() != TAG_CARD_RECOGNITION_DATA) {
            throw new DecodingException(TAG_CARD_RECOGNITION_DATA, cardRecData.getApplicationTag());
        }

        cardRecData.getDERObject();

        ASN1StreamParser parse = new ASN1StreamParser(cardRecData.getContents());

        DEREncodable der = null;
        while ((der = parse.readObject()) != null) {
            if (der instanceof ASN1ObjectIdentifier) {
                if (!GP_OID.branch("1").equals(der)) {
                    throw new DecodingException("Not GlobalPlatform card recognition data: " + der);
                }
            }

            if (der instanceof DERApplicationSpecific) {
                DERApplicationSpecific as = (DERApplicationSpecific) der;

                int tag = as.getApplicationTag();

                ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) ASN1Object.fromByteArray(as.getContents());

                switch (tag) {
                case 0:
                    gpVersion = oid.getId().replace(GP_OID.branch("2").toString() + ".", "");
                    break;

                case 3:
                    break;
                case 4:
                    String[] vals = oid.getId().replace(GP_OID.branch("4").toString() + ".", "").split("\\.");
                    scpVersion = Integer.parseInt(vals[0]);
                    scpIValue = Integer.parseInt(vals[1]);
                    break;
                case 5:
                    cardConfig = oid.getId();
                    break;
                case 6:
                    chip = oid.getId();
                    break;

                default:
                    throw new DecodingException("Unknow card recognition data tag: " + tag);
                }
            }
        }
    } catch (IOException e) {
        throw new DecodingException("Unable to decode card recognition data", e);
    }
}

From source file:com.vmware.identity.idm.server.clientcert.IdmClientCertificateValidator.java

License:Open Source License

/**
 * Parse DER-encoded bytes to locate a String object
 *
 * @param alterNameValue DER encoded data
 * @return First string found//  w w w . j a  v a2  s.c o  m
 * @throws Throwable
 */
private static String parseDERString(byte[] alterNameValue) throws Throwable {
    try {
        ASN1StreamParser p = new ASN1StreamParser(alterNameValue);
        ASN1Encodable d = p.readObject();
        ASN1Primitive der = d.toASN1Primitive();

        return getStringFromObject(der);
    } catch (Throwable e) {
        // Exception indicates parsing failed, skip this
        // value (most likely not UPN format)
        logger.error("Unable to extract User Principal Name: " + e.getMessage());
        throw e;
    }
}

From source file:de.fraunhofer.fokus.openeid.iso7816_4.DerUtils.java

License:Open Source License

/**
 * read DER structure/*from  w  ww  .j  a  v a  2s . c  o m*/
 * @param dataObject
 * @return DER structure
 * @throws IOException
 */
public static DEREncodable read(byte[] dataObject) throws IOException {
    ASN1StreamParser parser = new ASN1StreamParser(dataObject);
    return parser.readObject();
}

From source file:de.tsenger.animamea.asn1.CVCertificate.java

License:Open Source License

public CVCertificate(byte[] in) throws IllegalArgumentException, IOException {
    ASN1StreamParser asn1Parser = new ASN1StreamParser(in);

    DERApplicationSpecific cvcert = (DERApplicationSpecific) asn1Parser.readObject();
    if (cvcert.getApplicationTag() != 0x21)
        throw new IllegalArgumentException("Can't find a CV Certificate");

    ASN1Sequence derCert = (ASN1Sequence) cvcert.getObject(BERTags.SEQUENCE); // Das CV Cerificate ist eine Sequence

    DERApplicationSpecific body = (DERApplicationSpecific) derCert.getObjectAt(0); //Das erste Objekt des Certificates ist der Cert-Body
    if (body.getApplicationTag() != 0x4E)
        throw new IllegalArgumentException("Can't find a Body in the CV Certificate");

    certBody = new CVCertBody(body);

    DERApplicationSpecific signature = (DERApplicationSpecific) derCert.getObjectAt(1); //Das zweite Objekt des Certificates ist die Signatur
    if (signature.getApplicationTag() != 0x37)
        throw new IllegalArgumentException("Can't find a Signature in the CV Certificate");

    certSignature = new CVCertSignature(signature.getContents());

}

From source file:it.trento.comune.j4sign.examples.CMSServlet.java

License:Open Source License

/**
 * A text message resulting from a dump of provided authenticated attributes
 * data. Shows, among other things, the embedded timestamp attribute.
 * /*  w w  w. j  a v  a2 s.c o  m*/
 * @param bytes
 *            the ASN.1 DER set of authenticated attributes.
 * @return the attributes textual dump.
 */
private String getAuthenticatedAttributesPrintout(byte[] bytes) {
    StringWriter printout = new StringWriter();
    PrintWriter pw = new PrintWriter(printout);
    try {

        ASN1StreamParser a1p = new ASN1StreamParser(bytes);

        System.out.println("ASN1 parser built: " + a1p);

        DERSetParser signedAttributesParser = (DERSetParser) a1p.readObject();

        System.out.println("DERSetParser object read: " + signedAttributesParser);

        ASN1Set set = ASN1Set.getInstance(signedAttributesParser.getDERObject());

        AttributeTable attr = new AttributeTable(set);

        System.out.println("Attribute table created: " + attr);

        Iterator iter = attr.toHashtable().values().iterator();

        pw.println("Listing authenticated attributes:");
        int count = 1;
        while (iter.hasNext()) {
            Attribute a = (Attribute) iter.next();

            pw.println("Attribute " + count + ":");
            if (a.getAttrType().getId().equals(CMSAttributes.signingTime.getId())) {
                Time time = Time.getInstance(a.getAttrValues().getObjectAt(0));
                pw.println("Authenticated time (SERVER local time): " + time.getDate());
            }
            if (a.getAttrType().getId().equals(CMSAttributes.contentType.getId())) {
                if (CMSObjectIdentifiers.data.getId()
                        .equals(DERObjectIdentifier.getInstance(a.getAttrValues().getObjectAt(0)).getId()))
                    pw.println("Content Type: PKCS7_DATA");
            }
            if (a.getAttrType().getId().equals(CMSAttributes.messageDigest.getId())) {
                byte[] md = DEROctetString.getInstance(a.getAttrValues().getObjectAt(0)).getOctets();
                pw.println("Message Digest (SHA-256 hash of data content): " + formatAsString(md, " "));
            }
            if (a.getAttrType().getId().equals(PKCSObjectIdentifiers.id_aa_signingCertificateV2.getId())) {
                pw.println("Signing Certificate V2");
            }

            pw.println("\nAttribute dump follows:");
            pw.println(ASN1Dump.dumpAsString(a) + "\n");

            count++;
        }
    } catch (Exception e) {
        System.out.println(e);
        pw.println(e);
        return null;
    }
    pw.flush();

    return printout.toString();

}

From source file:mitm.common.security.cms.CMSContentTypeClassifier.java

License:Open Source License

/**
 * Returns the CMS content type of the provided byte array
 * //from   w ww .  j  a v  a  2s. co  m
 * See RFC3852 for content types
 * 
 * @param sequenceParser
 * @return
 */
public static CMSContentType getContentType(byte[] data) {
    CMSContentType contentType = CMSContentType.UNKNOWN;

    try {
        ASN1StreamParser streamParser = new ASN1StreamParser(data);

        ASN1SequenceParser sequenceParser = (ASN1SequenceParser) streamParser.readObject();

        contentType = getContentType(sequenceParser);
    } catch (IOException e) {
        logger.error("IOException retrieving CMS content type", e);
    }

    return contentType;
}

From source file:mitm.common.security.cms.CMSContentTypeClassifier.java

License:Open Source License

/**
 * Returns the CMS content type of the provided sequence.
 * //  ww w .  j a  v  a2s  . c  o  m
 * See RFC3852 for content types
 * 
 * @param sequenceParser
 * @return
 */
public static CMSContentType getContentType(InputStream input) {
    CMSContentType contentType = CMSContentType.UNKNOWN;

    try {
        ASN1StreamParser streamParser = new ASN1StreamParser(input);

        Object object = streamParser.readObject();

        if (object instanceof ASN1SequenceParser) {
            ASN1SequenceParser sequenceParser = (ASN1SequenceParser) object;
            contentType = getContentType(sequenceParser);
        } else {
            logger.warn("Object is not a ASN1SequenceParser.");
        }
    } catch (IOException e) {
        logger.error("IOException retrieving CMS content type", e);
    }

    return contentType;
}

From source file:org.dcache.gridsite.BouncyCastleCredentialDelegation.java

License:Open Source License

private static X509Name buildProxyDN(X500Principal principal) throws GeneralSecurityException {
    ASN1StreamParser parser = new ASN1StreamParser(principal.getEncoded());

    DERSequence seq;/*from   w ww .j a v  a 2s. c o  m*/
    try {
        ASN1Encodable object = parser.readObject().getDERObject();
        if (!(object instanceof DERSequence)) {
            throw new IOException("not a DER-encoded ASN.1 sequence");
        }
        seq = (DERSequence) object;
    } catch (IOException e) {
        throw new GeneralSecurityException("failed to parse DN: " + e.getMessage());
    }

    List<ASN1Encodable> rdn = new ArrayList<>(seq.size() + 1);
    for (Enumeration e = seq.getObjects(); e.hasMoreElements();) {
        rdn.add((ASN1Encodable) e.nextElement());
    }

    DERSequence atv = new DERSequence(new ASN1Object[] { X509Name.CN, new DERPrintableString("proxy") });
    rdn.add(new DERSet(atv));

    ASN1Encodable[] rdnArray = rdn.toArray(new ASN1Encodable[rdn.size()]);
    return new X509Name(new DERSequence(rdnArray));
}

From source file:org.deviceconnect.android.ssl.CertificateAuthority.java

License:MIT License

/**
 * ???? Subject Alternative Names (SANs) ??.
 *
 * @param request ???//from   w w w  . j a  v a2 s  . c  om
 * @return SubjectAlternativeNames? {@link GeneralNames} 
 * @throws IOException ?????
 */
private GeneralNames parseSANs(final PKCS10CertificationRequest request) throws IOException {
    List<ASN1Encodable> generalNames = new ArrayList<>();

    CertificationRequestInfo info = request.getCertificationRequestInfo();
    ASN1Set attributes = info.getAttributes();
    for (int i = 0; i < attributes.size(); i++) {
        DEREncodable extensionRequestObj = attributes.getObjectAt(i);
        if (!(extensionRequestObj instanceof DERSequence)) {
            continue;
        }
        DERSequence extensionRequest = (DERSequence) extensionRequestObj;
        if (extensionRequest.size() != 2) {
            continue;
        }
        DEREncodable idObj = extensionRequest.getObjectAt(0);
        DEREncodable contentObj = extensionRequest.getObjectAt(1);
        if (!(idObj instanceof ASN1ObjectIdentifier && contentObj instanceof DERSet)) {
            continue;
        }
        ASN1ObjectIdentifier id = (ASN1ObjectIdentifier) idObj;
        DERSet content = (DERSet) contentObj;
        if (!id.getId().equals("1.2.840.113549.1.9.14")) {
            continue;
        }
        if (content.size() < 1) {
            continue;
        }
        DEREncodable extensionsObj = content.getObjectAt(0);
        if (!(extensionsObj instanceof DERSequence)) {
            continue;
        }
        DERSequence extensions = (DERSequence) extensionsObj;

        for (int k = 0; k < extensions.size(); k++) {
            DEREncodable extensionObj = extensions.getObjectAt(k);
            if (!(extensionObj instanceof DERSequence)) {
                continue;
            }
            DERSequence extension = (DERSequence) extensionObj;
            if (extension.size() != 2) {
                continue;
            }
            DEREncodable extensionIdObj = extension.getObjectAt(0);
            DEREncodable extensionContentObj = extension.getObjectAt(1);
            if (!(extensionIdObj instanceof ASN1ObjectIdentifier)) {
                continue;
            }
            ASN1ObjectIdentifier extensionId = (ASN1ObjectIdentifier) extensionIdObj;
            if (extensionId.getId().equals("2.5.29.17")) {
                DEROctetString san = (DEROctetString) extensionContentObj;

                ASN1StreamParser sanParser = new ASN1StreamParser(san.parser().getOctetStream());
                DEREncodable namesObj = sanParser.readObject().getDERObject();
                if (namesObj instanceof DERSequence) {
                    DERSequence names = (DERSequence) namesObj;
                    for (int m = 0; m < names.size(); m++) {
                        DEREncodable nameObj = names.getObjectAt(m);
                        if (nameObj instanceof DERTaggedObject) {
                            DERTaggedObject name = (DERTaggedObject) nameObj;
                            switch (name.getTagNo()) {
                            case GeneralName.dNSName:
                                generalNames.add(new GeneralName(GeneralName.dNSName,
                                        DERIA5String.getInstance(name, false)));
                                break;
                            case GeneralName.iPAddress:
                                generalNames.add(new GeneralName(GeneralName.iPAddress,
                                        DEROctetString.getInstance(name, true)));
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    if (generalNames.size() > 0) {
        return new GeneralNames(new DERSequence(generalNames.toArray(new ASN1Encodable[generalNames.size()])));
    }
    return null;
}

From source file:org.hyperledger.common.ECKeyPairTest.java

License:Apache License

@Test
public void testMalleableSignature() throws Exception {
    for (int i = 0; i < 1000; i++) {
        PrivateKey key = PrivateKey.createNew(true);

        byte[] signature = key.sign(MESSAGE.getBytes());

        ASN1StreamParser asn1 = new ASN1StreamParser(signature);

        DERSequence seq = (DERSequence) asn1.readObject().toASN1Primitive();
        BigInteger s = ((ASN1Integer) seq.getObjectAt(1)).getPositiveValue();

        assertTrue(key.getPublic().verify(MESSAGE.getBytes(), signature));
        assertTrue(String.format("Signature is not canonical for iteration %d key %s", i, key), isCanonical(s));
    }//from   w  w w  .  ja  v a  2 s. c  om
}