Example usage for java.security.cert X509Certificate getSerialNumber

List of usage examples for java.security.cert X509Certificate getSerialNumber

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getSerialNumber.

Prototype

public abstract BigInteger getSerialNumber();

Source Link

Document

Gets the serialNumber value from the certificate.

Usage

From source file:org.signserver.admin.cli.defaultimpl.WSAuditorsCommand.java

@Override
public int execute(String... args)
        throws IllegalCommandArgumentsException, CommandFailureException, UnexpectedCommandFailureException {
    try {//  w  w w. java 2  s .c  o m
        // Parse the command line
        parseCommandLine(new GnuParser().parse(OPTIONS, args));
    } catch (ParseException ex) {
        throw new IllegalCommandArgumentsException(ex.getMessage());
    }
    validateOptions();

    try {
        final String admins = getGlobalConfigurationSession().getGlobalConfiguration()
                .getProperty(GlobalConfiguration.SCOPE_GLOBAL, "WSAUDITORS");
        final List<Entry> entries = parseAdmins(admins);

        if (LIST.equals(operation)) {
            final StringBuilder buff = new StringBuilder();
            buff.append("Authorized auditors:");
            buff.append("\n");
            for (Entry entry : entries) {
                buff.append(String.format("%-20s %s", entry.getCertSerialNo(), entry.getIssuerDN()));
                buff.append("\n");
            }
            getOutputStream().println(buff.toString());
        } else if (ADD.equals(operation)) {
            if (cert == null) {
                // serial number and issuer DN was entered manually
                entries.add(new Entry(certSerialNo, issuerDN));
            } else {
                // read serial number and issuer DN from cert file
                X509Certificate certificate = SignServerUtil.getCertFromFile(cert);
                String sn = certificate.getSerialNumber().toString(16);
                String dn = certificate.getIssuerX500Principal().getName();

                CertTools.BasicX509NameTokenizer tok = new CertTools.BasicX509NameTokenizer(dn);
                StringBuilder buf = new StringBuilder();

                while (tok.hasMoreTokens()) {
                    final String token = tok.nextToken();
                    buf.append(token);
                    if (tok.hasMoreTokens()) {
                        buf.append(", ");
                    }
                }

                entries.add(new Entry(sn, buf.toString()));
            }
            getGlobalConfigurationSession().setProperty(GlobalConfiguration.SCOPE_GLOBAL, "WSAUDITORS",
                    serializeAdmins(entries));
            getOutputStream().println("Auditor added");
        } else if (REMOVE.equals(operation)) {
            if (entries.remove(new Entry(certSerialNo, issuerDN))) {
                getGlobalConfigurationSession().setProperty(GlobalConfiguration.SCOPE_GLOBAL, "WSAUDITORS",
                        serializeAdmins(entries));
                getOutputStream().println("Auditor removed");
            } else {
                getErrorStream().println("No such auditor");
            }
        }
        return 0;
    } catch (EJBException eJBException) {
        if (eJBException.getCausedByException() instanceof IllegalArgumentException) {
            getErrorStream().println(eJBException.getMessage());
            return -2;
        } else {
            throw new UnexpectedCommandFailureException(eJBException);
        }
    } catch (Exception e) {
        throw new UnexpectedCommandFailureException(e);
    }
}

From source file:mitm.common.security.cms.SignerIdentifierImpl.java

@Override
public boolean match(X509Certificate certificate) throws IOException {
    if (certificate == null) {
        return false;
    }// w w w. ja v a  2s. c o  m

    if (issuer != null && !issuer.equals(certificate.getIssuerX500Principal())) {
        return false;
    }

    if (serialNumber != null && !serialNumber.equals(certificate.getSerialNumber())) {
        return false;
    }

    if (subjectKeyIdentifier != null && !Arrays.equals(subjectKeyIdentifier,
            X509CertificateInspector.getSubjectKeyIdentifier(certificate))) {
        return false;
    }

    return true;
}

From source file:org.ejbca.core.protocol.ocsp.extension.unid.OCSPUnidExtension.java

