Example usage for org.bouncycastle.asn1.x509 X509CertificateStructure X509CertificateStructure

List of usage examples for org.bouncycastle.asn1.x509 X509CertificateStructure X509CertificateStructure

Introduction

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

Prototype

public X509CertificateStructure(ASN1Sequence seq) 

Source Link

Usage

From source file:ch.bfh.unicert.certimport.CertificateIssuer.java

License:GNU General Public License

public Certificate createClientCertificate(IdentityData id, String keyStorePath, PublicKey pk, int validity,
        String applicationIdentifier, String[] roles, String uniBoardWsdlURL, String uniBoardServiceURL,
        String section) throws CertificateCreationException {

    X509Certificate caCert;//from   w w w . j av  a2s . c  om
    RSAPrivateCrtKey privKey;
    try {
        caCert = this.readIssuerCertificate(this.issuerId);
        privKey = this.readPrivateKey(this.issuerId, this.privKeyPass);
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) {
        logger.log(Level.SEVERE, null, ex);
        throw new CertificateCreationException("230 Could not create client certificate. Key error");
    }

    RSAPrivateCrtKeyParameters cipherParams = this.createIssuerCipherParams(privKey);

    X509Certificate clientCert;

    Hashtable extension = new Hashtable();

    extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier)));

    String completeRole = "";
    for (String role : roles) {
        completeRole += role + ", ";
    }
    completeRole = completeRole.substring(0, completeRole.length() - 2);
    extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole)));

    extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider())));

    Map<String, String> extensionMap = new HashMap();
    if (id.getOtherValues() != null) {
        for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) {
            extension.put(new DERObjectIdentifier(entry.getKey().getOID()),
                    new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue())));
            extensionMap.put(entry.getKey().getName(), entry.getValue());
        }
    }

    try {

        String x509NameString = "";
        x509NameString += "CN=" + id.getCommonName();

        if (id.getSurname() != null && !id.getSurname().equals("")) {
            x509NameString += ", SURNAME=" + id.getSurname();
        }
        if (id.getGivenName() != null && !id.getGivenName().equals("")) {
            x509NameString += ", GIVENNAME=" + id.getGivenName();
        }
        if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) {
            x509NameString += ", UID=" + id.getUniqueIdentifier();
        }
        if (id.getOrganisation() != null && !id.getOrganisation().equals("")) {
            x509NameString += ", O=" + id.getOrganisation();
        }
        if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) {
            x509NameString += ", OU=" + id.getOrganisationUnit();
        }
        if (id.getCountryName() != null && !id.getCountryName().equals("")) {
            x509NameString += ", C=" + id.getCountryName();
        }
        if (id.getState() != null && !id.getState().equals("")) {
            x509NameString += ", ST=" + id.getState();
        }
        if (id.getLocality() != null && !id.getLocality().equals("")) {
            x509NameString += ", L=" + id.getLocality();
        }

        X509Name x509Name = new X509Name(x509NameString);

        V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
        certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis())));
        certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert));
        certGen.setSubject(x509Name);
        certGen.setExtensions(new X509Extensions(extension));
        DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5");
        AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull());
        certGen.setSignature(sigAlgId);
        certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject()));
        certGen.setStartDate(new Time(new Date(System.currentTimeMillis())));
        certGen.setEndDate(new Time(getExpiryDate(validity).getTime()));
        TBSCertificateStructure tbsCert = certGen.generateTBSCertificate();

        //Sign certificate
        SHA1Digest digester = new SHA1Digest();
        AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(tbsCert);
        byte[] signature;
        byte[] certBlock = bOut.toByteArray();
        // first create digest
        digester.update(certBlock, 0, certBlock.length);
        byte[] hash = new byte[digester.getDigestSize()];
        digester.doFinal(hash, 0);
        // then sign it
        rsa.init(true, cipherParams);
        DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash);
        byte[] digest = dInfo.getEncoded(ASN1Encodable.DER);
        signature = rsa.processBlock(digest, 0, digest.length);

        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(tbsCert);
        v.add(sigAlgId);
        v.add(new DERBitString(signature));

        // Create CRT data structure
        clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v)));
        clientCert.verify(caCert.getPublicKey());
    } catch (IOException | InvalidCipherTextException | CertificateException | NoSuchAlgorithmException
            | InvalidKeyException | NoSuchProviderException | SignatureException e) {
        logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() });
        throw new CertificateCreationException("230 Could not create client certificate");
    }

    Certificate cert = new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(),
            id.getOrganisation(), id.getOrganisationUnit(), id.getCountryName(), id.getState(),
            id.getLocality(), id.getSurname(), id.getGivenName(), applicationIdentifier, roles,
            id.getIdentityProvider(), extensionMap);

    //post message on UniBoard if corresponding JNDI parameter is defined
    postOnUniBoard(cert, uniBoardWsdlURL, uniBoardServiceURL, section, (RSAPublicKey) caCert.getPublicKey(),
            privKey);

    return cert;

}

