Example usage for org.bouncycastle.asn1.x500 X500Name X500Name

List of usage examples for org.bouncycastle.asn1.x500 X500Name X500Name

Introduction

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

Prototype

public X500Name(String dirName) 

Source Link

Usage

From source file:at.asitplus.regkassen.core.modules.signature.rawsignatureprovider.NEVER_USE_IN_A_REAL_SYSTEM_SoftwareCertificateOpenSystemSignatureModule.java

License:Apache License

public void intialise() {
    try {//from   w w w  .j  a va2s  . co  m
        //create random demonstration ECC keys
        final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
        kpg.initialize(256); //256 bit ECDSA key

        //create a key pair for the demo Certificate Authority
        final KeyPair caKeyPair = kpg.generateKeyPair();

        //create a key pair for the signature certificate, which is going to be used to sign the receipts
        final KeyPair signingKeyPair = kpg.generateKeyPair();

        //get references to private keys for the CA and the signing key
        final PrivateKey caKey = caKeyPair.getPrivate();
        signingKey = signingKeyPair.getPrivate();

        //create CA certificate and add it to the certificate chain
        //NOTE: DO NEVER EVER USE IN A REAL CASHBOX, THIS IS JUST FOR DEMONSTRATION PURPOSES
        //NOTE: these certificates have random values, just for the demonstration purposes here
        //However, for testing purposes the most important feature is the EC256 Signing Key, since this is required
        //by the RK Suite
        final X509v3CertificateBuilder caBuilder = new X509v3CertificateBuilder(new X500Name("CN=RegKassa ZDA"),
                BigInteger.valueOf(new SecureRandom().nextLong()), new Date(System.currentTimeMillis() - 10000),
                new Date(System.currentTimeMillis() + 24L * 3600 * 1000), new X500Name("CN=RegKassa CA"),
                SubjectPublicKeyInfo.getInstance(caKeyPair.getPublic().getEncoded()));
        caBuilder.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(false));
        caBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
        final X509CertificateHolder caHolder = caBuilder
                .build(new JcaContentSignerBuilder("SHA256withECDSA").setProvider("BC").build(caKey));
        final X509Certificate caCertificate = new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(caHolder);
        certificateChain = new ArrayList<java.security.cert.Certificate>();
        certificateChain.add(caCertificate);

        //create signing cert
        final long serialNumberCertificate = new SecureRandom().nextLong();
        if (!closedSystemSignatureDevice) {
            serialNumberOrKeyId = Long.toHexString(serialNumberCertificate);
        }

        final X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
                new X500Name("CN=RegKassa CA"), BigInteger.valueOf(Math.abs(serialNumberCertificate)),
                new Date(System.currentTimeMillis() - 10000),
                new Date(System.currentTimeMillis() + 24L * 3600 * 1000),
                new X500Name("CN=Signing certificate"),
                SubjectPublicKeyInfo.getInstance(signingKeyPair.getPublic().getEncoded()));
        certBuilder.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(false));
        certBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
        final X509CertificateHolder certHolder = certBuilder
                .build(new JcaContentSignerBuilder("SHA256withECDSA").setProvider("BC").build(caKey));
        signingCertificate = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);

    } catch (final NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (final OperatorCreationException e) {
        e.printStackTrace();
    } catch (final CertIOException e) {
        e.printStackTrace();
    } catch (final CertificateException e) {
        e.printStackTrace();
    }
}

From source file:ataraxis.crypt.UBERKeyStoreHandlerTest.java

License:Open Source License

public static X509Certificate generateX509V3Cert(KeyPair keyPair) throws Exception {
    X509v1CertificateBuilder certBldr = new JcaX509v1CertificateBuilder(new X500Name("CN=Root"),
            BigInteger.valueOf(1), new Date(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() + 1000 * 3600 * 24), new X500Name("CN=Root"),
            keyPair.getPublic());//from w w  w .  j a  v  a2s.  c o  m

    ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC")
            .build(keyPair.getPrivate());

    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBldr.build(signer));
}

From source file:be.e_contract.mycarenet.common.SessionKey.java

License:Open Source License