@Override
public void init() {
    // DataSource
    dataSourceJndi = OcspConfiguration.getUnidDataSource();
    if (StringUtils.isEmpty(dataSourceJndi)) {
        String errMsg = intres.getLocalizedMessage("ocsp.errornoinitparam", "unidDataSource");
        m_log.error(errMsg);/*from ww  w .  j ava  2  s .c om*/
        throw new IllegalArgumentException(errMsg);
    }
    String trustDir = OcspConfiguration.getUnidTrustDir();
    if (StringUtils.isEmpty(trustDir)) {
        String errMsg = intres.getLocalizedMessage("ocsp.errornoinitparam", "unidTrustDir");
        m_log.error(errMsg);
        throw new IllegalArgumentException(errMsg);
    }
    // read all files from trustDir, expect that they are PEM formatted certificates
    CryptoProviderTools.installBCProviderIfNotAvailable();
    File dir = new File(trustDir);
    try {
        if (dir == null || dir.isDirectory() == false) {
            m_log.error(dir.getCanonicalPath() + " is not a directory.");
            throw new IllegalArgumentException(dir.getCanonicalPath() + " is not a directory.");
        }
        File files[] = dir.listFiles();
        if (files == null || files.length == 0) {
            String errMsg = intres.getLocalizedMessage("ocsp.errornotrustfiles", dir.getCanonicalPath());
            m_log.error(errMsg);
        }
        for (int i = 0; i < files.length; i++) {
            final String fileName = files[i].getCanonicalPath();
            // Read the file, don't stop completely if one file has errors in it
            try {
                final byte bFromFile[] = FileTools.readFiletoBuffer(fileName);
                byte[] bytes;
                try {
                    bytes = FileTools.getBytesFromPEM(bFromFile, CertTools.BEGIN_CERTIFICATE,
                            CertTools.END_CERTIFICATE);
                } catch (Exception t) {
                    bytes = bFromFile; // assume binary data (.der)
                }
                final X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(bytes);
                this.trustedCerts.add(cert.getSerialNumber());
            } catch (CertificateException e) {
                String errMsg = intres.getLocalizedMessage("ocsp.errorreadingfile", fileName, "trustDir",
                        e.getMessage());
                m_log.error(errMsg, e);
            } catch (IOException e) {
                String errMsg = intres.getLocalizedMessage("ocsp.errorreadingfile", fileName, "trustDir",
                        e.getMessage());
                m_log.error(errMsg, e);
            }
        }
    } catch (IOException e) {
        String errMsg = intres.getLocalizedMessage("ocsp.errorreadingtrustfiles", e.getMessage());
        m_log.error(errMsg, e);
        throw new IllegalArgumentException(errMsg);
    }
    String cacertfile = OcspConfiguration.getUnidCaCert();
    if (StringUtils.isEmpty(cacertfile)) {
        String errMsg = intres.getLocalizedMessage("ocsp.errornoinitparam", "unidCACert");
        m_log.error(errMsg);
        throw new IllegalArgumentException(errMsg);
    }
    try {
        byte[] bytes = FileTools.getBytesFromPEM(FileTools.readFiletoBuffer(cacertfile),
                CertTools.BEGIN_CERTIFICATE, CertTools.END_CERTIFICATE);
        cacert = CertTools.getCertfromByteArray(bytes);
    } catch (Exception e) {
        String errMsg = intres.getLocalizedMessage("ocsp.errorreadingfile", "file", "cacertfile",
                e.getMessage());
        m_log.error(errMsg, e);
        throw new IllegalArgumentException(errMsg);
    }

}

From source file:mx.bigdata.sat.cfdi.CFDv33.java

@Override
public void sellar(PrivateKey key, X509Certificate cert) throws Exception {
    String nc = new String(cert.getSerialNumber().toByteArray());
    cert.checkValidity();//from w  w  w.java  2 s  . c om
    byte[] bytes = cert.getEncoded();
    Base64 b64 = new Base64(-1);
    String certStr = b64.encodeToString(bytes);
    document.setCertificado(certStr);
    document.setNoCertificado(nc);
    String signature = getSignature(key);
    document.setSello(signature);
}

From source file:test.integ.be.fedict.trust.CodeSigningTest.java

