Example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

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

Introduction

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

Prototype

public ASN1InputStream(byte[] input) 

Source Link

Document

Create an ASN1InputStream based on the input byte array.

Usage

From source file:com.peterphi.std.crypto.keygen.CaHelper.java

License:Open Source License

/**
 * @param gen//ww w .  j a v a2s .c  om
 * @param pubKey
 *
 * @throws IOException
 */
private static void addAuthorityKeyIdentifier(X509V3CertificateGenerator gen, PublicKey pubKey)
        throws Exception {
    {
        ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded()));
        try {
            SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) is.readObject());
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);

            gen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
}

From source file:com.peterphi.std.crypto.keygen.CaHelper.java

License:Open Source License

/**
 * @param gen/*ww w .  jav  a 2 s.c  o m*/
 * @param pubKey
 *
 * @throws IOException
 */
private static void addSubjectKeyIdentifier(X509V3CertificateGenerator gen, PublicKey pubKey) throws Exception {
    {
        ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded()));
        try {
            SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo((ASN1Sequence) is.readObject());
            SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki);
            gen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
}

From source file:com.rcn.service.CertificateService.java

License:Open Source License

private SubjectPublicKeyInfo getSubjectPublicKeyInfo(PublicKey pub) {
    ByteArrayInputStream bIn = new ByteArrayInputStream(pub.getEncoded());
    try {// ww w .  j a  v  a2 s  . c  o m
        return new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(bIn).readObject());
    } catch (IOException e) {
        throw new SecurityException(e);
    }
}

From source file:com.rovemonteux.silvertunnel.netlib.layer.tor.util.Encryption.java

License:Open Source License

/**
 * makes RSA public key from bin byte array.
 *
 * @param b byte array that contains the key
 * @return//from  w  w w  .j a  v a  2s.  c  om
 * @see JCERSAPublicKey
 */
public static RSAPublicKey extractBinaryRSAKey(final byte[] b) {
    RSAPublicKey theKey;

    try {
        final ASN1InputStream ais = new ASN1InputStream(b);
        final Object asnObject = ais.readObject();
        final ASN1Sequence sequence = (ASN1Sequence) asnObject;
        final RSAPublicKeyStructure tempKey = new RSAPublicKeyStructure(sequence);
        theKey = getRSAPublicKey(tempKey.getModulus(), tempKey.getPublicExponent());
        ais.close();
    } catch (final IOException e) {
        LOG.warn("Caught exception:" + e.getMessage());
        theKey = null;
    }

    return theKey;
}

From source file:com.tremolosecurity.proxy.auth.ssl.util.UpnExtractor.java

License:Apache License

private String loadNTPrincipal(X509Certificate[] certs) throws CertificateParsingException, IOException {
    X509Certificate cert = certs[0];
    Collection<List<?>> subjectAlternativeNames = cert.getSubjectAlternativeNames();
    if (subjectAlternativeNames != null && !subjectAlternativeNames.isEmpty()) {
        for (List<?> subjectAltName : subjectAlternativeNames) {
            if (((Integer) subjectAltName.get(0)) == GeneralName.otherName) {
                ASN1InputStream asn1Input = new ASN1InputStream((byte[]) subjectAltName.get(1));
                ASN1Primitive derObject = asn1Input.readObject();
                DLSequence seq = (DLSequence) derObject;
                ASN1ObjectIdentifier id = ASN1ObjectIdentifier.getInstance(seq.getObjectAt(0));
                if (id.getId().equals("1.3.6.1.4.1.311.20.2.3")) {
                    ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(1);
                    DERUTF8String str = null;
                    while (str == null) {
                        if (obj.getObject() instanceof DERTaggedObject) {
                            obj = (ASN1TaggedObject) obj.getObject();
                        } else if (obj.getObject() instanceof DERUTF8String) {
                            str = (DERUTF8String) obj.getObject();
                        } else {
                            asn1Input.close();
                            return null;
                        }/*from  w ww. j  a v a  2 s. c  om*/
                    }
                    asn1Input.close();
                    return str.getString();
                }
            }
        }
    }
    return null;
}

From source file:com.viettel.hqmc.DAO.FilesDAO.java

private static List<String> getAIALocations(X509Certificate cert) throws Exception {

    //Gets the DER-encoded OCTET string for the extension value for Authority information access Points
    byte[] aiaExtensionValue = cert.getExtensionValue(X509Extensions.AuthorityInfoAccess.getId());
    if (aiaExtensionValue == null) {
        throw new Exception("Certificate doesn't have authority " + "information access points");
    }//from w  ww.  j a  va 2 s .  co m
    //might have to pass an ByteArrayInputStream(aiaExtensionValue)
    ASN1InputStream asn1In = new ASN1InputStream(aiaExtensionValue);
    AuthorityInformationAccess authorityInformationAccess;

    try {
        DEROctetString aiaDEROctetString = (DEROctetString) (asn1In.readObject());
        ASN1InputStream asn1InOctets = new ASN1InputStream(aiaDEROctetString.getOctets());
        ASN1Sequence aiaASN1Sequence = (ASN1Sequence) asn1InOctets.readObject();
        authorityInformationAccess = AuthorityInformationAccess.getInstance(aiaASN1Sequence);
    } catch (IOException ex) {
        LogUtil.addLog(ex);//binhnt sonar a160901
        throw new Exception("Cannot read certificate to get OCSP URLs", ex);
    }

    List<String> ocspUrlList = new ArrayList<String>();
    AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions();
    for (AccessDescription accessDescription : accessDescriptions) {

        GeneralName gn = accessDescription.getAccessLocation();
        if (gn.getTagNo() == GeneralName.uniformResourceIdentifier) {
            DERIA5String str = DERIA5String.getInstance(gn.getName());
            String accessLocation = str.getString();
            ocspUrlList.add(accessLocation);
        }
    }
    if (ocspUrlList.isEmpty()) {
        throw new Exception("Cant get OCSP urls from certificate");
    }

    return ocspUrlList;
}