private void generateCertificate() {
    X500Name name = new X500Name(this.name);
    BigInteger serial = BigInteger.valueOf(1);
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo
            .getInstance(this.keyPair.getPublic().getEncoded());
    X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(name, serial,
            this.notBefore, this.notAfter, name, publicKeyInfo);
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter asymmetricKeyParameter;
    try {/*from w  w w  . j  a v a 2 s . c  o  m*/
        asymmetricKeyParameter = PrivateKeyFactory.createKey(this.keyPair.getPrivate().getEncoded());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    ContentSigner contentSigner;
    try {
        contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(asymmetricKeyParameter);
    } catch (OperatorCreationException e) {
        throw new RuntimeException(e);
    }
    X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);

    byte[] encodedCertificate;
    try {
        encodedCertificate = x509CertificateHolder.getEncoded();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    CertificateFactory certificateFactory;
    try {
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    }
    try {
        this.certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(encodedCertificate));
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    }
}

From source file:be.fedict.trust.service.bean.HarvesterMDB.java

License:Open Source License

private void processHarvestMessage(HarvestMessage harvestMessage) {
    if (null == harvestMessage) {
        return;//from   w  w  w  . j a  va 2 s .  c o  m
    }
    String caName = harvestMessage.getCaName();
    boolean update = harvestMessage.isUpdate();
    String crlFilePath = harvestMessage.getCrlFile();
    File crlFile = new File(crlFilePath);

    LOG.debug("processHarvestMessage - Don't have CA's Serial Number??");
    LOG.debug("issuer: " + caName);
    CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO
            .findCertificateAuthority(caName);
    if (null == certificateAuthority) {
        LOG.error("unknown certificate authority: " + caName);
        deleteCrlFile(crlFile);
        return;
    }
    if (!update && Status.PROCESSING != certificateAuthority.getStatus()) {
        /*
         * Possible that another harvester instance already activated or is
         * processing the CA cache in the meanwhile.
         */
        LOG.debug("CA status not marked for processing");
        deleteCrlFile(crlFile);
        return;
    }

    Date validationDate = new Date();

    X509Certificate issuerCertificate = certificateAuthority.getCertificate();

    Date notAfter = issuerCertificate.getNotAfter();
    if (validationDate.after(notAfter)) {
        LOG.info("will not update CRL cache for expired CA: " + issuerCertificate.getSubjectX500Principal());
        deleteCrlFile(crlFile);
        return;
    }

    FileInputStream crlInputStream;
    try {
        crlInputStream = new FileInputStream(crlFile);
    } catch (FileNotFoundException e) {
        LOG.error("CRL file does not exist: " + crlFilePath);
        return;
    }
    X509CRL crl;
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
        crl = (X509CRL) certificateFactory.generateCRL(crlInputStream);
    } catch (Exception e) {
        LOG.error("BC error: " + e.getMessage(), e);
        deleteCrlFile(crlFile);
        return;
    }

    LOG.debug("checking integrity CRL...");
    boolean crlValid = CrlTrustLinker.checkCrlIntegrity(crl, issuerCertificate, validationDate);
    if (!crlValid) {
        this.auditDAO.logAudit("Invalid CRL for CA=" + caName);
        deleteCrlFile(crlFile);
        return;
    }
    BigInteger crlNumber = getCrlNumber(crl);
    LOG.debug("CRL number: " + crlNumber);

    BigInteger currentCrlNumber = this.certificateAuthorityDAO.findCrlNumber(caName);
    if (null != currentCrlNumber) {
        LOG.debug("CRL number in database: " + currentCrlNumber);
    }
    if (null != currentCrlNumber && currentCrlNumber.compareTo(crlNumber) >= 0
            && certificateAuthority.getStatus() == Status.ACTIVE) {
        // current CRL cache is higher or equal, no update needed
        LOG.debug("current CA cache is new enough.");
        deleteCrlFile(crlFile);
        return;
    }

    List<RevokedCertificateEntity> revokedCertificateEntities = this.certificateAuthorityDAO
            .getRevokedCertificates(caName);
    LOG.debug("number of revoked certificates in database: " + revokedCertificateEntities.size());
    Map<String, RevokedCertificateEntity> revokedCertificatesMap = new HashMap<String, RevokedCertificateEntity>();
    for (RevokedCertificateEntity revokedCertificateEntity : revokedCertificateEntities) {
        String serialNumber = revokedCertificateEntity.getPk().getSerialNumber();
        revokedCertificatesMap.put(serialNumber, revokedCertificateEntity);
    }

    LOG.debug("processing CRL... " + caName);
    boolean isIndirect;
    Enumeration revokedCertificatesEnum;
    try {
        isIndirect = isIndirectCRL(crl);
        revokedCertificatesEnum = getRevokedCertificatesEnum(crl);
    } catch (Exception e) {
        this.auditDAO.logAudit("Failed to parse CRL for CA=" + caName);
        this.failures++;
        throw new RuntimeException(e);
    }

    int entries = 0;
    if (revokedCertificatesEnum.hasMoreElements()) {
        /*
         * Split up persisting the crl entries to avoid memory issues.
         */
        Set<X509CRLEntry> revokedCertsBatch = new HashSet<X509CRLEntry>();
        X500Principal previousCertificateIssuer = crl.getIssuerX500Principal();
        int added = 0;
        while (revokedCertificatesEnum.hasMoreElements()) {

            TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry) revokedCertificatesEnum.nextElement();
            X500Name x500name = new X500Name(previousCertificateIssuer.getName(X500Principal.RFC1779));
            X509CRLEntryObject revokedCertificate = new X509CRLEntryObject(entry, isIndirect, x500name);
            previousCertificateIssuer = revokedCertificate.getCertificateIssuer();

            revokedCertsBatch.add(revokedCertificate);
            added++;
            if (added == BATCH_SIZE) {
                /*
                 * Persist batch
                 */
                this.certificateAuthorityDAO.updateRevokedCertificates(revokedCertsBatch, crlNumber,
                        crl.getIssuerX500Principal(), revokedCertificatesMap);
                entries += revokedCertsBatch.size();
                revokedCertsBatch.clear();
                added = 0;
            }
        }
        /*
         * Persist final batch
         */
        this.certificateAuthorityDAO.updateRevokedCertificates(revokedCertsBatch, crlNumber,
                crl.getIssuerX500Principal(), revokedCertificatesMap);
        entries += revokedCertsBatch.size();

        /*
         * Cleanup redundant CRL entries
         */
        if (null != crlNumber) {
            this.certificateAuthorityDAO.removeOldRevokedCertificates(crlNumber,
                    crl.getIssuerX500Principal().toString());
        }
    }

    deleteCrlFile(crlFile);

    LOG.debug("CRL this update: " + crl.getThisUpdate());
    LOG.debug("CRL next update: " + crl.getNextUpdate());
    certificateAuthority.setStatus(Status.ACTIVE);
    certificateAuthority.setThisUpdate(crl.getThisUpdate());
    certificateAuthority.setNextUpdate(crl.getNextUpdate());
    LOG.debug("cache activated for CA: " + crl.getIssuerX500Principal() + " (entries=" + entries + ")");
}