@Test
public void testValidation2011_2014() throws Exception {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    InputStream fedictCertInputStream = CodeSigningTest.class.getResourceAsStream("/fedict-2011-2014.der");
    X509Certificate fedictCert = (X509Certificate) certificateFactory
            .generateCertificate(fedictCertInputStream);
    LOG.debug("code signing not before: " + fedictCert.getNotBefore());
    LOG.debug("code signing serial: " + fedictCert.getSerialNumber());

    InputStream govCertInputStream = CodeSigningTest.class.getResourceAsStream("/gov-ca-2011.der");
    X509Certificate govCert = (X509Certificate) certificateFactory.generateCertificate(govCertInputStream);

    InputStream rootCertInputStream = CodeSigningTest.class.getResourceAsStream("/root-ca2.der");
    X509Certificate rootCert = (X509Certificate) certificateFactory.generateCertificate(rootCertInputStream);

    InputStream gsCertInputStream = CodeSigningTest.class
            .getResourceAsStream("/be/fedict/trust/roots/globalsign-be.crt");
    X509Certificate gsCert = (X509Certificate) certificateFactory.generateCertificate(gsCertInputStream);

    List<X509Certificate> certChain = new LinkedList<>();
    certChain.add(fedictCert);//w w w. j  a v a2  s .  c  om
    certChain.add(govCert);
    certChain.add(rootCert);
    certChain.add(gsCert);

    MemoryCertificateRepository certificateRepository = new MemoryCertificateRepository();
    certificateRepository.addTrustPoint(gsCert);
    TrustValidator trustValidator = new TrustValidator(certificateRepository);

    NetworkConfig networkConfig = new NetworkConfig("proxy.yourict.net", 8080);
    TrustValidatorDecorator trustValidatorDecorator = new TrustValidatorDecorator(networkConfig);
    trustValidatorDecorator.addDefaultTrustLinkerConfig(trustValidator, null, true);

    trustValidator.isTrusted(certChain);
}

From source file:org.ejbca.core.protocol.ocsp.OCSPUnidExtension.java

/** Called after construction
 * //w  ww  . j  av  a  2s. c  o m
 * @param config ServletConfig that can be used to read init-params from web-xml
 */
public void init(ServletConfig config) {
    // DataSource
    dataSourceJndi = OcspConfiguration.getUnidDataSource();
    if (StringUtils.isEmpty(dataSourceJndi)) {
        String errMsg = intres.getLocalizedMessage("ocsp.errornoinitparam", "unidDataSource");
        m_log.error(errMsg);
        throw new IllegalArgumentException(errMsg);
    }
    String trustDir = OcspConfiguration.getUnidTrustDir();
    if (StringUtils.isEmpty(trustDir)) {
        String errMsg = intres.getLocalizedMessage("ocsp.errornoinitparam", "unidTrustDir");
        m_log.error(errMsg);
        throw new IllegalArgumentException(errMsg);
    }
    // read all files from trustDir, expect that they are PEM formatted certificates
    CertTools.installBCProvider();
    File dir = new File(trustDir);
    try {
        if (dir == null || dir.isDirectory() == false) {
            m_log.error(dir.getCanonicalPath() + " is not a directory.");
            throw new IllegalArgumentException(dir.getCanonicalPath() + " is not a directory.");
        }
        File files[] = dir.listFiles();
        if (files == null || files.length == 0) {
            String errMsg = intres.getLocalizedMessage("ocsp.errornotrustfiles", dir.getCanonicalPath());
            m_log.error(errMsg);
        }
        for (int i = 0; i < files.length; i++) {
            final String fileName = files[i].getCanonicalPath();
            // Read the file, don't stop completely if one file has errors in it
            try {
                final byte bFromFile[] = FileTools.readFiletoBuffer(fileName);
                byte[] bytes;
                try {
                    bytes = FileTools.getBytesFromPEM(bFromFile, CertTools.BEGIN_CERTIFICATE,
                            CertTools.END_CERTIFICATE);
                } catch (Throwable t) {
                    bytes = bFromFile; // assume binary data (.der)
                }
                final X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(bytes);
                this.trustedCerts.add(cert.getSerialNumber());
            } catch (CertificateException e) {
                String errMsg = intres.getLocalizedMessage("ocsp.errorreadingfile", fileName, "trustDir",
                        e.getMessage());
                m_log.error(errMsg, e);
            } catch (IOException e) {
                String errMsg = intres.getLocalizedMessage("ocsp.errorreadingfile", fileName, "trustDir",
                        e.getMessage());
                m_log.error(errMsg, e);
            }
        }
    } catch (IOException e) {
        String errMsg = intres.getLocalizedMessage("ocsp.errorreadingtrustfiles", e.getMessage());
        m_log.error(errMsg, e);
        throw new IllegalArgumentException(errMsg);
    }
    String cacertfile = OcspConfiguration.getUnidCaCert();
    if (StringUtils.isEmpty(cacertfile)) {
        String errMsg = intres.getLocalizedMessage("ocsp.errornoinitparam", "unidCACert");
        m_log.error(errMsg);
        throw new IllegalArgumentException(errMsg);
    }
    try {
        byte[] bytes = FileTools.getBytesFromPEM(FileTools.readFiletoBuffer(cacertfile),
                CertTools.BEGIN_CERTIFICATE, CertTools.END_CERTIFICATE);
        cacert = CertTools.getCertfromByteArray(bytes);
    } catch (Exception e) {
        String errMsg = intres.getLocalizedMessage("ocsp.errorreadingfile", "file", "cacertfile",
                e.getMessage());
        m_log.error(errMsg, e);
        throw new IllegalArgumentException(errMsg);
    }

}

