Example usage for org.bouncycastle.asn1 ASN1Sequence getObjectAt

List of usage examples for org.bouncycastle.asn1 ASN1Sequence getObjectAt

Introduction

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

Prototype

public ASN1Encodable getObjectAt(int index) 

Source Link

Document

Return the object at the sequence position indicated by index.

Usage

From source file:at.asitplus.regkassen.common.util.CryptoUtil.java

License:Apache License

/**
 * Helper method to convert DER-encoded signature values (e.g. used by Java)
 * to concatenated signature values//from   www  . j  a  va2 s.c  o m
 * (as used by the JWS-standard)
 *
 * @param derEncodedSignatureValue
 *          DER-encoded signature value
 * @return concatenated signature value (as used by JWS standard)
 * @throws IOException
 */
public static byte[] convertDEREncodedSignatureToJWSConcatenated(final byte[] derEncodedSignatureValue)
        throws IOException {
    final ASN1InputStream asn1InputStream = new ASN1InputStream(derEncodedSignatureValue);
    final ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    asn1InputStream.close();
    final ASN1Sequence asn1Sequence = (ASN1Sequence.getInstance(asn1Primitive));
    final ASN1Integer rASN1 = (ASN1Integer) asn1Sequence.getObjectAt(0);
    final ASN1Integer sASN1 = (ASN1Integer) asn1Sequence.getObjectAt(1);
    final X9IntegerConverter x9IntegerConverter = new X9IntegerConverter();
    final byte[] r = x9IntegerConverter.integerToBytes(rASN1.getValue(), 32);
    final byte[] s = x9IntegerConverter.integerToBytes(sASN1.getValue(), 32);

    final byte[] concatenatedSignatureValue = new byte[64];
    System.arraycopy(r, 0, concatenatedSignatureValue, 0, 32);
    System.arraycopy(s, 0, concatenatedSignatureValue, 32, 32);

    return concatenatedSignatureValue;
}

From source file:at.asitplus.regkassen.core.base.util.CryptoUtil.java

License:Apache License

/**
 * Helper method to convert DER-encoded signature values (e.g. used by Java) to concatenated signature values
 * (as used by the JWS-standard)//from   ww  w  .j  a v  a 2s  .co  m
 *
 * @param derEncodedSignatureValue DER-encoded signature value
 * @return concatenated signature value (as used by JWS standard)
 * @throws IOException
 */
public static byte[] convertDEREncodedSignatureToJWSConcatenated(byte[] derEncodedSignatureValue)
        throws IOException {
    ASN1InputStream asn1InputStream = new ASN1InputStream(derEncodedSignatureValue);
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    ASN1Sequence asn1Sequence = (ASN1Sequence.getInstance(asn1Primitive));
    ASN1Integer rASN1 = (ASN1Integer) asn1Sequence.getObjectAt(0);
    ASN1Integer sASN1 = (ASN1Integer) asn1Sequence.getObjectAt(1);
    X9IntegerConverter x9IntegerConverter = new X9IntegerConverter();
    byte[] r = x9IntegerConverter.integerToBytes(rASN1.getValue(), 32);
    byte[] s = x9IntegerConverter.integerToBytes(sASN1.getValue(), 32);

    byte[] concatenatedSignatureValue = new byte[64];
    System.arraycopy(r, 0, concatenatedSignatureValue, 0, 32);
    System.arraycopy(s, 0, concatenatedSignatureValue, 32, 32);

    return concatenatedSignatureValue;
}

From source file:be.fedict.eid.pkira.crypto.csr.CSRInfo.java

License:Open Source License

public static <T> void getElementsFromASN1Sequence(ASN1Sequence sequence,
        ASN1ObjectIdentifier requiredObjectIdentifier, Class<T> expectedClass, List<T> resultList) {
    for (int j = 0; j < sequence.size(); j++) {
        DEREncodable object = sequence.getObjectAt(j);
        if (object instanceof DERSequence) {
            getElementsFromASN1Sequence((DERSequence) object, requiredObjectIdentifier, expectedClass,
                    resultList);/* w w w  .  j a  va 2 s  . co m*/
        } else {
            ASN1ObjectIdentifier objectIdentifier = (ASN1ObjectIdentifier) object;
            if (objectIdentifier.equals(requiredObjectIdentifier)) {
                resultList.add(expectedClass.cast(sequence.getObjectAt(j + 1)));
            }
            j++;
        }
    }
}