From source file:be.fedict.trust.test.PKITestUtils.java

License:Open Source License

public static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn,
        DateTime notBefore, DateTime notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey,
        boolean caFlag, int pathLength, String crlUri, String ocspUri, KeyUsage keyUsage,
        String signatureAlgorithm, boolean tsa, boolean includeSKID, boolean includeAKID,
        PublicKey akidPublicKey, String certificatePolicy, Boolean qcCompliance, boolean ocspResponder,
        boolean qcSSCD) throws IOException, InvalidKeyException, IllegalStateException,
        NoSuchAlgorithmException, SignatureException, CertificateException, OperatorCreationException {

    X500Name issuerName;/*from  ww w.  jav a2 s .c  om*/
    if (null != issuerCertificate) {
        issuerName = new X500Name(issuerCertificate.getSubjectX500Principal().toString());
    } else {
        issuerName = new X500Name(subjectDn);
    }
    X500Name subjectName = new X500Name(subjectDn);
    BigInteger serial = new BigInteger(128, new SecureRandom());
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded());
    X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuerName, serial,
            notBefore.toDate(), notAfter.toDate(), subjectName, publicKeyInfo);

    JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
    if (includeSKID) {
        x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false,
                extensionUtils.createSubjectKeyIdentifier(subjectPublicKey));
    }

    if (includeAKID) {

        PublicKey authorityPublicKey;
        if (null != akidPublicKey) {
            authorityPublicKey = akidPublicKey;
        } else if (null != issuerCertificate) {
            authorityPublicKey = issuerCertificate.getPublicKey();
        } else {
            authorityPublicKey = subjectPublicKey;
        }
        x509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false,
                extensionUtils.createAuthorityKeyIdentifier(authorityPublicKey));
    }

    if (caFlag) {
        if (-1 == pathLength) {
            x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true,
                    new BasicConstraints(2147483647));
        } else {
            x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true,
                    new BasicConstraints(pathLength));
        }
    }

    if (null != crlUri) {
        GeneralName generalName = new GeneralName(GeneralName.uniformResourceIdentifier,
                new DERIA5String(crlUri));
        GeneralNames generalNames = new GeneralNames(generalName);
        DistributionPointName distPointName = new DistributionPointName(generalNames);
        DistributionPoint distPoint = new DistributionPoint(distPointName, null, null);
        DistributionPoint[] crlDistPoints = new DistributionPoint[] { distPoint };
        CRLDistPoint crlDistPoint = new CRLDistPoint(crlDistPoints);
        x509v3CertificateBuilder.addExtension(Extension.cRLDistributionPoints, false, crlDistPoint);
    }

    if (null != ocspUri) {
        GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, ocspUri);
        AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
                X509ObjectIdentifiers.ocspAccessMethod, ocspName);
        x509v3CertificateBuilder.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    }

    if (null != keyUsage) {
        x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, keyUsage);
    }

    if (null != certificatePolicy) {
        ASN1ObjectIdentifier policyObjectIdentifier = new ASN1ObjectIdentifier(certificatePolicy);
        PolicyInformation policyInformation = new PolicyInformation(policyObjectIdentifier);
        x509v3CertificateBuilder.addExtension(Extension.certificatePolicies, false,
                new DERSequence(policyInformation));
    }

    if (null != qcCompliance) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        if (qcCompliance) {
            vec.add(new QCStatement(QCStatement.id_etsi_qcs_QcCompliance));
        } else {
            vec.add(new QCStatement(QCStatement.id_etsi_qcs_RetentionPeriod));
        }
        if (qcSSCD) {
            vec.add(new QCStatement(QCStatement.id_etsi_qcs_QcSSCD));
        }
        x509v3CertificateBuilder.addExtension(Extension.qCStatements, true, new DERSequence(vec));

    }

    if (tsa) {
        x509v3CertificateBuilder.addExtension(Extension.extendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping));
    }

    if (ocspResponder) {
        x509v3CertificateBuilder.addExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck, false,
                DERNull.INSTANCE);

        x509v3CertificateBuilder.addExtension(Extension.extendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_OCSPSigning));
    }

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(signatureAlgorithm);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter asymmetricKeyParameter = PrivateKeyFactory.createKey(issuerPrivateKey.getEncoded());

    ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
            .build(asymmetricKeyParameter);
    X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);

    byte[] encodedCertificate = x509CertificateHolder.getEncoded();

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(encodedCertificate));
    return certificate;
}