From source file:org.signserver.admin.cli.defaultimpl.WSAdminsCommand.java

@Override
public int execute(String... args)
        throws IllegalCommandArgumentsException, CommandFailureException, UnexpectedCommandFailureException {
    final CommandLine line;
    try {//from   w w  w  .java 2s  . c om
        // Parse the command line
        line = new GnuParser().parse(OPTIONS, args);
        parseCommandLine(line);
    } catch (ParseException ex) {
        throw new IllegalCommandArgumentsException(ex.getMessage());
    } catch (IllegalCommandArgumentsException e) {
        throw e;
    }
    validateOptions();

    try {
        final String admins = getGlobalConfigurationSession().getGlobalConfiguration()
                .getProperty(GlobalConfiguration.SCOPE_GLOBAL, "WSADMINS");
        final Set<ClientEntry> entries;

        if (admins != null) {
            entries = ClientEntry.clientEntriesFromProperty(admins);
        } else {
            entries = new HashSet<ClientEntry>();
        }

        if (LIST.equals(operation)) {
            final String allowAnyWSAdminProp = getGlobalConfigurationSession().getGlobalConfiguration()
                    .getProperty(GlobalConfiguration.SCOPE_GLOBAL, ALLOWANYWSADMIN);
            final boolean allowAnyWSAdmin = allowAnyWSAdminProp != null
                    ? Boolean.parseBoolean(allowAnyWSAdminProp)
                    : false;
            final StringBuilder buff = new StringBuilder();
            buff.append("Authorized administrators:");
            buff.append("\n");

            if (allowAnyWSAdmin) {
                buff.append("ANY CERTIFICATE ACCEPTED FOR WS ADMINISTRATORS");
                buff.append("\n");
                buff.append(
                        "Use the command \"signserver wsadmins -allowany false\" to enable the administrator list");
                buff.append("\n");
            } else {
                for (ClientEntry entry : entries) {
                    buff.append(String.format("%-20s %s", entry.getSerialNumber().toString(16),
                            entry.getIssuerDN()));
                    buff.append("\n");
                }
            }
            getOutputStream().println(buff.toString());
        } else if (ADD.equals(operation)) {
            final boolean added;
            if (cert == null) {
                // serial number and issuer DN was entered manually
                added = entries.add(new ClientEntry(certSerialNo, issuerDN));
            } else {
                // read serial number and issuer DN from cert file
                X509Certificate certificate = SignServerUtil.getCertFromFile(cert);

                added = entries.add(new ClientEntry(certificate.getSerialNumber(),
                        SignServerUtil.getTokenizedIssuerDNFromCert(certificate)));
            }

            if (added) {
                getGlobalConfigurationSession().setProperty(GlobalConfiguration.SCOPE_GLOBAL, "WSADMINS",
                        ClientEntry.serializeClientEntries(entries));
                getOutputStream().println("Administrator added");
            } else {
                getOutputStream().println("Administrator already exists");
            }
        } else if (REMOVE.equals(operation)) {
            if (entries.remove(new ClientEntry(certSerialNo, issuerDN))) {
                getGlobalConfigurationSession().setProperty(GlobalConfiguration.SCOPE_GLOBAL, "WSADMINS",
                        ClientEntry.serializeClientEntries(entries));
                getOutputStream().println("Administrator removed");
            } else {
                getErrorStream().println("No such administrator");
            }
        } else if (ALLOWANY.equals(operation)) {
            boolean allowAny = true;
            final String value = line.getOptionValue(ALLOWANY);

            if (value != null) {
                allowAny = Boolean.parseBoolean(value);
            }

            if (allowAny) {
                getGlobalConfigurationSession().setProperty(GlobalConfiguration.SCOPE_GLOBAL, ALLOWANYWSADMIN,
                        "true");
                getOutputStream().println("Set to allow any WS admin");
            } else {
                getGlobalConfigurationSession().removeProperty(GlobalConfiguration.SCOPE_GLOBAL,
                        ALLOWANYWSADMIN);
                getOutputStream().println("Set to not allow any WS admin");
            }
        }
        return 0;
    } catch (EJBException eJBException) {
        if (eJBException.getCausedByException() instanceof IllegalArgumentException) {
            getErrorStream().println(eJBException.getMessage());
            return -2;
        } else {
            throw new UnexpectedCommandFailureException(eJBException);
        }
    } catch (Exception e) {
        throw new UnexpectedCommandFailureException(e);
    }
}