From source file:bluecrystal.bcdeps.helper.DerEncoder.java

License:Open Source License

private static DLSequence getEncodedIssuer(final byte[] enc) {
    try {/*from w w w .ja v  a 2 s.  c  o m*/
        final ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc));
        final ASN1Sequence seq = (ASN1Sequence) in.readObject();
        return (DLSequence) seq.getObjectAt(seq.getObjectAt(0) instanceof DERTaggedObject ? 3 : 2);
    } catch (final IOException e) {
        return null;
    }
}

From source file:ca.trustpoint.m2m.M2mCertificate.java

License:Apache License

/**
 * Converts this instance to its string representation using the given indentation level.
 *
 * @param depth Indentation level./*from w  w w . ja  v a  2s  . c  om*/
 * @return String representation of this instance at the given indentation level.
 */
public String toString(int depth) {
    StringBuffer buffer = new StringBuffer();

    final String LINE_SEPARATOR = System.getProperty("line.separator");

    FormattingUtils.indent(buffer, depth).append("M2MCertificate [APPLICATION 20] SEQUENCE {")
            .append(LINE_SEPARATOR);
    FormattingUtils.indent(buffer, depth + 1).append("[0] tbsCertificate TBSCertificate: ")
            .append(LINE_SEPARATOR);

    FormattingUtils.indent(buffer, depth + 2).append("TBSCertificate SEQUENCE {").append(LINE_SEPARATOR);
    FormattingUtils.indent(buffer, depth + 3).append("[ 0] version INTEGER:               ");
    buffer.append(VERSION).append(LINE_SEPARATOR);

    if (serialNumber != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[ 1] serialNumber OCTET STRING:     ");
        buffer.append(Hex.toHexString(serialNumber)).append(LINE_SEPARATOR);
    }

    if (caKeyDefinition != null) {
        if (caKeyDefinition.getAlgorithm() != null) {
            FormattingUtils.indent(buffer, depth + 3).append("[ 2] cAAlgorithm OBJECT IDENTIFIER: ");
            buffer.append(caKeyDefinition.getAlgorithm().getOid()).append(LINE_SEPARATOR);
        }

        if (caKeyDefinition.getParameters() != null) {
            FormattingUtils.indent(buffer, depth + 3).append("[ 3] cAAlgParams OCTET STRING:      ");
            buffer.append(Hex.toHexString(caKeyDefinition.getParameters())).append(LINE_SEPARATOR);
        }
    }

    if (issuer != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[ 4] issuer Name: ").append(LINE_SEPARATOR);
        buffer.append(issuer.toString(depth + 4));
    }

    if (validFrom != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[ 5] validFrom OCTET STRING: ");
        buffer.append(Hex.toHexString(BigInteger.valueOf(validFrom.getTime() / 1000).toByteArray()))
                .append(LINE_SEPARATOR);
    }

    if (validDuration != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[ 6] validDuration OCTET STRING: ");
        buffer.append(validDuration).append(LINE_SEPARATOR);
    }

    if (subject != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[ 7] subject Name: ").append(LINE_SEPARATOR);
        buffer.append(subject.toString(depth + 4));
    }

    if (publicKeyDefinition != null) {
        if (publicKeyDefinition.getAlgorithm() != null) {
            FormattingUtils.indent(buffer, depth + 3).append("[ 8] pKAlgorithm OBJECT IDENTIFIER: ");
            buffer.append(publicKeyDefinition.getAlgorithm()).append(LINE_SEPARATOR);
        }

        if (publicKeyDefinition.getParameters() != null) {
            FormattingUtils.indent(buffer, depth + 3).append("[ 9] pKAlgParams OCTET STRING: ");
            buffer.append(Hex.toHexString(publicKeyDefinition.getParameters())).append(LINE_SEPARATOR);
        }
    }

    if (publicKey != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[10] pubKey OCTET STRING: ");
        buffer.append(Hex.toHexString(publicKey.getEncoded())).append(LINE_SEPARATOR);
    }

    if (authorityKeyIdentifier != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[11] authKeyId OCTET STRING: ")
                .append(LINE_SEPARATOR);
        buffer.append(authorityKeyIdentifier.toString(depth + 4)).append(LINE_SEPARATOR);
    }

    if (subjectKeyIdentifier != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[12] subjKeyId OCTET STRING: ");
        buffer.append(Hex.toHexString(subjectKeyIdentifier)).append(LINE_SEPARATOR);
    }

    if (keyUsage != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[13] keyUsage OCTET STRING: ");
        buffer.append(keyUsage.toString(depth + 4)).append(LINE_SEPARATOR);
    }

    if (basicConstraints != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[14] basicConstraints INTEGER: ");
        buffer.append(basicConstraints).append(LINE_SEPARATOR);
    }

    if (certificatePolicy != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[15] certificatePolicy OBJECT IDENTIFIER: ");
        buffer.append(certificatePolicy).append(LINE_SEPARATOR);
    }

    if (subjectAlternativeName != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[16] subjectAltName GeneralName: ");
        buffer.append(subjectAlternativeName.toString(depth + 4)).append(LINE_SEPARATOR);
    }

    if (issuerAlternativeName != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[17] issuerAltName GeneralName: ");
        buffer.append(issuerAlternativeName.toString(depth + 4)).append(LINE_SEPARATOR);
    }

    if (extendedKeyUsage != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[18] extendedKeyUsage OBJECT IDENTIFIER: ");
        buffer.append(extendedKeyUsage).append(LINE_SEPARATOR);
    }

    if (authenticationInfoAccessOcsp != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[19] authInfoAccess IA5String: ");
        buffer.append(authenticationInfoAccessOcsp.toString()).append(LINE_SEPARATOR);
    }

    if (crlDistributionPointUri != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[20] cRLDistribPoint IA5String: ");
        buffer.append(crlDistributionPointUri.toString()).append(LINE_SEPARATOR);
    }

    if (!extensions.isEmpty()) {
        FormattingUtils.indent(buffer, depth + 3).append("[21] x509extensions:").append(LINE_SEPARATOR);
        FormattingUtils.indent(buffer, depth + 4).append("X509Extensions SEQUENCE {").append(LINE_SEPARATOR);

        for (int i = 0; i < extensions.size(); i++) {
            Extension e = extensions.get(i);

            FormattingUtils.indent(buffer, depth + 5).append("[").append(i).append("] Extension SEQUENCE {")
                    .append(LINE_SEPARATOR);
            FormattingUtils.indent(buffer, depth + 6).append("extnId OBJECT IDENTIFIER: ");
            buffer.append(e.oid).append(LINE_SEPARATOR);

            FormattingUtils.indent(buffer, depth + 6).append("criticality BOOLEAN: ");
            buffer.append((e.isCritical ? "TRUE" : "FALSE")).append(LINE_SEPARATOR);

            if (e.value != null) {
                FormattingUtils.indent(buffer, depth + 6).append("extnValue OCTET STRING: ");
                buffer.append(Hex.toHexString(e.value)).append(LINE_SEPARATOR);
            }

            FormattingUtils.indent(buffer, depth + 5).append("}").append(LINE_SEPARATOR);
        }

        FormattingUtils.indent(buffer, depth + 4).append("}").append(LINE_SEPARATOR);
    }

    if (caCalcValue != null) {
        ASN1Sequence caCalcValueSequence = null;
        // The caCalcValue is an ASN1Sequence for non-ECQV certificate but not for ECQV
        // certificate, so exception may be encountered
        try {
            caCalcValueSequence = ASN1Sequence.getInstance(caCalcValue);
        } catch (Exception e) {
            // Not an ASN1Sequence
            caCalcValueSequence = null;
        }

        if (caCalcValueSequence != null) {
            FormattingUtils.indent(buffer, depth + 1).append("[1] cACalcValue OCTET STRING representing: ")
                    .append(LINE_SEPARATOR);
            FormattingUtils.indent(buffer, depth + 2).append("SEQUENCE {").append(LINE_SEPARATOR);

            for (int i = 0; i < caCalcValueSequence.size(); i++) {
                try {
                    FormattingUtils.indent(buffer, depth + 3).append("INTEGER: ")
                            .append(Hex.toHexString(
                                    caCalcValueSequence.getObjectAt(i).toASN1Primitive().getEncoded()))
                            .append(LINE_SEPARATOR);
                } catch (IOException ex) {
                    // Do nothing.
                }
            }

            FormattingUtils.indent(buffer, depth + 2).append("}").append(LINE_SEPARATOR);
        } else {
            FormattingUtils.indent(buffer, depth + 1).append("[1] cACalcValue OCTET STRING: ");
            buffer.append(Hex.toHexString(caCalcValue)).append(LINE_SEPARATOR);
        }
    }

    FormattingUtils.indent(buffer, depth).append("}").append(LINE_SEPARATOR);

    return buffer.toString();
}

