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:com.yacme.ext.oxsit.cust_it.security.crl.X509CertRL.java

License:Open Source License

/**
 * Returns DERObject extension if the certificate corresponding to given OID<br><br>
 * Restituisce un estensione DERObject dal certificato, corrispoendente
 * all'OID//from ww  w  .j a  v  a 2 s.  com
 *
 * @param cert certificate
 * @param oid String
 * @throws IOException
 * @return l'estensione
 */
private static DERObject getExtensionValue(X509Certificate cert, String oid) throws IOException {
    byte[] bytes = cert.getExtensionValue(oid);
    if (bytes == null) {
        return null;
    }
    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(bytes));
    ASN1OctetString otteti = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(otteti.getOctets()));
    return aIn.readObject();
}

From source file:com.yacme.ext.oxsit.Helpers.java

License:Open Source License

public static String getIssuerName(X509Certificate _Cert) {
    //convert to bouncycaste
    String sRet = "";

    ByteArrayInputStream as;/*from  ww w .  java  2  s  .  co m*/
    try {
        as = new ByteArrayInputStream(_Cert.getEncoded());
        ASN1InputStream aderin = new ASN1InputStream(as);
        DERObject ado;
        ado = aderin.readObject();
        X509CertificateStructure _aX509 = new X509CertificateStructure((ASN1Sequence) ado);
        //extract the name, same as in display         
        X509Name aName = _aX509.getIssuer();
        Vector<DERObjectIdentifier> oidv = aName.getOIDs();
        HashMap<DERObjectIdentifier, String> hm = new HashMap<DERObjectIdentifier, String>(20);
        Vector<?> values = aName.getValues();
        for (int i = 0; i < oidv.size(); i++) {
            hm.put(oidv.elementAt(i), values.elementAt(i).toString());
        }
        //look for givename (=nome di battesimo)
        //see BC source code for details about DefaultLookUp behaviour
        DERObjectIdentifier oix;
        if (sRet.length() == 0) {
            //check for O
            oix = (DERObjectIdentifier) (X509Name.DefaultLookUp.get("o"));
            if (hm.containsKey(oix)) {
                sRet = hm.get(oix).toString();
            }
        }
        if (sRet.length() == 0) {
            //check for CN
            oix = (DERObjectIdentifier) (X509Name.DefaultLookUp.get("cn"));
            if (hm.containsKey(oix)) {
                sRet = hm.get(oix).toString();
            }
        }
        if (sRet.length() == 0) {
            //if still not, check for pseudodym
            oix = (DERObjectIdentifier) (X509Name.DefaultLookUp.get("pseudonym"));
            if (hm.containsKey(oix))
                sRet = hm.get(oix).toString();
        }
        //check for CN
        oix = (DERObjectIdentifier) (X509Name.DefaultLookUp.get("cn"));
        if (hm.containsKey(oix)) {
            sRet = sRet + ((sRet.length() > 0) ? ", " : "") + hm.get(oix).toString();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
    }
    return sRet;
}

From source file:com.yacme.ext.oxsit.Helpers.java

License:Open Source License

/** Returns the DER encoded form of a X509 certificate.
 * @param _aCert the X509Certificate to encode
 * @return a byte array representing the DER encoded form of the certificate
 * @throws CertificateEncodingException/*  w  w w  .  ja va 2  s .c om*/
 * @throws IOException
 */
public static byte[] getDEREncoded(X509Certificate _aCert) throws CertificateEncodingException, IOException {
    ByteArrayInputStream as;
    as = new ByteArrayInputStream(_aCert.getEncoded());
    ASN1InputStream aderin = new ASN1InputStream(as);
    DERObject ado;
    ado = aderin.readObject();
    return ado.getEncoded("DER"); // _aCert.getTBSCertificate();//       aCertificateAttributes.getDEREncoded();//_aDERencoded;// aCert;
}

From source file:com.yacme.ext.oxsit.pkcs11.PKCS11Driver.java

License:Open Source License

/**
 * Finds a certificate matching the one passed as parameter.
 *
 * @param _aCertificate/*from  w  ww .  ja  v a 2s  .  c  o m*/
 * @return the handle of the certificate, or -1 if not found.
 * @throws PKCS11Exception
 * @throws CertificateEncodingException 
 * @throws IOException 
 */
public long findCertificate(X509Certificate _aCertificate)
        throws PKCS11Exception, CertificateEncodingException, IOException {

    long sessionHandle = getSession();
    long certificateHandle = -1L;

    if (sessionHandle < 0 || _aCertificate == null) {
        return -1L;
    }

    m_aLogger.debug("find certificate.");
    ByteArrayInputStream as = new ByteArrayInputStream(_aCertificate.getEncoded());
    ASN1InputStream aderin = new ASN1InputStream(as);
    DERObject ado;
    ado = aderin.readObject();
    X509CertificateStructure m_aX509 = new X509CertificateStructure((ASN1Sequence) ado);

    // now get the certificate with the same ID as the signature key
    int idx = 0;
    CK_ATTRIBUTE[] attributeTemplateList = new CK_ATTRIBUTE[4];

    attributeTemplateList[idx] = new CK_ATTRIBUTE();
    attributeTemplateList[idx].type = PKCS11Constants.CKA_CLASS;
    attributeTemplateList[idx++].pValue = new Long(PKCS11Constants.CKO_CERTIFICATE);

    attributeTemplateList[idx] = new CK_ATTRIBUTE();
    attributeTemplateList[idx].type = PKCS11Constants.CKA_SUBJECT;
    attributeTemplateList[idx++].pValue = m_aX509.getTBSCertificate().getSubject().getDEREncoded();

    attributeTemplateList[idx] = new CK_ATTRIBUTE();
    attributeTemplateList[idx].type = PKCS11Constants.CKA_ISSUER;
    attributeTemplateList[idx++].pValue = m_aX509.getTBSCertificate().getIssuer().getDEREncoded();

    byte[] ar = m_aX509.getTBSCertificate().getSerialNumber().getDEREncoded();
    byte[] sn = new byte[3];

    sn[0] = ar[2];
    sn[1] = ar[3];
    sn[2] = ar[4];

    ar = m_aX509.getTBSCertificate().getSerialNumber().getEncoded();

    ar = m_aX509.getTBSCertificate().getSerialNumber().getEncoded("BER");

    attributeTemplateList[idx] = new CK_ATTRIBUTE();
    attributeTemplateList[idx].type = PKCS11Constants.CKA_SERIAL_NUMBER;
    attributeTemplateList[idx++].pValue = sn;

    /*        attributeTemplateList[idx] = new CK_ATTRIBUTE();
            attributeTemplateList[idx].type = PKCS11Constants.CKA_SUBJECT;
            attributeTemplateList[idx++].pValue =  _aCertificate.getSubjectX500Principal().getEncoded();*/

    /*        attributeTemplateList[idx] = new CK_ATTRIBUTE();
            attributeTemplateList[idx].type = PKCS11Constants.CKA_ISSUER;
            attributeTemplateList[idx++].pValue =  _aCertificate.getIssuerX500Principal().getEncoded();
            
            //now we need to get the serial number of the certificate, we need the DER
            // version
          ByteArrayInputStream as = new ByteArrayInputStream(_aCertificate.getEncoded()); 
          ASN1InputStream aderin = new ASN1InputStream(as);
          DERObject ado;
          ado = aderin.readObject();
          X509CertificateStructure m_aX509 = new X509CertificateStructure((ASN1Sequence) ado);
            
          attributeTemplateList[idx] = new CK_ATTRIBUTE();
            attributeTemplateList[idx].type = PKCS11Constants.CKA_SERIAL_NUMBER;
            attributeTemplateList[idx++].pValue =  m_aX509.getTBSCertificate().toASN1Object().getObjectAT(1);//getSerialNumber().getDERObject().getDEREncoded();// getEncoded(); //getDEREncoded(); no
                    
    */
    pkcs11Module.C_FindObjectsInit(getSession(), attributeTemplateList);

    long[] availableCertificates = pkcs11Module.C_FindObjects(getSession(), 100);
    //maximum of 100 at once
    if (availableCertificates == null || availableCertificates.length == 0) {
        m_aLogger.log("null returned - no certificate found");
    } else {
        m_aLogger.debug("found " + availableCertificates.length + " certificates with matching attributes.");
        for (int i = 0; i < availableCertificates.length; i++) {
            if (i == 0) { // the first we find, we take as our certificate
                certificateHandle = availableCertificates[i];
                if (certificateHandle > 0L) {
                    // now get the certificate with the same ID as the signature key
                    CK_ATTRIBUTE[] attributeTemplateListR = new CK_ATTRIBUTE[3];

                    attributeTemplateListR[0] = new CK_ATTRIBUTE();
                    attributeTemplateListR[0].type = PKCS11Constants.CKA_SERIAL_NUMBER;

                    attributeTemplateListR[1] = new CK_ATTRIBUTE();
                    attributeTemplateListR[1].type = PKCS11Constants.CKA_LABEL;

                    attributeTemplateListR[2] = new CK_ATTRIBUTE();
                    attributeTemplateListR[2].type = PKCS11Constants.CKA_ID;

                    pkcs11Module.C_GetAttributeValue(getSession(), certificateHandle, attributeTemplateListR);
                    byte[] certificateSN = null;
                    if (attributeTemplateListR[0].pValue != null) {
                        certificateSN = (byte[]) attributeTemplateListR[0].pValue;
                        if (certificateSN != null) {
                            m_aLogger.debug("CKA_SERIAL_NUMBER " + Helpers.printHexBytes(certificateSN));
                        }
                    }
                    if (attributeTemplateListR[1].pValue != null) {

                        attributeTemplateListR[1].pValue.toString();
                        String aLabel = new String((char[]) attributeTemplateListR[1].pValue);
                        m_aLogger.debug("CKA_LABEL '" + aLabel + "'");
                    }
                    if (attributeTemplateListR[2].pValue != null) {
                        certificateSN = (byte[]) attributeTemplateListR[2].pValue;
                        if (certificateSN != null) {
                            m_aLogger.debug("CKA_ID " + Helpers.printHexBytes(certificateSN));
                        }
                    }
                }
            }
            m_aLogger.debug("certificate " + i);
        }
    }
    pkcs11Module.C_FindObjectsFinal(getSession());
    //get serial number of this certificate

    return certificateHandle;
}

From source file:com.zimbra.cs.service.authenticator.CertUtil.java

License:Open Source License

String getSubjectAltNameOtherNameUPN() {
    Collection<List<?>> generalNames = null;
    try {//  w ww .ja v  a  2 s.  c  o m
        generalNames = cert.getSubjectAlternativeNames();
    } catch (CertificateParsingException e) {
        ZimbraLog.account.warn(LOG_PREFIX + "unable to get subject alternative names", e);
    }

    if (generalNames == null) {
        return null;
    }

    ASN1InputStream decoder = null;
    try {
        // Check that the certificate includes the SubjectAltName extension
        for (List<?> generalName : generalNames) {
            Integer tag = (Integer) generalName.get(0);
            if (GeneralName.otherName == tag.intValue()) {
                // Value is encoded using ASN.1
                decoder = new ASN1InputStream((byte[]) generalName.toArray()[1]);
                DEREncodable encoded = decoder.readObject();
                DERSequence derSeq = (DERSequence) encoded;

                DERObjectIdentifier typeId = DERObjectIdentifier.getInstance(derSeq.getObjectAt(0));
                String oid = typeId.getId();

                String value = null;
                ASN1TaggedObject otherNameValue = ASN1TaggedObject.getInstance(derSeq.getObjectAt(1));
                if (OID_UPN.equals(oid)) {
                    ASN1TaggedObject upnValue = ASN1TaggedObject.getInstance(otherNameValue.getObject());
                    DERUTF8String str = DERUTF8String.getInstance(upnValue.getObject());
                    value = str.getString();
                    return value;
                }
            }
        }
    } catch (IOException e) {
        ZimbraLog.account.warn(LOG_PREFIX + "unable to process ASN.1 data", e);
    } finally {
        ByteUtil.closeStream(decoder);
    }

    return null;
}

From source file:com.zimbra.cs.service.authenticator.CertUtil.java

License:Open Source License

private String getSubjectAttr(String needAttrName, String needAttrOid) {
    String subjectDN = getSubjectDN();

    try {//from  w  w  w .ja  va2  s.  co  m
        LdapName dn = new LdapName(subjectDN);
        List<Rdn> rdns = dn.getRdns();

        for (Rdn rdn : rdns) {
            String type = rdn.getType();

            boolean isOid = type.contains(".");

            boolean matched = (isOid ? type.equals(needAttrOid) : type.equals(needAttrName));

            if (matched) {
                Object value = rdn.getValue();
                if (value == null) {
                    continue;
                }

                if (isOid) {
                    byte[] bytes = (byte[]) value;
                    ASN1InputStream decoder = null;
                    try {
                        decoder = new ASN1InputStream(bytes);
                        DEREncodable encoded = decoder.readObject();
                        DERIA5String str = DERIA5String.getInstance(encoded);
                        return str.getString();
                    } catch (IOException e) {
                        ZimbraLog.account.warn(LOG_PREFIX + "unable to decode " + type, e);
                    } finally {
                        ByteUtil.closeStream(decoder);
                    }

                } else {
                    return value.toString();
                }
            }
        }
    } catch (InvalidNameException e) {
        ZimbraLog.account.warn(LOG_PREFIX + "Invalid subject dn value" + subjectDN, e);
    }

    return null;
}

From source file:com.zimbra.cs.service.authenticator.CertUtil.java

License:Open Source License

private void printSubjectAlternativeNames(PrintStream outStream) throws Exception {

    final String UPN_DISPLAY = "Principal Name";
    final String RFC822NAME_DISPLAY = "RFC822 Name";
    final String DNSNAME_DISPLAY = "DNS Name";

    outStream.format("X509v3 Subject Alternative Name: \n");

    ASN1InputStream decoder = null;
    try {//from w  w  w.j  ava  2  s  .  c om
        Collection<List<?>> generalNames = cert.getSubjectAlternativeNames();
        // Check that the certificate includes the SubjectAltName extension
        if (generalNames == null) {
            return;
        }

        /*
           OtherName ::= SEQUENCE {
          type-id    OBJECT IDENTIFIER,
          value      [0] EXPLICIT ANY DEFINED BY type-id }
         */

        for (List<?> generalName : generalNames) {
            Integer tag = (Integer) generalName.get(0);
            if (GeneralName.otherName == tag.intValue()) {
                // Value is encoded using ASN.1
                decoder = new ASN1InputStream((byte[]) generalName.toArray()[1]);
                DEREncodable encoded = decoder.readObject();
                DERSequence derSeq = (DERSequence) encoded;

                DERObjectIdentifier typeId = DERObjectIdentifier.getInstance(derSeq.getObjectAt(0));
                String oid = typeId.getId();

                String value = null;
                ASN1TaggedObject otherNameValue = ASN1TaggedObject.getInstance(derSeq.getObjectAt(1));
                if (OID_UPN.equals(oid)) {
                    ASN1TaggedObject upnValue = ASN1TaggedObject.getInstance(otherNameValue.getObject());
                    DERUTF8String str = DERUTF8String.getInstance(upnValue.getObject());
                    value = str.getString();
                }

                outStream.format("    [%d] %s(%s) = %s\n", tag, oid, UPN_DISPLAY, value);
            } else if (GeneralName.rfc822Name == tag.intValue()) {
                String value = (String) generalName.get(1);
                outStream.format("    [%d] %s = %s\n", tag, RFC822NAME_DISPLAY, value);
            } else if (GeneralName.dNSName == tag.intValue()) {
                String value = (String) generalName.get(1);
                outStream.format("    [%d] %s = %s\n", tag, DNSNAME_DISPLAY, value);
            } else {
                outStream.format("    [%d] - not yet supported\n", tag);
            }

        }
    } catch (CertificateParsingException e) {
        e.printStackTrace();
    } finally {
        ByteUtil.closeStream(decoder);
    }
}

From source file:de.fraunhofer.fokus.openeid.ca.SignedData.java

License:Open Source License

public SignedData(DEROctetString object) throws IOException {
    ASN1InputStream signedDataReader = new ASN1InputStream(object.getOctets());
    signedData = signedDataReader.readObject();
    signedDataReader.close();/*from  w ww.  j  a va2  s. c  o  m*/
}

From source file:de.fraunhofer.fokus.openeid.eac.EfFile.java

License:Open Source License

protected void processContent() throws IOException {
    ASN1InputStream asn1InputStream = new ASN1InputStream(content);
    file = asn1InputStream.readObject();
    asn1InputStream.close();//  w ww  .j  av  a 2 s . c  om
}

From source file:de.rub.dez6a3.jpdfsigner.TimeStampToken.java

License:Open Source License

public TimeStampToken(CMSSignedData signedData) throws TSPException, IOException {
    this.tsToken = signedData;

    if (!this.tsToken.getSignedContentTypeOID().equals(PKCSObjectIdentifiers.id_ct_TSTInfo.getId())) {
        throw new TSPValidationException("ContentInfo object not for a time stamp.");
    }/*from ww  w . java  2 s  .  c  om*/

    Collection signers = tsToken.getSignerInfos().getSigners();

    if (signers.size() != 1) {
        throw new IllegalArgumentException("Time-stamp token signed by " + signers.size()
                + " signers, but it must contain just the TSA signature.");
    }

    tsaSignerInfo = (SignerInformation) signers.iterator().next();

    try {
        CMSProcessable content = tsToken.getSignedContent();
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        content.write(bOut);

        ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(bOut.toByteArray()));

        this.tstInfo = new TimeStampTokenInfo(TSTInfo.getInstance(aIn.readObject()));

        Attribute attr = tsaSignerInfo.getSignedAttributes()
                .get(PKCSObjectIdentifiers.id_aa_signingCertificate);

        if (attr == null) {
            throw new TSPValidationException("no signing certificate attribute found, time stamp invalid.");
        }

        SigningCertificate signCert = SigningCertificate.getInstance(attr.getAttrValues().getObjectAt(0));

        this.certID = ESSCertID.getInstance(signCert.getCerts()[0]);
    } catch (CMSException e) {
        throw new TSPException(e.getMessage(), e.getUnderlyingException());
    }
}