From source file:eu.europa.esig.dss.pades.InfiniteLoopDSS621Test.java

/**
 * These signatures are invalid because of non ordered  signed attributes
 *///from  w ww.j  a v  a  2 s.  co m
@Test
public void manualTest() throws Exception {

    File pdfFile = new File(FILE_PATH);

    FileInputStream fis = new FileInputStream(pdfFile);
    byte[] pdfBytes = IOUtils.toByteArray(fis);

    PDDocument document = PDDocument.load(pdfFile);
    List<PDSignature> signatures = document.getSignatureDictionaries();
    assertEquals(6, signatures.size());

    int idx = 0;
    for (PDSignature pdSignature : signatures) {
        byte[] contents = pdSignature.getContents(pdfBytes);
        byte[] signedContent = pdSignature.getSignedContent(pdfBytes);

        logger.info("Byte range : " + Arrays.toString(pdSignature.getByteRange()));

        IOUtils.write(contents, new FileOutputStream("target/sig" + (idx++) + ".p7s"));

        ASN1InputStream asn1sInput = new ASN1InputStream(contents);
        ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

        logger.info("SEQ : " + asn1Seq.toString());

        ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
        assertEquals(PKCSObjectIdentifiers.signedData, oid);

        SignedData signedData = SignedData
                .getInstance(DERTaggedObject.getInstance(asn1Seq.getObjectAt(1)).getObject());

        ASN1Set digestAlgorithmSet = signedData.getDigestAlgorithms();
        ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier
                .getInstance(ASN1Sequence.getInstance(digestAlgorithmSet.getObjectAt(0)).getObjectAt(0));
        DigestAlgorithm digestAlgorithm = DigestAlgorithm.forOID(oidDigestAlgo.getId());
        logger.info("DIGEST ALGO : " + digestAlgorithm);

        ContentInfo encapContentInfo = signedData.getEncapContentInfo();
        ASN1ObjectIdentifier contentTypeOID = encapContentInfo.getContentType();
        logger.info("ENCAPSULATED CONTENT INFO TYPE : " + contentTypeOID);

        if (!PKCSObjectIdentifiers.id_ct_TSTInfo.equals(contentTypeOID)) { // If not timestamp
            assertEquals(PKCSObjectIdentifiers.data, contentTypeOID);

            ASN1Encodable content = encapContentInfo.getContent();
            logger.info("ENCAPSULATED CONTENT INFO CONTENT : " + content);
            assertNull(content);

            List<X509Certificate> certificates = extractCertificates(signedData);

            ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
            logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString());
            SignerInfo signedInfo = SignerInfo
                    .getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0)));

            ASN1Set authenticatedAttributeSet = signedInfo.getAuthenticatedAttributes();
            logger.info("AUTHENTICATED ATTR : " + authenticatedAttributeSet);

            Attribute attributeDigest = null;
            for (int i = 0; i < authenticatedAttributeSet.size(); i++) {
                Attribute attribute = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(i));
                if (PKCSObjectIdentifiers.pkcs_9_at_messageDigest.equals(attribute.getAttrType())) {
                    attributeDigest = attribute;
                    break;
                }
            }

            assertNotNull(attributeDigest);

            ASN1OctetString asn1ObjString = ASN1OctetString
                    .getInstance(attributeDigest.getAttrValues().getObjectAt(0));
            String embeddedDigest = Base64.encode(asn1ObjString.getOctets());
            logger.info("MESSAGE DIGEST : " + embeddedDigest);

            byte[] digestSignedContent = DSSUtils.digest(digestAlgorithm, signedContent);
            String computedDigestSignedContentEncodeBase64 = Base64.encode(digestSignedContent);
            logger.info("COMPUTED DIGEST SIGNED CONTENT BASE64 : " + computedDigestSignedContentEncodeBase64);
            assertEquals(embeddedDigest, computedDigestSignedContentEncodeBase64);

            SignerIdentifier sid = signedInfo.getSID();
            logger.info("SIGNER IDENTIFIER : " + sid.getId());

            IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber
                    .getInstance(signedInfo.getSID());
            ASN1Integer signerSerialNumber = issuerAndSerialNumber.getSerialNumber();
            logger.info("ISSUER AND SN : " + issuerAndSerialNumber.getName() + " " + signerSerialNumber);

            BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue();
            X509Certificate signerCertificate = null;
            for (X509Certificate x509Certificate : certificates) {
                if (serial.equals(x509Certificate.getSerialNumber())) {
                    signerCertificate = x509Certificate;
                }
            }
            assertNotNull(signerCertificate);

            String algorithm = signerCertificate.getPublicKey().getAlgorithm();
            EncryptionAlgorithm encryptionAlgorithm = EncryptionAlgorithm.forName(algorithm);

            ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest();
            String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets());

            logger.info("SIGNATURE VALUE : " + signatureValue);

            Cipher cipher = Cipher.getInstance(encryptionAlgorithm.getName());
            cipher.init(Cipher.DECRYPT_MODE, signerCertificate);
            byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets());

            ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted);

            ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject();
            logger.info("DECRYPTED : " + seqDecrypt);

            DigestInfo digestInfo = new DigestInfo(seqDecrypt);
            assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm());

            String decryptedDigestEncodeBase64 = Base64.encode(digestInfo.getDigest());
            logger.info("DECRYPTED BASE64 : " + decryptedDigestEncodeBase64);

            byte[] encoded = authenticatedAttributeSet.getEncoded();
            byte[] digest = DSSUtils.digest(digestAlgorithm, encoded);
            String computedDigestFromSignatureEncodeBase64 = Base64.encode(digest);
            logger.info("COMPUTED DIGEST FROM SIGNATURE BASE64 : " + computedDigestFromSignatureEncodeBase64);

            assertEquals(decryptedDigestEncodeBase64, computedDigestFromSignatureEncodeBase64);

            IOUtils.closeQuietly(inputDecrypted);

        }

        IOUtils.closeQuietly(asn1sInput);
    }

    IOUtils.closeQuietly(fis);
    document.close();
}