From source file:com.vvote.verifierlibrary.utils.io.ASN1ToJSONConverter.java

License:Open Source License

/**
 * Utility method used for converting asn.1 files to json
 * // w ww  .ja  va 2s .co m
 * @param inputFile
 * @param outputFile
 * @param fileType
 * @return whether the conversion was successful
 * @throws ASN1Exception
 */
public static boolean asn1ToJSON(String inputFile, String outputFile, FileType fileType) throws ASN1Exception {

    logger.debug("Reading in asn.1 file: {}", inputFile);

    JSONArray out = new JSONArray();

    // create the ASN1 input stream
    try (ASN1InputStream ais = new ASN1InputStream(new FileInputStream(inputFile))) {
        ASN1Primitive obj = null;

        // loop over each ASN1 primitive
        while ((obj = ais.readObject()) != null) {
            switch (fileType) {
            // convert plaintexts
            case MIX_OUTPUT:
                convertASN1ECPoints(obj, out);
                break;
            // convert ciphers
            case MIX_INPUT:
                convertASN1Ciphers(obj, out);
                break;
            default:
                return false;
            }
        }

        // write the output JSON to file
        IOUtils.writeJSONToFile(out, outputFile);

    } catch (FileNotFoundException e) {
        logger.error("Cannot find file", e);
        throw new ASN1Exception("Cannot find file", e);
    } catch (IOException e) {
        logger.error("Cannot read file", e);
        throw new ASN1Exception("Cannot read file", e);
    } catch (JSONException e) {
        logger.error("There was a problem during conversion", e);
        throw new ASN1Exception("There was a problem during conversion", e);
    } catch (JSONIOException e) {
        logger.error("Unable to write JSON to file", e);
        throw new ASN1Exception("Unable to write JSON to file", e);
    }

    return true;
}

From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java

License:Open Source License

/**
 * Returns a {@code SubjectKeyIdentifier} for the received {@code Key}.
 *
 * @param key/*from w w  w  . ja  v a2  s .c  o  m*/
 *            the key for generating the identifier
 * @return a {@code SubjectKeyIdentifier} for the received {@code Key}
 * @throws IOException
 *             if any problem occurs while reading the key
 */
private final SubjectKeyIdentifier createSubjectKeyIdentifier(final Key key) throws IOException {
    final ASN1Sequence seq; // Sequence for the key info
    ASN1InputStream stream = null; // Stream for reading the key

    try {
        stream = new ASN1InputStream(new ByteArrayInputStream(key.getEncoded()));
        seq = (ASN1Sequence) stream.readObject();
    } finally {
        IOUtils.closeQuietly(stream);
    }

    return new BcX509ExtensionUtils().createSubjectKeyIdentifier(new SubjectPublicKeyInfo(seq));
}

From source file:com.yacme.ext.oxsit.comp.security.cert.X509Certificate.java

License:Open Source License

@Override
public void setDEREncoded(byte[] _DEREncoded) {
    ////ww w .j a  v  a2s. com
    m_aX509 = null; //remove old certificate
    //remove old data from HashMaps
    /*      m_aExtensions.clear();
          m_aExtensionLocalizedNames.clear();
          m_aExtensionDisplayValues.clear();
          m_aCriticalExtensions.clear();
          m_aNotCriticalExtensions.clear();*/

    ByteArrayInputStream as = new ByteArrayInputStream(_DEREncoded);
    ASN1InputStream aderin = new ASN1InputStream(as);
    DERObject ado;
    try {
        ado = aderin.readObject();
        m_aX509 = new X509CertificateStructure((ASN1Sequence) ado);
    } catch (IOException e) {
        m_aLogger.severe("setDEREncoded", e);
    }
}

From source file:com.yacme.ext.oxsit.cust_it.comp.security.cert.CertificateComplianceCA_IT.java

License:Open Source License