From source file:ch.bfh.unicert.issuer.CertificateIssuerBean.java

License:GNU General Public License

/**
 * Actually creates the requestor certificate.
 *
 * @param id requestor identity data//www.  j  a  va 2 s.c o m
 * @param caCert certificate of the certification authority
 * @param cipherParams issuer private key parameters used for signing
 * @param pk public key of the requestor to certify
 * @param expiry the expiry date
 * @param applicationIdentifier the application identifier for which te certificate is issued
 * @param role role for which the certificate is issued
 * @return the certificate object containing the X509 certificate
 * @throws CertificateCreationException if an error occurs
 */
private Certificate createClientCertificate(IdentityData id, X509Certificate caCert,
        CipherParameters cipherParams, PublicKey pk, Calendar expiry, String applicationIdentifier,
        String[] roles) throws CertificateCreationException {

    X509Certificate clientCert;

    Hashtable extension = new Hashtable();

    extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier)));

    String completeRole = "";
    for (String role : roles) {
        completeRole += role + ", ";
    }
    completeRole = completeRole.substring(0, completeRole.length() - 2);
    extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole)));

    extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider())));

    Map<String, String> extensionMap = new HashMap();
    if (id.getOtherValues() != null) {
        for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) {
            extension.put(new DERObjectIdentifier(entry.getKey().getOID()),
                    new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue())));
            extensionMap.put(entry.getKey().getName(), entry.getValue());
        }
    }

    try {

        String x509NameString = "";
        x509NameString += "CN=" + id.getCommonName();

        if (id.getSurname() != null && !id.getSurname().equals("")) {
            x509NameString += ", SURNAME=" + id.getSurname();
        }
        if (id.getGivenName() != null && !id.getGivenName().equals("")) {
            x509NameString += ", GIVENNAME=" + id.getGivenName();
        }
        if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) {
            x509NameString += ", UID=" + id.getUniqueIdentifier();
        }
        if (id.getOrganisation() != null && !id.getOrganisation().equals("")) {
            x509NameString += ", O=" + id.getOrganisation();
        }
        if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) {
            x509NameString += ", OU=" + id.getOrganisationUnit();
        }
        if (id.getCountryName() != null && !id.getCountryName().equals("")) {
            x509NameString += ", C=" + id.getCountryName();
        }
        if (id.getState() != null && !id.getState().equals("")) {
            x509NameString += ", ST=" + id.getState();
        }
        if (id.getLocality() != null && !id.getLocality().equals("")) {
            x509NameString += ", L=" + id.getLocality();
        }

        X509Name x509Name = new X509Name(x509NameString);

        V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
        certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis())));
        certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert));
        certGen.setSubject(x509Name);
        certGen.setExtensions(new X509Extensions(extension));
        DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5");
        AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull());
        certGen.setSignature(sigAlgId);
        certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject()));
        certGen.setStartDate(new Time(new Date(System.currentTimeMillis())));
        certGen.setEndDate(new Time(expiry.getTime()));
        TBSCertificateStructure tbsCert = certGen.generateTBSCertificate();

        //Sign certificate
        SHA1Digest digester = new SHA1Digest();
        AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(tbsCert);
        byte[] signature;
        byte[] certBlock = bOut.toByteArray();
        // first create digest
        digester.update(certBlock, 0, certBlock.length);
        byte[] hash = new byte[digester.getDigestSize()];
        digester.doFinal(hash, 0);
        // then sign it
        rsa.init(true, cipherParams);
        DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash);
        byte[] digest = dInfo.getEncoded(ASN1Encodable.DER);
        signature = rsa.processBlock(digest, 0, digest.length);

        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(tbsCert);
        v.add(sigAlgId);
        v.add(new DERBitString(signature));

        // Create CRT data structure
        clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v)));
        clientCert.verify(caCert.getPublicKey());
    } catch (IOException | CertificateException | NoSuchAlgorithmException | InvalidKeyException
            | NoSuchProviderException | InvalidCipherTextException | SignatureException e) {
        logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() });
        throw new CertificateCreationException("230 Could not create client certificate");
    }

    return new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(), id.getOrganisation(),
            id.getOrganisationUnit(), id.getCountryName(), id.getState(), id.getLocality(), id.getSurname(),
            id.getGivenName(), applicationIdentifier, roles, id.getIdentityProvider(), extensionMap);

}

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