From source file:be.fedict.eid.dss.model.bean.TrustValidationServiceBean.java

public void validate(TimeStampToken timeStampToken, List<OCSPResp> ocspResponses, List<X509CRL> crls)
        throws CertificateEncodingException, TrustDomainNotFoundException, RevocationDataNotFoundException,
        ValidationFailedException, NoSuchAlgorithmException, NoSuchProviderException, CMSException,
        CertStoreException, IOException {
    LOG.debug("performing historical TSA validation...");
    String tsaTrustDomain = this.configuration.getValue(ConfigProperty.TSA_TRUST_DOMAIN, String.class);
    LOG.debug("TSA trust domain: " + tsaTrustDomain);

    Date validationDate = timeStampToken.getTimeStampInfo().getGenTime();
    LOG.debug("TSA validation date is TST time: " + validationDate);
    LOG.debug("# TSA ocsp responses: " + ocspResponses.size());
    LOG.debug("# TSA CRLs: " + crls.size());

    /*/*  w  ww  .  j a  v a2s.c o m*/
     *Building TSA chain. (Code from eID-applet)
     * 
     */

    SignerId signerId = timeStampToken.getSID();
    BigInteger signerCertSerialNumber = signerId.getSerialNumber();
    //X500Principal signerCertIssuer = signerId.getIssuer();

    X500Principal signerCertIssuer = new X500Principal(signerId.getIssuer().getEncoded());

    LOG.debug("signer cert serial number: " + signerCertSerialNumber);
    LOG.debug("signer cert issuer: " + signerCertIssuer);

    // TSP signer certificates retrieval
    CertStore certStore = timeStampToken.getCertificatesAndCRLs("Collection",
            BouncyCastleProvider.PROVIDER_NAME);
    Collection<? extends Certificate> certificates = certStore.getCertificates(null);
    X509Certificate signerCert = null;
    Map<String, X509Certificate> certificateMap = new HashMap<String, X509Certificate>();
    for (Certificate certificate : certificates) {
        X509Certificate x509Certificate = (X509Certificate) certificate;
        if (signerCertIssuer.equals(x509Certificate.getIssuerX500Principal())
                && signerCertSerialNumber.equals(x509Certificate.getSerialNumber())) {
            signerCert = x509Certificate;
        }
        String ski = Hex.encodeHexString(getSubjectKeyId(x509Certificate));
        certificateMap.put(ski, x509Certificate);
        LOG.debug("embedded certificate: " + x509Certificate.getSubjectX500Principal() + "; SKI=" + ski);
    }

    // TSP signer cert path building
    if (null == signerCert) {
        throw new RuntimeException("TSP response token has no signer certificate");
    }
    List<X509Certificate> tspCertificateChain = new LinkedList<X509Certificate>();

    X509Certificate tsaIssuer = loadCertificate(
            "be/fedict/eid/dss/CA POLITICA SELLADO DE TIEMPO - COSTA RICA.crt");
    X509Certificate rootCA = loadCertificate("be/fedict/eid/dss/CA RAIZ NACIONAL COSTA RICA.cer");
    LOG.debug("adding to certificate chain: " + signerCert.getSubjectX500Principal());
    tspCertificateChain.add(signerCert);
    LOG.debug("adding to certificate chain: " + tsaIssuer.getSubjectX500Principal());
    tspCertificateChain.add(tsaIssuer);
    LOG.debug("adding to certificate chain: " + rootCA.getSubjectX500Principal());
    tspCertificateChain.add(rootCA);

    /*
     * Perform PKI validation via eID Trust Service.
     */
    getXkms2Client().validate(tsaTrustDomain, tspCertificateChain, validationDate, ocspResponses, crls);
}