From source file:be.fedict.trust.test.PKITestUtils.java

License:Open Source License

public static X509CRL generateCrl(PrivateKey issuerPrivateKey, X509Certificate issuerCertificate,
        DateTime thisUpdate, DateTime nextUpdate, List<String> deltaCrlUris, boolean deltaCrl,
        List<RevokedCertificate> revokedCertificates, String signatureAlgorithm,
        long numberOfRevokedCertificates)
        throws InvalidKeyException, CRLException, IllegalStateException, NoSuchAlgorithmException,
        SignatureException, CertificateException, IOException, OperatorCreationException {

    X500Name issuerName = new X500Name(issuerCertificate.getSubjectX500Principal().toString());
    X509v2CRLBuilder x509v2crlBuilder = new X509v2CRLBuilder(issuerName, thisUpdate.toDate());
    x509v2crlBuilder.setNextUpdate(nextUpdate.toDate());

    for (RevokedCertificate revokedCertificate : revokedCertificates) {
        x509v2crlBuilder.addCRLEntry(revokedCertificate.serialNumber,
                revokedCertificate.revocationDate.toDate(), CRLReason.privilegeWithdrawn);
    }//from w w w.j  av a 2  s.c o  m
    if (-1 != numberOfRevokedCertificates) {
        SecureRandom secureRandom = new SecureRandom();
        while (numberOfRevokedCertificates-- > 0) {
            BigInteger serialNumber = new BigInteger(128, secureRandom);
            Date revocationDate = new Date();
            x509v2crlBuilder.addCRLEntry(serialNumber, revocationDate, CRLReason.privilegeWithdrawn);
        }
    }

    JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
    x509v2crlBuilder.addExtension(Extension.authorityKeyIdentifier, false,
            extensionUtils.createAuthorityKeyIdentifier(issuerCertificate));
    x509v2crlBuilder.addExtension(Extension.cRLNumber, false, new CRLNumber(BigInteger.ONE));

    if (null != deltaCrlUris && !deltaCrlUris.isEmpty()) {
        DistributionPoint[] deltaCrlDps = new DistributionPoint[deltaCrlUris.size()];
        for (int i = 0; i < deltaCrlUris.size(); i++) {
            deltaCrlDps[i] = getDistributionPoint(deltaCrlUris.get(i));
        }
        CRLDistPoint crlDistPoint = new CRLDistPoint((DistributionPoint[]) deltaCrlDps);
        x509v2crlBuilder.addExtension(Extension.freshestCRL, false, crlDistPoint);
    }

    if (deltaCrl) {
        x509v2crlBuilder.addExtension(Extension.deltaCRLIndicator, true, new CRLNumber(BigInteger.ONE));
    }

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(signatureAlgorithm);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter asymmetricKeyParameter = PrivateKeyFactory.createKey(issuerPrivateKey.getEncoded());

    ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
            .build(asymmetricKeyParameter);

    X509CRLHolder x509crlHolder = x509v2crlBuilder.build(contentSigner);
    byte[] crlValue = x509crlHolder.getEncoded();
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509CRL crl = (X509CRL) certificateFactory.generateCRL(new ByteArrayInputStream(crlValue));
    return crl;
}