@Override
public CertificateState verifyCertificateCompliance(XFrame _xFrame, Object _xComponent)
        throws IllegalArgumentException, Exception {
    m_xFrame = _xFrame;//from   ww  w . ja v  a  2  s.c  om
    // TODO Auto-generated method stub
    m_xQc = (XOX_X509Certificate) UnoRuntime.queryInterface(XOX_X509Certificate.class, _xComponent);
    if (m_xQc == null)
        throw (new IllegalArgumentException(
                "XOX_CertificateComplianceControlProcedure#verifyCertificateCertificateCompliance wrong argument"));
    m_aCertificateState = CertificateState.OK;
    //convert the certificate to java internal representation
    try {
        m_JavaCert = Helpers.getCertificate(m_xQc);// (java.security.cert.X509Certificate) cf.generateCertificate(bais);
        //check for version, if version is not 3, exits, certificate cannot be used

        m_aCAState = CertificationAuthorityState.TRUSTED;

        if (m_JavaCert.getVersion() != 3) {
            m_xQc.setCertificateElementErrorState(GlobConstant.m_sX509_CERTIFICATE_VERSION,
                    CertificateElementState.INVALID_value);
            setCertificateStateHelper(CertificateState.MALFORMED_CERTIFICATE);
            return m_aCertificateState;
        }
        //check for validity date
        try {
            /*            // test for date information
                        // not yet valid: 
                        // GregorianCalendar aCal = new GregorianCalendar(2008,12,12);
                        // expired:
                        // GregorianCalendar aCal = new GregorianCalendar(2019,12,12);
                        m_JavaCert.checkValidity(aCal.getTime());*/
            m_JavaCert.checkValidity();
            //valid, set no CRL needed
            m_aCertStateConds = CertificateStateConditions.REVOCATION_CONTROL_NOT_NEEDED;
        } catch (CertificateExpiredException e) {
            m_xQc.setCertificateElementErrorState(GlobConstant.m_sX509_CERTIFICATE_NOT_AFTER,
                    CertificateElementState.INVALID_value);
            setCertificateStateHelper(CertificateState.EXPIRED);
            m_aCAState = CertificationAuthorityState.TRUSTED_WITH_WARNING;
            m_xQc.getCertificateDisplayObj().setCertificateElementCommentString(CertificateElementID.NOT_AFTER,
                    "The date is elapsed.");
            //check CRL of this certificate
            //commented due to excessive time out         verifyCertifRevocHelper();
        } catch (CertificateNotYetValidException e) {
            m_xQc.setCertificateElementErrorState(GlobConstant.m_sX509_CERTIFICATE_NOT_BEFORE,
                    CertificateElementState.INVALID_value);
            setCertificateStateHelper(CertificateState.NOT_ACTIVE);
            m_aCAState = CertificationAuthorityState.TRUSTED_WITH_WARNING;
            m_xQc.getCertificateDisplayObj().setCertificateElementCommentString(CertificateElementID.NOT_BEFORE,
                    "The date is not yet arrived.");
        }

        //check the KeyUsage extension
        /*         int tempState = CertificateElementState.OK_value;
                 if(!isKeyUsageNonRepudiationCritical(m_JavaCert)) {
                    tempState =  CertificateElementState.INVALID_value;
                    setCertificateStateHelper(CertificateState.NOT_COMPLIANT);
                 }
                 m_xQc.setCertificateElementErrorState(X509Extensions.KeyUsage.getId(), tempState);*/
    } catch (CertificateException e) {
        m_aLogger.severe(e);
        setCertificateStateHelper(CertificateState.MALFORMED_CERTIFICATE);
        throw (new com.sun.star.uno.Exception(" wrapped exception: "));
    }

    //convert to Bouncy Castle representation      
    ByteArrayInputStream as = new ByteArrayInputStream(m_xQc.getCertificateAttributes().getDEREncoded());
    ASN1InputStream aderin = new ASN1InputStream(as);
    DERObject ado = null;
    try {
        ado = aderin.readObject();
        X509CertificateStructure x509Str = new X509CertificateStructure((ASN1Sequence) ado);
        //check issuer field for conformance
        TBSCertificateStructure xTBSCert = x509Str.getTBSCertificate();

        //check if either one of IssuerUniqueID or SubjectUniqueID is present
        //ETSI 102 280 5.3
        if (!isOKUniqueIds(xTBSCert)) {
            setCertificateStateHelper(CertificateState.CORE_CERTIFICATE_ELEMENT_INVALID);
            return m_aCertificateState;
        }

        if (!isIssuerIdOk(xTBSCert)) {
            m_xQc.setCertificateElementErrorState("IssuerName", CertificateElementState.INVALID_value);
            setCertificateStateHelper(CertificateState.NOT_COMPLIANT);
        }

        /*         //check if qcStatements are present
                 //the function set the error itself
                 if(!hasQcStatements(xTBSCert)) {
                    return m_aCertificateState;
                 }*/

    } catch (java.io.IOException e) {
        m_aLogger.severe(e);
        setCertificateStateHelper(CertificateState.MALFORMED_CERTIFICATE);
        throw (new com.sun.star.uno.Exception(" wrapped exception: "));
    } catch (java.lang.Exception e) {
        m_aLogger.severe(e);
        setCertificateStateHelper(CertificateState.MALFORMED_CERTIFICATE);
        throw (new com.sun.star.uno.Exception(" wrapped exception: "));
    }
    return m_aCertificateState;
}