License:Open Source License

@Override
public void setDEREncoded(byte[] _DEREncoded) {
    ///*w ww  .j a  v  a  2s  .co  m*/
    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;// ww w  . j a  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;
}

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

License:Open Source License

@Override
public CertificateState verifyCertificateCompliance(XFrame _xFrame, Object arg0)
        throws IllegalArgumentException, Exception {

    m_xQc = (XOX_X509Certificate) UnoRuntime.queryInterface(XOX_X509Certificate.class, arg0);
    if (m_xQc == null)
        throw (new IllegalArgumentException(
                "XOX_CertificateComplianceProcedure#verifyCertificateCertificateCompliance wrong argument"));
    m_aCertificateState = CertificateState.OK;
    m_aLogger.log("verifyCertificateCompliance");

    //convert the certificate to java internal representation
    java.security.cert.CertificateFactory cf;
    try {//w w w . j a  v a2  s  .c om
        cf = java.security.cert.CertificateFactory.getInstance("X.509");
        java.io.ByteArrayInputStream bais = null;
        bais = new java.io.ByteArrayInputStream(m_xQc.getCertificateAttributes().getDEREncoded());
        m_JavaCert = (java.security.cert.X509Certificate) cf.generateCertificate(bais);
        //check for version, if version is not 3, exits, certificate cannot be used
        if (m_JavaCert.getVersion() != 3) {
            m_xQc.setCertificateElementErrorState(GlobConstant.m_sX509_CERTIFICATE_VERSION,
                    CertificateElementState.INVALID_value);
            setCertificateStateHelper(CertificateState.MALFORMED_CERTIFICATE);
            m_xQc.getCertificateDisplayObj().setCertificateElementCommentString(CertificateElementID.VERSION,
                    "Version MUST be V3");
            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();
        } catch (CertificateExpiredException e) {
            m_xQc.setCertificateElementErrorState(GlobConstant.m_sX509_CERTIFICATE_NOT_AFTER,
                    CertificateElementState.INVALID_value);
            setCertificateStateHelper(CertificateState.EXPIRED);
            m_xQc.getCertificateDisplayObj().setCertificateElementCommentString(CertificateElementID.NOT_AFTER,
                    "The date is elapsed.");
        } catch (CertificateNotYetValidException e) {
            m_xQc.setCertificateElementErrorState(GlobConstant.m_sX509_CERTIFICATE_NOT_BEFORE,
                    CertificateElementState.INVALID_value);
            setCertificateStateHelper(CertificateState.NOT_ACTIVE);
            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 both IssuerUniqueID and SubjectUniqueID are 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;
}

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

License:Open Source License

@Override
public void prepareDisplayStrings(XFrame _xFrame, XComponent _xComp)
        throws IllegalArgumentException, Exception {
    m_xQc = (XOX_X509Certificate) UnoRuntime.queryInterface(XOX_X509Certificate.class, _xComp);
    if (m_xQc == null)
        throw (new IllegalArgumentException(
                "com.yacme.ext.oxsit.security.cert.XOX_X509CertificateDisplay#prepareDisplayStrings wrong argument"));

    ///*from w w w.jav a2s. c o  m*/
    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(m_xQc.getCertificateAttributes().getDEREncoded());
    ASN1InputStream aderin = new ASN1InputStream(as);
    DERObject ado;
    try {
        ado = aderin.readObject();
        m_aX509 = new X509CertificateStructure((ASN1Sequence) ado);
        //initializes the certificate display information
        initSubjectName();
        m_sVersion = String.format("V%d", m_aX509.getVersion());
        m_sSerialNumber = new String("" + m_aX509.getSerialNumber().getValue());
        initIssuerName();
        m_sNotValidBefore = initCertDate(m_aX509.getStartDate().getDate());
        m_sNotValidAfter = initCertDate(m_aX509.getEndDate().getDate());
        m_sSubjectPublicKeyAlgorithm = initPublicKeyAlgorithm();
        m_sSubjectPublicKeyValue = initPublicKeyData();
        m_sSignatureAlgorithm = initSignatureAlgorithm();
        initThumbPrints();
        //now initializes the Extension listing         
        X509Extensions aX509Exts = m_aX509.getTBSCertificate().getExtensions();
        //fill the internal extension HashMaps
        //at the same time we'll get the extension localized name from resources and
        //fill the display data
        MessageConfigurationAccess m_aRegAcc = null;
        m_aRegAcc = new MessageConfigurationAccess(m_xContext, m_xMCF);
        //FIXME: may be we need to adapt this to the context: the following is valid ONLY if this
        //object is instantiated from within a dialog, is not true if instantiated from a not UI method (e.g. from basic for example).
        IDynamicLogger aDlgH = null;
        CertificateExtensionDisplayHelper aHelper = new CertificateExtensionDisplayHelper(m_xContext,
                m_lTheLocale, m_sTimeLocaleString, m_sLocaleDateOfBirth, m_bDisplayOID, m_aLogger);

        for (Enumeration<DERObjectIdentifier> enume = aX509Exts.oids(); enume.hasMoreElements();) {
            DERObjectIdentifier aDERId = enume.nextElement();
            String aTheOID = aDERId.getId();
            X509Extension aext = aX509Exts.getExtension(aDERId);
            m_aExtensions.put(aTheOID, aext);
            //now grab the localized description
            try {
                m_aExtensionLocalizedNames.put(aTheOID, m_aRegAcc.getStringFromRegistry(aTheOID)
                        + ((m_bDisplayOID) ? (" (OID: " + aTheOID.toString() + ")") : ""));
            } catch (com.sun.star.uno.Exception e) {
                m_aLogger.severe("setDEREncoded", e);
                m_aExtensionLocalizedNames.put(aTheOID, aTheOID);
            }
            //and decode this extension
            m_aExtensionDisplayValues.put(aTheOID, aHelper.examineExtension(aext, aDERId, this));

            if (aext.isCritical())
                m_aCriticalExtensions.put(aTheOID, aext);
            else
                m_aNotCriticalExtensions.put(aTheOID, aext);
        }
        m_aRegAcc.dispose();
    } catch (IOException e) {
        m_aLogger.severe("setDEREncoded", e);
    }
}

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 www. ja v  a2 s .  c  om
    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.pkcs11.PKCS11Driver.java

License:Open Source License

/**
 * Finds a certificate matching the one passed as parameter.
 *
 * @param _aCertificate/* w w  w.  ja va  2 s  . c  om*/
 * @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:ec.rubrica.util.BouncyCastleUtils.java

License:Open Source License

public static boolean certificateHasPolicy(X509Certificate cert, String sOid) {
    try {/*from w  w w  .ja  va 2  s .c  o  m*/
        logger.fine("Read cert policies: " + cert.getSerialNumber().toString());

        ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
        ASN1InputStream aIn = new ASN1InputStream(bIn);
        ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
        X509CertificateStructure obj = new X509CertificateStructure(seq);
        TBSCertificateStructure tbsCert = obj.getTBSCertificate();
        if (tbsCert.getVersion() == 3) {
            X509Extensions ext = tbsCert.getExtensions();
            if (ext != null) {
                Enumeration en = ext.oids();
                while (en.hasMoreElements()) {
                    DERObjectIdentifier oid = (DERObjectIdentifier) en.nextElement();
                    X509Extension extVal = ext.getExtension(oid);
                    ASN1OctetString oct = extVal.getValue();
                    ASN1InputStream extIn = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets()));

                    if (oid.equals(X509Extension.certificatePolicies)) {
                        ASN1Sequence cp = (ASN1Sequence) extIn.readObject();
                        for (int i = 0; i != cp.size(); i++) {
                            PolicyInformation pol = PolicyInformation.getInstance(cp.getObjectAt(i));
                            DERObjectIdentifier dOid = pol.getPolicyIdentifier();
                            String soid2 = dOid.getId();

                            logger.fine("Policy: " + soid2);
                            if (soid2.startsWith(sOid))
                                return true;
                        }
                    }
                }
            }

        }
    } catch (Exception ex) {
        logger.severe("Error reading cert policies: " + ex);
    }
    return false;
}

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESProfileXL.java