From source file:beta01.SimpleRootCA.java

/**
 * Build a sample V1 certificate to use as a CA root certificate
 * @param keyPair/* w w  w .j av a  2s  .  c  o  m*/
 */
public static X509CertificateHolder buildRootCert(org.bouncycastle.crypto.AsymmetricCipherKeyPair keyPair)
        throws Exception {
    X509v1CertificateBuilder certBldr = new X509v1CertificateBuilder(new X500Name("CN=Test Root Certificate"),
            BigInteger.valueOf(1), new Date(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() + VALIDITY_PERIOD), new X500Name("CN=Test Root Certificate"),
            SubjectPublicKeyInfoFactory
                    .createSubjectPublicKeyInfo((AsymmetricKeyParameter) keyPair.getPublic()));

    AlgorithmIdentifier sigAlg = algFinder.find("SHA1withRSA");
    AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg);

    ContentSigner signer = new BcRSAContentSignerBuilder(sigAlg, digAlg)
            .build((AsymmetricKeyParameter) keyPair.getPrivate());

    return certBldr.build(signer);
}

From source file:beta01.SimpleRootCA.java

/**
 * Build a sample V3 certificate to use as an intermediate CA certificate
 * @param intKey//from  w w w  .  j a v a2s  . co  m
 * @param caKey
 * @param caCert
 * @return 
 * @throws java.lang.Exception 
 */
public static X509CertificateHolder buildIntermediateCert(AsymmetricKeyParameter intKey,
        AsymmetricKeyParameter caKey, X509CertificateHolder caCert) throws Exception {
    SubjectPublicKeyInfo intKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(intKey);

    X509v3CertificateBuilder certBldr = new X509v3CertificateBuilder(caCert.getSubject(), BigInteger.valueOf(1),
            new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + VALIDITY_PERIOD),
            new X500Name("CN=Test CA Certificate"), intKeyInfo);

    X509ExtensionUtils extUtils = new X509ExtensionUtils(new SHA1DigestCalculator());

    certBldr.addExtension(Extension.authorityKeyIdentifier, false,
            extUtils.createAuthorityKeyIdentifier(caCert))
            .addExtension(Extension.subjectKeyIdentifier, false,
                    extUtils.createSubjectKeyIdentifier(intKeyInfo))
            .addExtension(Extension.basicConstraints, true, new BasicConstraints(0))
            .addExtension(Extension.keyUsage, true,
                    new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));

    AlgorithmIdentifier sigAlg = algFinder.find("SHA1withRSA");
    AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg);

    ContentSigner signer = new BcRSAContentSignerBuilder(sigAlg, digAlg).build(caKey);

    return certBldr.build(signer);
}

From source file:beta01.SimpleRootCA.java

/**
 * Build a sample V3 certificate to use as an end entity certificate
 *//*from  w  w w  .  java2s .c  o  m*/