From source file:ca.trustpoint.m2m.M2mCertificateFactory.java

License:Apache License

/**
 * Generates a certificate object and initializes it with the data read from the
 * {@link java.io.InputStream InputStream} {@code inStream}.
 *
 * <p>/* w w w .  j a  v  a2s .co  m*/
 * The returned certificate object can be casted to the {@link M2mCertificate M2MCertificate}
 * class.
 *
 * <p>
 * The certificate provided in {@code inStream} must be DER-encoded and may be supplied in binary
 * or printable (Base64) encoding. If the certificate is provided in Base64 encoding, it must be
 * bounded at the beginning by -----BEGIN CERTIFICATE-----, and must be bounded at the end by
 * -----END CERTIFICATE-----.
 *
 * <p>
 * Note that if the given input stream does not support {@link java.io.InputStream#mark(int) mark}
 * and {@link java.io.InputStream#reset() reset}, this method will consume the entire input
 * stream. Otherwise, each call to this method consumes one certificate and the read position of
 * the input stream is positioned to the next available byte after the inherent end-of-certificate
 * marker. If the data in the input stream does not contain an inherent end-of-certificate marker
 * (other than EOF) and there is trailing data after the certificate is parsed, a
 * {@link java.security.cert.CertificateException CertificateException} is thrown.
 *
 * @param inStream an input stream with the certificate data.
 *
 * @return a certificate object initialized with the data from the input stream.
 *
 * @exception CertificateException on parsing errors.
 */
@Override
public Certificate engineGenerateCertificate(InputStream inStream) throws CertificateException {
    if (inStream == null) {
        throw new IllegalArgumentException("input stream is null");
    }

    try {
        ASN1InputStream aIn = new ASN1InputStream(inStream);
        ASN1ApplicationSpecific app = ASN1ApplicationSpecific.getInstance(aIn.readObject());

        aIn.close();

        int appTag = app.getApplicationTag();

        if (appTag != M2mCertificate.APPLICATION_TAG_NUMBER) {
            throw new IOException("not M2M certificate application tag: " + appTag);
        }

        ASN1Sequence seq = (ASN1Sequence) app.getObject(BERTags.SEQUENCE);
        if (seq.size() != 2) {
            throw new IOException("sequence wrong size for a M2M certificate");
        }

        // Construct M2M certificate
        M2mCertificate cert = new M2mCertificate();
        for (int i = 0; i < seq.size(); i++) {
            ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(i);
            CertificateFields tag = CertificateFields.getInstance(obj.getTagNo());

            switch (tag) {
            case TBS_CERTIFICATE:
                ASN1Sequence tbsCertificate = ASN1Sequence.getInstance(obj, false);
                parseTbsCertificate(tbsCertificate, cert);
                break;
            case CA_CALC_VALUE:
                ASN1OctetString cACalcValue = ASN1OctetString.getInstance(obj, false);
                cert.setCaCalcValue(cACalcValue.getOctets());
                break;
            default:
                throw new IOException("unknown M2M data field number: " + tag.getTagNumber());
            }
        }

        return cert;
    } catch (Exception e) {
        // Catch all exceptions and convert it to a CertificateException
        throw new CertificateException("exception on parsing certificate data", e);
    }
}

From source file:ca.trustpoint.m2m.M2mCertificateFactory.java

License:Apache License

/**
 * Parses the given ASN.1 sequence and return the corresponding {@link M2mCertificate
 * M2MCertificate} object.//from w  w  w  . ja v  a 2 s .c o  m
 *
 * @param seq ASN.1 sequence containing TBS data.
 * @param cert A M2MCertificate object.
 * @throw InvalidKeyException if public key is invalid.
 * @throw IOException if parsing error.
 * @throw URISyntaxException if URI field is invalid.
 */
private void parseTbsCertificate(ASN1Sequence seq, M2mCertificate cert)
        throws InvalidKeyException, IOException, URISyntaxException {
    if (seq.size() < 2) {
        throw new IOException("no enough data for TBS certificate in sequence");
    }

    // Set tbsCertificate
    for (int i = 0; i < seq.size(); i++) {
        ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(i);
        TbsCertificateFields tag = TbsCertificateFields.getInstance(obj.getTagNo());

        switch (tag) {
        case SERIAL_NUMBER:
            ASN1OctetString serialNumber = ASN1OctetString.getInstance(obj, false);
            cert.setSerialNumber(serialNumber.getOctets());
            break;
        case CA_ALGORITHM:
            ASN1ObjectIdentifier cAAlgorithm = ASN1ObjectIdentifier.getInstance(obj, false);

            if (cert.getCaKeyDefinition() == null) {
                cert.setCaKeyDefinition(new KeyAlgorithmDefinition());
            }

            cert.getCaKeyDefinition().setAlgorithm(parseKeyAlgorithmDefinitionAlgorithm(cAAlgorithm));
            break;
        case CA_ALGORITHM_PARAMETERS:
            ASN1OctetString cAAlgParams = ASN1OctetString.getInstance(obj, false);

            if (cert.getCaKeyDefinition() == null) {
                cert.setCaKeyDefinition(new KeyAlgorithmDefinition());
            }

            cert.getCaKeyDefinition().setParameters(cAAlgParams.getOctets());
            break;
        case ISSUER:
            ASN1Sequence issuerSeq = ASN1Sequence.getInstance(obj, false);
            cert.setIssuer(parseEntityName(issuerSeq));
            break;
        case VALID_FROM:
            ASN1OctetString validFrom = ASN1OctetString.getInstance(obj, false);
            BigInteger dateTimeBInt = new BigInteger(validFrom.getOctets());

            // date in sequence is second, converts to millisecond for constructing Date
            long dateTime = dateTimeBInt.longValue() * 1000;

            cert.setValidFrom(new Date(dateTime));
            break;
        case VALID_DURATION:
            ASN1OctetString validDuration = ASN1OctetString.getInstance(obj, false);
            BigInteger duration = new BigInteger(validDuration.getOctets());

            cert.setValidDuration(new Integer(duration.intValue()));
            break;
        case SUBJECT:
            ASN1Sequence subjectSeq = ASN1Sequence.getInstance(obj, false);
            cert.setSubject(parseEntityName(subjectSeq));
            break;
        case PUBLIC_KEY_ALGORITHM:
            ASN1ObjectIdentifier pKAlgorithm = ASN1ObjectIdentifier.getInstance(obj, false);

            if (cert.getPublicKeyDefinition() == null) {
                cert.setPublicKeyDefinition(new KeyAlgorithmDefinition());
            }

            cert.getPublicKeyDefinition().setAlgorithm(parseKeyAlgorithmDefinitionAlgorithm(pKAlgorithm));
            break;
        case PUBLIC_KEY_ALGORITHM_PARAMETERS:
            ASN1OctetString pKAlgParams = ASN1OctetString.getInstance(obj, false);

            if (cert.getPublicKeyDefinition() == null) {
                cert.setPublicKeyDefinition(new KeyAlgorithmDefinition());
            }

            cert.getPublicKeyDefinition().setParameters(pKAlgParams.getOctets());
            break;
        case PUBLIC_KEY:
            ASN1OctetString pubKey = ASN1OctetString.getInstance(obj, false);
            byte[] rawPublicKey = pubKey.getOctets();

            cert.setIsPublicKeyCompressed(KeyConversionUtils.isCompressedEcPoint(rawPublicKey));

            PublicKey publicKey = KeyConversionUtils.convertRawBytestoEcPublicKey(rawPublicKey);
            cert.setPublicKey(publicKey);
            break;
        case AUTHORITY_KEY_ID:
            ASN1Sequence authKeyIdSeq = ASN1Sequence.getInstance(obj, false);
            cert.setAuthorityKeyIdentifier(parseAuthorityKeyIdentifier(authKeyIdSeq));
            break;
        case SUBJECT_KEY_ID:
            ASN1OctetString subjKeyId = ASN1OctetString.getInstance(obj, false);
            cert.setSubjectKeyIdentifier(subjKeyId.getOctets());
            break;
        case KEY_USAGE:
            ASN1OctetString keyUsageObj = ASN1OctetString.getInstance(obj, false);
            KeyUsage keyUsage = new KeyUsage(keyUsageObj.getEncoded());
            cert.setKeyUsage(keyUsage);
            break;
        case BASIC_CONSTRAINTS:
            ASN1Integer basicConstraints = ASN1Integer.getInstance(obj, false);
            cert.setBasicConstraints(basicConstraints.getValue().intValue());
            break;
        case CERTIFICATE_POLICY:
            ASN1ObjectIdentifier certPolicy = ASN1ObjectIdentifier.getInstance(obj, false);
            cert.setCertificatePolicy(certPolicy.getId());
            break;
        case SUBJECT_ALTERNATE_NAME:
            ASN1TaggedObject subjectAltNameObj = ASN1TaggedObject.getInstance(obj, true);
            cert.setSubjectAlternativeName(parseGeneralName(subjectAltNameObj));
            break;
        case ISSUER_ALTERNATE_NAME:
            ASN1TaggedObject issuerAltNameObj = ASN1TaggedObject.getInstance(obj, true);
            cert.setIssuerAlternativeName(parseGeneralName(issuerAltNameObj));
            break;
        case EXTENDED_KEY_USAGE:
            ASN1ObjectIdentifier extendedKeyUsage = ASN1ObjectIdentifier.getInstance(obj, false);
            cert.setExtendedKeyUsage(extendedKeyUsage.getId());
            break;
        case AUTHENTICATION_INFO_ACCESS_OCSP:
            DERIA5String authInfoAccessOCSPObj = DERIA5String.getInstance(obj, false);
            URI authInfoAccessOCSP = new URI(authInfoAccessOCSPObj.getString());
            cert.setAuthenticationInfoAccessOcsp(authInfoAccessOCSP);
            break;
        case CRL_DISTRIBUTION_POINT_URI:
            DERIA5String cRLDistribPointURIObj = DERIA5String.getInstance(obj, false);
            URI cRLDistribPointURI = new URI(cRLDistribPointURIObj.getString());
            cert.setCrlDistributionPointUri(cRLDistribPointURI);
            break;
        case EXTENSIONS:
            ASN1Sequence x509extensionsSeq = ASN1Sequence.getInstance(obj, false);
            parseX509extensions(x509extensionsSeq, cert);
            break;
        default:
            throw new IOException("unknow TBS certificate field number: " + tag.getTagNumber());
        }
    }
}

From source file:ca.trustpoint.m2m.M2mCertificateFactory.java

License:Apache License

/**
 * Parses ASN.1 sequence to construct an {@link EntityName} object.
 *
 * @param seq ASN.1 sequence data for {@link EntityName}.
 * @return An instance of {@link EntityName} constructed from seq.
 * @throw IOException if parsing has error or not enough data or too much data
 */// www  . j  av a  2s. c  o  m
private EntityName parseEntityName(ASN1Sequence seq) throws IOException {
    if (seq.size() < EntityName.MINIMUM_ATTRIBUTES) {
        throw new IOException("no name attribute in sequence");
    } else if (seq.size() > EntityName.MAXIMUM_ATTRIBUTES) {
        throw new IOException("too many name attributes in sequence:" + seq.size());
    }

    EntityName name = new EntityName();

    for (int i = 0; i < seq.size(); i++) {
        ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(i);
        name.addAttribute(parseEntityNameAttribute(obj));
    }

    return name;
}

From source file:ca.trustpoint.m2m.M2mCertificateFactory.java

License:Apache License

/**
 * Parses ASN.1 sequence to construct an {@link AuthorityKeyIdentifier} object.
 *
 * @param seq An ASN.1 sequence.//from w  ww.j ava 2 s . c o m
 * @return An instance of {@link AuthorityKeyIdentifier} constructed from seq.
 * @throw IOException if parsing error or data invalid.
 */
private AuthorityKeyIdentifier parseAuthorityKeyIdentifier(ASN1Sequence seq) throws IOException {
    if (seq.size() < 1) {
        throw new IOException("no authKeyId data in sequence");
    } else if (seq.size() > 3) {
        throw new IOException("too much authKeyId data in sequence: " + seq.size());
    }

    AuthorityKeyIdentifier authKeyId = new AuthorityKeyIdentifier();

    for (int i = 0; i < seq.size(); i++) {
        ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(i);

        switch (obj.getTagNo()) {
        case AuthorityKeyIdentifier.INDEX_KEY_IDENTIFIER:
            ASN1OctetString identifierObj = ASN1OctetString.getInstance(obj, false);
            authKeyId.setKeyIdentifier(identifierObj.getOctets());
            break;
        case AuthorityKeyIdentifier.INDEX_AUTH_CERT_ISSUER:
            ASN1TaggedObject authCertIssuerObj = ASN1TaggedObject.getInstance(obj, true);
            authKeyId.setCertificateIssuer(parseGeneralName(authCertIssuerObj));
            break;
        case AuthorityKeyIdentifier.INDEX_AUTH_CERT_SERIAL_NUM:
            ASN1OctetString authCertSerialNumObj = ASN1OctetString.getInstance(obj, false);
            BigInteger serialNumber = new BigInteger(authCertSerialNumObj.getOctets());
            authKeyId.setCertificateSerialNumber(serialNumber);
            break;
        default:
            throw new IOException("unknown authKeyId index: " + obj.getTagNo());
        }
    }

    if (!authKeyId.isValid()) {
        throw new IOException("invalid AuthorityKeyIdentifier instance parsed from ASN.1 sequence");
    }

    return authKeyId;
}

From source file:ca.trustpoint.m2m.M2mCertificateFactory.java

License:Apache License

/**
 * Parses ASN.1 sequence to set up X.509 extentions of a {@link M2mCertificate} object.
 *
 * @param seq An ASN.1 sequence containing X.509 extentions.
 * @param cert A {@link M2mCertificate} object to be filled.
 * @throw IOException if parsing error or data invalid.
 *///  w w  w.  j a va2  s. c o m
private void parseX509extensions(ASN1Sequence seq, M2mCertificate cert) throws IOException {
    if (seq.size() < 1) {
        throw new IOException("not X.509 extension data in sequence");
    }

    for (int i = 0; i < seq.size(); i++) {
        ASN1Sequence extSeq = (ASN1Sequence) seq.getObjectAt(i);

        if (extSeq.size() < 2) {
            throw new IOException("no enough data fields for X.509 extension in sequence");
        } else if (extSeq.size() > 3) {
            throw new IOException("too many data fields for X.509 extension in sequence");
        }

        String oid = null;
        boolean isCritical = false;
        byte[] value = null;

        for (int j = 0; j < extSeq.size(); j++) {
            ASN1TaggedObject obj = (ASN1TaggedObject) extSeq.getObjectAt(j);

            switch (obj.getTagNo()) {
            case 0: // oid
                ASN1ObjectIdentifier oidObj = ASN1ObjectIdentifier.getInstance(obj, false);
                oid = oidObj.getId();
                break;
            case 1: // isCritical
                ASN1Boolean isCriticalObj = ASN1Boolean.getInstance(obj, false);
                isCritical = isCriticalObj.isTrue();
                break;
            case 2: // value
                ASN1OctetString valueObj = ASN1OctetString.getInstance(obj, false);
                value = valueObj.getOctets();
                break;
            default:
                throw new IOException("unknown x509extension ID: " + obj.getTagNo());
            }
        }

        cert.addExtension(oid, isCritical, value);
    }
}