From source file:org.ejbca.core.protocol.cmp.CrmfRARequestCustomSerialNoTest.java

@Test
public void test01CustomCertificateSerialNumber() throws Exception {
    final KeyPair key1 = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    final String userName1 = "cmptest1";
    final X500Name userDN1 = new X500Name("C=SE,O=PrimeKey,CN=" + userName1);
    try {//from w  w  w.  j a  v  a2  s  .c om
        // check that several certificates could be created for one user and one key.
        long serno = RandomUtils.nextLong();
        BigInteger bint = BigInteger.valueOf(serno);
        // First it should fail because the CMP RA does not even look for, or parse, requested custom certificate serial numbers
        // Actually it does not fail here, but returns good answer
        X509Certificate cert = crmfHttpUserTest(userDN1, key1, null, null);
        assertFalse("SerialNumbers should not be equal when custom serialnumbers are not allowed.",
                bint.equals(cert.getSerialNumber()));

        // Second it should fail when the certificate profile does not allow serial number override
        // crmfHttpUserTest checks the returned serno if bint parameter is not null
        this.cmpConfiguration.setAllowRACustomSerno(cmpAlias, true);
        this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);
        crmfHttpUserTest(userDN1, key1, "Used certificate profile ('" + this.cpDnOverrideId
                + "') is not allowing certificate serial number override.", bint);

        // Third it should succeed and we should get our custom requested serialnumber
        this.cmpConfiguration.setAllowRACustomSerno(cmpAlias, true);
        this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);
        CertificateProfile cp = this.certProfileSession.getCertificateProfile(this.cpDnOverrideId);
        cp.setAllowCertSerialNumberOverride(true);
        // Now when the profile allows serial number override it should work
        this.certProfileSession.changeCertificateProfile(ADMIN, CP_DN_OVERRIDE_NAME, cp);
        crmfHttpUserTest(userDN1, key1, null, bint);
    } finally {
        try {
            this.endEntityManagementSession.deleteUser(ADMIN, userName1);
        } catch (NotFoundException e) {
            /* do nothing */}
    }
}