Example usage for org.bouncycastle.asn1 ASN1InputStream readObject

List of usage examples for org.bouncycastle.asn1 ASN1InputStream readObject

Introduction

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

Prototype

public ASN1Primitive readObject() throws IOException 

Source Link

Usage

From source file:de.tsenger.animamea.iso7816.DO87.java

License:Open Source License

public void fromByteArray(byte[] encodedData) {
    ASN1InputStream asn1in = new ASN1InputStream(encodedData);
    try {//from  ww  w  .j  av  a 2s  .  c om
        to = (DERTaggedObject) asn1in.readObject();
        asn1in.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    DEROctetString ocs = (DEROctetString) to.getObject();
    value_ = ocs.getOctets();
    data = removePaddingIndicator(value_);

}

From source file:de.tsenger.animamea.iso7816.DO8E.java

License:Open Source License

public void fromByteArray(byte[] encodedData) {
    ASN1InputStream asn1in = new ASN1InputStream(encodedData);
    try {//from  w  w  w .  j a v a  2 s.  c om
        to = (DERTaggedObject) asn1in.readObject();
        asn1in.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    DEROctetString ocs = (DEROctetString) to.getObject();
    data = ocs.getOctets();
}

From source file:de.tsenger.animamea.iso7816.DO97.java

License:Open Source License

public void fromByteArray(byte[] encodedData) {
    ASN1InputStream asn1in = new ASN1InputStream(encodedData);
    try {/* w w  w.j  ava  2s .c  o  m*/
        to = (DERTaggedObject) asn1in.readObject();
        asn1in.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    DEROctetString ocs = (DEROctetString) to.getObject();
    data = ocs.getOctets();

}

From source file:de.tsenger.animamea.iso7816.DO99.java

License:Open Source License

public void fromByteArray(byte[] encodedData) {
    ASN1InputStream asn1in = new ASN1InputStream(encodedData);
    try {/*from   ww  w  .j  a v  a2s. co  m*/
        to = (DERTaggedObject) asn1in.readObject();
        asn1in.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    DEROctetString ocs = (DEROctetString) to.getObject();
    data = ocs.getOctets();

}

From source file:de.tsenger.animamea.iso7816.SecureMessaging.java

License:Open Source License

/**
 *  Erzeugt aus einer SM geschtzten Response-APDU eine plain Response-APDU
 *  ohne Secure Messaging.//ww w  .  ja  va 2  s  .  c o m
 * @param rapdu SM protected RAPDU
 * @return plain RAPDU
 * @throws SecureMessagingException
 */
public ResponseAPDU unwrap(ResponseAPDU rapdu) throws SecureMessagingException {

    DO87 do87 = null;
    DO99 do99 = null;
    DO8E do8E = null;

    incrementAtIndex(ssc, ssc.length - 1);

    int pointer = 0;
    byte[] rapduBytes = rapdu.getData();
    byte[] subArray = new byte[rapduBytes.length];

    while (pointer < rapduBytes.length) {
        System.arraycopy(rapduBytes, pointer, subArray, 0, rapduBytes.length - pointer);
        ASN1InputStream asn1sp = new ASN1InputStream(subArray);
        byte[] encodedBytes = null;
        try {
            encodedBytes = asn1sp.readObject().getEncoded();
            asn1sp.close();
        } catch (IOException e) {
            throw new SecureMessagingException(e);
        }

        ASN1InputStream asn1in = new ASN1InputStream(encodedBytes);
        try {
            switch (encodedBytes[0]) {
            case (byte) 0x87:
                do87 = new DO87();
                do87.fromByteArray(asn1in.readObject().getEncoded());
                break;
            case (byte) 0x99:
                do99 = new DO99();
                do99.fromByteArray(asn1in.readObject().getEncoded());
                break;
            case (byte) 0x8E:
                do8E = new DO8E();
                do8E.fromByteArray(asn1in.readObject().getEncoded());
            }
            asn1in.close();
        } catch (IOException e) {
            throw new SecureMessagingException(e);
        }

        pointer += encodedBytes.length;
    }

    if (do99 == null)
        throw new SecureMessagingException("Secure Messaging error: mandatory DO99 not found"); // DO99 is mandatory
    // and only absent
    // if SM error
    // occurs

    // Construct K (SSC||DO87||DO99)
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    try {
        if (do87 != null)
            bout.write(do87.getEncoded());
        bout.write(do99.getEncoded());
    } catch (IOException e) {
        throw new SecureMessagingException(e);
    }

    crypto.init(ks_mac, ssc);
    byte[] cc = crypto.getMAC(bout.toByteArray());

    byte[] do8eData = do8E.getData();

    if (!java.util.Arrays.equals(cc, do8eData))
        throw new SecureMessagingException("Checksum is incorrect!\n Calculated CC: "
                + HexString.bufferToHex(cc) + "\nCC in DO8E: " + HexString.bufferToHex(do8eData));

    // Decrypt DO87
    byte[] data = null;
    byte[] unwrappedAPDUBytes = null;

    if (do87 != null) {
        crypto.init(ks_enc, ssc);
        byte[] do87Data = do87.getData();
        try {
            data = crypto.decrypt(do87Data);
        } catch (AmCryptoException e) {
            throw new SecureMessagingException(e);
        }
        // Build unwrapped RAPDU
        unwrappedAPDUBytes = new byte[data.length + 2];
        System.arraycopy(data, 0, unwrappedAPDUBytes, 0, data.length);
        byte[] do99Data = do99.getData();
        System.arraycopy(do99Data, 0, unwrappedAPDUBytes, data.length, do99Data.length);
    } else
        unwrappedAPDUBytes = do99.getData().clone();

    return new ResponseAPDU(unwrappedAPDUBytes);
}

From source file:demo.sts.provider.cert.CRLVerifier.java

License:Apache License

/**
 * Extracts all CRL distribution point URLs from the
 * "CRL Distribution Point" extension in a X.509 certificate. If CRL
 * distribution point extension is unavailable, returns an empty list.
 *///from w  w  w . ja  v  a 2  s  . c  o m
public static List<String> getCrlDistributionPoints(X509Certificate cert)
        throws CertificateParsingException, IOException {
    byte[] crldpExt = cert.getExtensionValue(X509Extensions.CRLDistributionPoints.getId());
    if (crldpExt == null) {
        return new ArrayList<String>();
    }
    ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(crldpExt));
    DERObject derObjCrlDP = oAsnInStream.readObject();
    DEROctetString dosCrlDP = (DEROctetString) derObjCrlDP;
    byte[] crldpExtOctets = dosCrlDP.getOctets();
    ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(crldpExtOctets));
    DERObject derObj2 = oAsnInStream2.readObject();
    CRLDistPoint distPoint = CRLDistPoint.getInstance(derObj2);
    List<String> crlUrls = new ArrayList<String>();
    for (DistributionPoint dp : distPoint.getDistributionPoints()) {
        DistributionPointName dpn = dp.getDistributionPoint();
        // Look for URIs in fullName
        if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) {
            GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames();
            // Look for an URI
            for (int j = 0; j < genNames.length; j++) {
                if (genNames[j].getTagNo() == GeneralName.uniformResourceIdentifier) {
                    String url = DERIA5String.getInstance(genNames[j].getName()).getString();
                    crlUrls.add(url);
                }
            }
        }
    }
    return crlUrls;
}

From source file:dk.itst.oiosaml.sp.metadata.CRLChecker.java

License:Mozilla Public License

/**
 * Gets an URL to use when performing an OCSP validation of a certificate.
 * // w ww . ja  v  a  2  s .c  o m
 * @param conf
 * @param entityId
 * @param certificate
 * @return the URL to use.
 * @see <a href="http://oid-info.com/get/1.3.6.1.5.5.7.48.1">http://oid-info.com/get/1.3.6.1.5.5.7.48.1</a>
 */
private String getOCSPUrl(Configuration conf, String entityId, X509Certificate certificate) {
    String url = conf.getString(Constants.PROP_OCSP_RESPONDER);

    if (url != null) {
        return url;
    }

    log.debug("No OCSP configured for " + entityId + " attempting to extract OCSP location from certificate "
            + certificate.getSubjectDN());

    AuthorityInformationAccess authInfoAcc = null;
    ASN1InputStream aIn = null;

    try {
        byte[] bytes = certificate.getExtensionValue(AUTH_INFO_ACCESS);
        aIn = new ASN1InputStream(bytes);
        ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
        aIn = new ASN1InputStream(octs.getOctets());
        ASN1Primitive auth_info_acc = aIn.readObject();

        if (auth_info_acc != null) {
            authInfoAcc = AuthorityInformationAccess.getInstance(auth_info_acc);
        }
    } catch (Exception e) {
        log.debug("Cannot extract access location of OCSP responder.", e);
        return null;
    } finally {
        if (aIn != null) {
            try {
                aIn.close();
            } catch (IOException e) {
            }
        }
    }

    List<String> ocspUrls = getOCSPUrls(authInfoAcc);
    Iterator<String> urlIt = ocspUrls.iterator();

    while (urlIt.hasNext()) {
        // Just return the first URL
        Object ocspUrl = new UntrustedUrlInput(urlIt.next());
        url = ocspUrl.toString();
    }

    return url;
}

From source file:dorkbox.build.util.jar.JarSignatureUtil.java

License:Apache License

/**
 * @return null if there is a problem with the certificate loading process.
 *//*w  ww . j  a v  a 2 s.  c  o m*/
public static final String extractSignatureHashFromSignatureBlock(byte[] signatureBlock) {
    ASN1InputStream sigStream = null;
    try {
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

        InputStream signatureIn = new ByteArrayInputStream(signatureBlock);
        sigStream = new ASN1InputStream(signatureIn);
        ASN1Primitive signatureASN = sigStream.readObject();
        ASN1Sequence seq = ASN1Sequence.getInstance(signatureASN);
        ASN1TaggedObject tagged = (ASN1TaggedObject) seq.getObjectAt(1);

        // Extract certificates
        SignedData newSignedData = SignedData.getInstance(tagged.getObject());

        @SuppressWarnings("rawtypes")
        Enumeration newSigOjects = newSignedData.getCertificates().getObjects();
        Object newSigElement = newSigOjects.nextElement();

        if (newSigElement instanceof DERSequence) {
            DERSequence newSigDERElement = (DERSequence) newSigElement;
            InputStream newSigIn = new ByteArrayInputStream(newSigDERElement.getEncoded());
            Certificate newSigCertificate = certFactory.generateCertificate(newSigIn);

            // certificate bytes
            byte[] newSigCertificateBytes = newSigCertificate.getEncoded();
            String encodeToString = Base64Fast.encodeToString(newSigCertificateBytes, false);
            return encodeToString;
        }
    } catch (IOException e) {
    } catch (CertificateException e) {
    } finally {
        Sys.close(sigStream);
    }
    return null;
}

From source file:dorkbox.build.util.jar.JarSignatureUtil.java

License:Apache License

/**
 * Verify that the two certificates MATCH from within a signature block (ie,
 * XXXXX.DSA in the META-INF directory).
 *
 * @return true if the two certificates are the same. false otherwise.
 *//*  w w w  .j  a v  a 2s. co  m*/
public static final boolean compareCertificates(byte[] newSignatureContainerBytes,
        byte[] oldSignatureContainerBytes) {
    ASN1InputStream newSigStream = null;
    ASN1InputStream oldSigStream = null;
    try {
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

        InputStream newSignatureIn = new ByteArrayInputStream(newSignatureContainerBytes);
        newSigStream = new ASN1InputStream(newSignatureIn);
        ASN1Primitive newSigASNPrim = newSigStream.readObject();
        ContentInfo newSigContent = ContentInfo.getInstance(newSigASNPrim);

        InputStream oldSignatureIn = new ByteArrayInputStream(oldSignatureContainerBytes);
        oldSigStream = new ASN1InputStream(oldSignatureIn);
        ASN1Primitive oldSigASNPrim = oldSigStream.readObject();
        ContentInfo oldSigContent = ContentInfo.getInstance(oldSigASNPrim);

        // Extract certificates
        SignedData newSignedData = SignedData.getInstance(newSigContent.getContent());
        @SuppressWarnings("rawtypes")
        Enumeration newSigOjects = newSignedData.getCertificates().getObjects();

        SignedData oldSignedData = SignedData.getInstance(oldSigContent.getContent());
        @SuppressWarnings("rawtypes")
        Enumeration oldSigOjects = oldSignedData.getCertificates().getObjects();

        Object newSigElement = newSigOjects.nextElement();
        Object oldSigElement = oldSigOjects.nextElement();

        if (newSigElement instanceof DERSequence && oldSigElement instanceof DERSequence) {
            DERSequence newSigDERElement = (DERSequence) newSigElement;
            InputStream newSigIn = new ByteArrayInputStream(newSigDERElement.getEncoded());
            Certificate newSigCertificate = certFactory.generateCertificate(newSigIn);

            DERSequence oldSigDERElement = (DERSequence) oldSigElement;
            InputStream oldSigIn = new ByteArrayInputStream(oldSigDERElement.getEncoded());
            Certificate oldSigCertificate = certFactory.generateCertificate(oldSigIn);

            // certificate bytes
            byte[] newSigCertificateBytes = newSigCertificate.getEncoded();
            byte[] oldSigCertificateBytes = oldSigCertificate.getEncoded();

            return Arrays.equals(newSigCertificateBytes, oldSigCertificateBytes);
        }
    } catch (IOException e) {
    } catch (CertificateException e) {
    } finally {
        Sys.close(newSigStream);
        Sys.close(oldSigStream);
    }

    return false;
}

From source file:ec.gov.informatica.firmadigital.FirmaDigital.java

License:Open Source License

/**
 * <code> crearDatosUsuario </code>
 * /*  w  ww  .  j  av a  2  s.  co m*/
 * @param signingCert
 * @return Esta funcion llena los datos del usuario encontrados en el
 *         certificado
 */
public DatosUsuario crearDatosUsuario(X509Certificate signingCert) {
    // System.out.println("Libreria: Esta en crearDatosUsuario : ");

    // System.out.println(" Antigua Infra probando Datos User CEDULA: " +
    // signingCert.getExtensionValue("1.2.3.4.1"));
    // System.out.println(" Nueva Infra probando Datos User CEDULA: " +
    // (signingCert.getExtensionValue("1.3.6.1.4.1.37947.3.1")));

    /* **************************************************************************************************************
     * No existe la posibilidad de que se realice una firma si el
     * certificado no tiene el campo de cedula, por esta razon el campo
     * cedula ser el validador del tipo de infraestructura que fue creado
     * el certificado
     * ********************************************************
     * ******************************************************
     */
    DatosUsuario datosUsuario = new DatosUsuario();

    if (signingCert.getExtensionValue("1.2.3.4.1") != null) { // esta sobre
        // la
        // antigua
        // infraestructura
        System.out.println("- Certificado generado con OIDS de antigua infraestructura BCE ");
        datosUsuario.setCedula(new String(signingCert.getExtensionValue("1.2.3.4.1")).trim());

        if (signingCert.getExtensionValue("1.2.3.4.2") != null) {
            datosUsuario.setNombre(new String(signingCert.getExtensionValue("1.2.3.4.2")).trim());
        }
        if (signingCert.getExtensionValue("1.2.3.4.3") != null) {
            String txtApellido = new String(signingCert.getExtensionValue("1.2.3.4.3")).trim();
            if (signingCert.getExtensionValue("1.2.3.4.4") != null) {
                txtApellido = txtApellido + " " + new String(signingCert.getExtensionValue("1.2.3.4.4")).trim();
            }
            datosUsuario.setApellido(txtApellido);
        }
        if (signingCert.getExtensionValue("1.2.3.4.6") != null) {
            datosUsuario.setInstitucion(new String(signingCert.getExtensionValue("1.2.3.4.6")).trim());
        }
        if (signingCert.getExtensionValue("1.2.3.4.5") != null) {
            datosUsuario.setCargo(new String(signingCert.getExtensionValue("1.2.3.4.5")).trim());
        }

        if (signingCert.getSerialNumber() != null) {
            datosUsuario.setSerial(signingCert.getSerialNumber().toString());
        }
    } else if (signingCert.getExtensionValue("1.3.6.1.4.1.37947.3.1") != null) { // esta
        // sobre
        // la
        // nueva
        // infraestructura
        System.out.println("- Certificado generado con OIDS de nueva infraestructura BCE");
        datosUsuario.setCedula(new String(signingCert.getExtensionValue("1.3.6.1.4.1.37947.3.1")).trim());

        if (signingCert.getExtensionValue("1.3.6.1.4.1.37947.3.2") != null) {
            datosUsuario.setNombre(new String(signingCert.getExtensionValue("1.3.6.1.4.1.37947.3.2")).trim());
        }
        if (signingCert.getExtensionValue("1.3.6.1.4.1.37947.3.3") != null) {
            String txtApellido = new String(signingCert.getExtensionValue("1.3.6.1.4.1.37947.3.3")).trim();
            if (signingCert.getExtensionValue("1.3.6.1.4.1.37947.3.4") != null) {
                txtApellido = txtApellido + " "
                        + new String(signingCert.getExtensionValue("1.3.6.1.4.1.37947.3.4")).trim();
            }
            datosUsuario.setApellido(txtApellido);
        }
        if (signingCert.getExtensionValue("1.3.6.1.4.1.37947.3.6") != null) {
            datosUsuario
                    .setInstitucion(new String(signingCert.getExtensionValue("1.3.6.1.4.1.37947.3.6")).trim());
        }
        if (signingCert.getExtensionValue("1.3.6.1.4.1.37947.3.5") != null) {
            datosUsuario.setCargo(new String(signingCert.getExtensionValue("1.3.6.1.4.1.37947.3.5")).trim());
        }

        if (signingCert.getSerialNumber() != null) {
            datosUsuario.setSerial(signingCert.getSerialNumber().toString());
        }
    } else {
        System.out.println("- Certificado generado con OIDS de infraestructura securityData");
        datosUsuario.setCedula(new String(signingCert.getExtensionValue("1.3.6.1.4.1.37746.3.1")).trim());

        if (signingCert.getExtensionValue("1.3.6.1.4.1.37746.3.2") != null) {
            datosUsuario.setNombre(new String(signingCert.getExtensionValue("1.3.6.1.4.1.37746.3.2")).trim());
        }
        if (signingCert.getExtensionValue("1.3.6.1.4.1.37746.3.3") != null) {
            String txtApellido = new String(signingCert.getExtensionValue("1.3.6.1.4.1.37746.3.3")).trim();
            if (signingCert.getExtensionValue("1.3.6.1.4.1.37746.3.4") != null) {
                txtApellido = txtApellido + " "
                        + new String(signingCert.getExtensionValue("1.3.6.1.4.1.37746.3.4")).trim();
            }
            datosUsuario.setApellido(txtApellido);
        }
        if (signingCert.getExtensionValue("1.3.6.1.4.1.37746.3.6") != null) {
            datosUsuario
                    .setInstitucion(new String(signingCert.getExtensionValue("1.3.6.1.4.1.37746.3.6")).trim());
        }
        if (signingCert.getExtensionValue("1.3.6.1.4.1.37746.3.5") != null) {
            datosUsuario.setCargo(new String(signingCert.getExtensionValue("1.3.6.1.4.1.37746.3.5")).trim());
        }

        if (signingCert.getSerialNumber() != null) {
            datosUsuario.setSerial(signingCert.getSerialNumber().toString());
        }

    }

    if (signingCert.getExtensionValue("2.5.29.31") != null) {

        // Nuevo codigo validacion CRL
        byte[] val1 = signingCert.getExtensionValue("2.5.29.31");
        if (val1 == null) // esta parte se puede omitir o se lo puede dejar
                          // si se quiere tener un mayor control
        {
            if (signingCert.getSubjectDN().getName().equals(signingCert.getIssuerDN().getName())) {
                System.out.println(
                        "El certificado es un certificado raiz: " + signingCert.getSubjectDN().getName());
            } else {
                System.out.println("El certificado NO tiene punto de distribucin de CRL : "
                        + signingCert.getSubjectDN().getName());
            }
            // return Collections.emptyList();
        } else {
            // Obtiene dentro del certificado del token la lista de
            // distribucin CRL usada para consultar el LDAP del BCE.
            try {
                ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(val1));
                DERObject derObj = oAsnInStream.readObject();
                DEROctetString dos = (DEROctetString) derObj;
                byte[] val2 = dos.getOctets();
                ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(val2));
                DERObject derObj2 = oAsnInStream2.readObject();
                List<String> urls = getDERValue(derObj2);

                for (int j = 0; j < urls.size(); j++) {
                    datosUsuario.setCrl(urls.get(7));
                }
                // datosUsuario.setCrl( new String( distrPoint.substring(
                // distrPoint.indexOf("U")+8,
                // distrPoint.indexOf("ldap") - 8 ) ).trim() );
                // //distrPoint.substring( distrPoint.indexOf("U")+8,
                // distrPoint.indexOf("U") + 12 )
                System.out.println("- Informacion contenida en el Certificado : > " + urls + "\n");// .println(urls);
            } catch (Exception e) {
                System.out.println("Error: " + e.getMessage());
                e.printStackTrace();
            }
        } // fin else
          // Fin validacion CRL

        // System.out.println("Dist_point:" + distrPoint );
        // OJO : Esta validacion puede fallar si la lista de distribucion
        // crece a dos digitos . REVISAR
        // datosUsuario.setCrl( new String( distrPoint.substring(
        // distrPoint.indexOf("U")+8, distrPoint.indexOf("U")
        // + 12 ) ).trim() );
    }
    return datosUsuario;
}