License:Open Source License

private Hashtable<ASN1ObjectIdentifier, ASN1Encodable> extendUnsignedAttributes(
        Hashtable<ASN1ObjectIdentifier, ASN1Encodable> unsignedAttrs, X509Certificate signingCertificate,
        Date signingDate, CertificateSource optionalCertificateSource) throws IOException {

    ValidationContext validationContext = certificateVerifier.validateCertificate(signingCertificate,
            signingDate, optionalCertificateSource, null, null);

    try {/*from www. ja  v a  2 s. c om*/
        List<X509CertificateStructure> certificateValues = new ArrayList<X509CertificateStructure>();
        ArrayList<CertificateList> crlValues = new ArrayList<CertificateList>();
        ArrayList<BasicOCSPResponse> ocspValues = new ArrayList<BasicOCSPResponse>();

        /*
         * The ETSI TS 101 733 stipulates (6.2.1): "It references the full set of CA certificates that have been
         * used to validate an ES with Complete validation data up to (but not including) the signer's certificate.
         * [...] NOTE 1: The signer's certificate is referenced in the signing certificate attribute (see clause
         * 5.7.3)." (6.2.1)
         * 
         * "The second and subsequent CrlOcspRef fields shall be in the same order as the OtherCertID to which they
         * relate." (6.2.2)
         * 
         * Also, no mention of the way to order those second and subsequent fields, so we add the certificates as
         * provided by the context.
         */

        /* The SignedCertificate is in validationContext.getCertificate() */

        for (CertificateAndContext c : validationContext.getNeededCertificates()) {

            /*
             * Add every certificate except the signing certificate
             */
            if (!c.equals(signingCertificate)) {
                certificateValues.add(new X509CertificateStructure(
                        (ASN1Sequence) ASN1Object.fromByteArray(c.getCertificate().getEncoded())));
            }

        }

        /*
         * Record each CRL and OCSP with a reference to the corresponding certificate
         */
        for (CRL relatedcrl : validationContext.getNeededCRL()) {
            crlValues.add(new CertificateList(
                    (ASN1Sequence) ASN1Object.fromByteArray(((X509CRL) relatedcrl).getEncoded())));
        }

        for (BasicOCSPResp relatedocspresp : validationContext.getNeededOCSPResp()) {
            ocspValues.add((new BasicOCSPResponse(
                    (ASN1Sequence) ASN1Object.fromByteArray(relatedocspresp.getEncoded()))));
        }

        CertificateList[] crlValuesArray = new CertificateList[crlValues.size()];
        BasicOCSPResponse[] ocspValuesArray = new BasicOCSPResponse[ocspValues.size()];
        RevocationValues revocationValues = new RevocationValues(crlValues.toArray(crlValuesArray),
                ocspValues.toArray(ocspValuesArray), null);
        unsignedAttrs.put(PKCSObjectIdentifiers.id_aa_ets_revocationValues,
                new Attribute(PKCSObjectIdentifiers.id_aa_ets_revocationValues, new DERSet(revocationValues)));

        X509CertificateStructure[] certValuesArray = new X509CertificateStructure[certificateValues.size()];
        unsignedAttrs.put(PKCSObjectIdentifiers.id_aa_ets_certValues,
                new Attribute(PKCSObjectIdentifiers.id_aa_ets_certValues,
                        new DERSet(new DERSequence(certificateValues.toArray(certValuesArray)))));

    } catch (CertificateEncodingException e) {
        throw new RuntimeException(e);
    } catch (CRLException e) {
        throw new RuntimeException(e);
    }

    return unsignedAttrs;

}