public static X509CertificateHolder buildEndEntityCert(AsymmetricKeyParameter entityKey,
        AsymmetricKeyParameter caKey, X509CertificateHolder caCert) throws Exception {
    SubjectPublicKeyInfo entityKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(entityKey);

    X509v3CertificateBuilder certBldr = new X509v3CertificateBuilder(caCert.getSubject(), BigInteger.valueOf(1),
            new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + VALIDITY_PERIOD),
            new X500Name("CN=Test End Entity Certificate"), entityKeyInfo);

    X509ExtensionUtils extUtils = new X509ExtensionUtils(new SHA1DigestCalculator());

    certBldr.addExtension(Extension.authorityKeyIdentifier, false,
            extUtils.createAuthorityKeyIdentifier(caCert))
            .addExtension(Extension.subjectKeyIdentifier, false,
                    extUtils.createSubjectKeyIdentifier(entityKeyInfo))
            .addExtension(Extension.basicConstraints, true, new BasicConstraints(false))
            .addExtension(Extension.keyUsage, true,
                    new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    AlgorithmIdentifier sigAlg = algFinder.find("SHA1withRSA");
    AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg);

    ContentSigner signer = new BcRSAContentSignerBuilder(sigAlg, digAlg).build(caKey);

    return certBldr.build(signer);
}

From source file:br.ufpb.dicomflow.integrationAPI.mail.AbstractMailSender.java

License:Open Source License

private Message signAndEcrypt(Message message, X509Certificate signCert, X509Certificate encryptCert,
        PrivateKey privateKey) throws Exception {
    MailcapCommandMap mailcap = (MailcapCommandMap) CommandMap.getDefaultCommandMap();

    mailcap.addMailcap(/*from  ww w. j a va  2s  .c o  m*/
            "application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature");
    mailcap.addMailcap(
            "application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime");
    mailcap.addMailcap(
            "application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature");
    mailcap.addMailcap(
            "application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime");
    mailcap.addMailcap(
            "multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed");

    CommandMap.setDefaultCommandMap(mailcap);

    /* Create the Signer - SMIMESignedGenerator */
    SMIMECapabilityVector capabilities = new SMIMECapabilityVector();
    capabilities.addCapability(SMIMECapability.dES_EDE3_CBC);
    capabilities.addCapability(SMIMECapability.rC2_CBC, 128);
    capabilities.addCapability(SMIMECapability.dES_CBC);

    ASN1EncodableVector attributes = new ASN1EncodableVector();
    attributes.add(new SMIMEEncryptionKeyPreferenceAttribute(
            new IssuerAndSerialNumber(new X500Name(((X509Certificate) signCert).getIssuerDN().getName()),
                    ((X509Certificate) signCert).getSerialNumber())));
    attributes.add(new SMIMECapabilitiesAttribute(capabilities));

    SMIMESignedGenerator signer = new SMIMESignedGenerator();
    signer.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder()
            .setSignedAttributeGenerator(new AttributeTable(attributes))
            .build("DSA".equals(privateKey.getAlgorithm()) ? "SHA1withDSA" : "MD5withRSA", privateKey,
                    signCert));

    /* Add the list of certs to the generator */
    List certList = new ArrayList();
    certList.add(signCert);
    Store certs = new JcaCertStore(certList);
    signer.addCertificates(certs);

    /* Sign the message */
    MimeMultipart mm = signer.generate((MimeMessage) message);
    MimeMessage signedMessage = new MimeMessage(message.getSession());

    /* Set all original MIME headers in the signed message */
    Enumeration headers = ((MimeMessage) message).getAllHeaderLines();
    while (headers.hasMoreElements()) {
        signedMessage.addHeaderLine((String) headers.nextElement());
    }

    /* Set the content of the signed message */
    signedMessage.setContent(mm);
    signedMessage.saveChanges();

    /* Create the encrypter - SMIMEEnvelopedGenerator */
    SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator();
    encrypter.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(encryptCert));

    /* Encrypt the message */
    MimeBodyPart encryptedPart = encrypter.generate(signedMessage,
            new JceCMSContentEncryptorBuilder(CMSAlgorithm.RC2_CBC).build());

    /*
     * Create a new MimeMessage that contains the encrypted and signed
     * content
     */
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    encryptedPart.writeTo(out);

    MimeMessage encryptedMessage = new MimeMessage(message.getSession(),
            new ByteArrayInputStream(out.toByteArray()));

    /* Set all original MIME headers in the encrypted message */
    headers = ((MimeMessage) message).getAllHeaderLines();
    while (headers.hasMoreElements()) {
        String headerLine = (String) headers.nextElement();
        /*
         * Make sure not to override any content-* headers from the
         * original message
         */
        if (!Strings.toLowerCase(headerLine).startsWith("content-")) {
            encryptedMessage.addHeaderLine(headerLine);
        }
    }

    return encryptedMessage;

}