Example usage for org.bouncycastle.jcajce.provider.asymmetric.x509 CertificateFactory CertificateFactory

List of usage examples for org.bouncycastle.jcajce.provider.asymmetric.x509 CertificateFactory CertificateFactory

Introduction

In this page you can find the example usage for org.bouncycastle.jcajce.provider.asymmetric.x509 CertificateFactory CertificateFactory.

Prototype

CertificateFactory

Source Link

Usage

From source file:org.codice.ddf.security.certificate.generator.PkiTools.java

License:Open Source License

/**
 * Given a PEM encoded X509 certificate, return an object representation of the certificate
 *
 * @param certString PEM encoded X509 certificate
 * @return instance of X509 certificate//from  ww w. j a  va 2s .  co m
 */
public static X509Certificate pemToCertificate(String certString) {
    CertificateFactory cf = new CertificateFactory();
    ByteArrayInputStream in = new ByteArrayInputStream(PkiTools.pemToDer(certString));
    X509Certificate cert;
    try {
        cert = (X509Certificate) cf.engineGenerateCertificate(in);
    } catch (CertificateException e) {
        throw new CertificateGeneratorException("Cannot convert this PEM object to X509 certificate", e);
    }
    if (cert == null) {
        throw new CertificateGeneratorException("Cannot convert this PEM object to X509 certificate");
    }
    return cert;
}

From source file:org.xipki.ca.server.impl.X509CA.java

License:Open Source License

public X509CA(final CAManagerImpl caManager, final X509CAInfo caInfo, final CertificateStore certstore,
        final SecurityFactory securityFactory, final boolean masterMode) throws OperationException {
    ParamChecker.assertNotNull("caManager", caManager);
    ParamChecker.assertNotNull("caInfo", caInfo);
    ParamChecker.assertNotNull("certstore", certstore);

    this.caManager = caManager;
    this.caInfo = caInfo;
    this.certstore = certstore;
    this.masterMode = masterMode;

    if (caInfo.isSignerRequired()) {
        try {/*from   w  ww  . ja v a 2s.co  m*/
            caInfo.initSigner(securityFactory);
        } catch (SignerException e) {
            final String message = "security.createSigner caSigner (ca=" + caInfo.getName() + ")";
            if (LOG.isErrorEnabled()) {
                LOG.error(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage());
            }
            LOG.debug(message, e);

            throw new OperationException(ErrorCode.SYSTEM_FAILURE, "SigenrException: " + e.getMessage());
        }
    }

    X509CertWithDBCertId caCert = caInfo.getCertificate();

    X509CrlSignerEntryWrapper crlSigner = getCrlSigner();
    if (crlSigner != null) {
        // CA signs the CRL
        if (caManager.getCrlSignerWrapper(caInfo.getCrlSignerName()) == null
                && X509Util.hasKeyusage(caInfo.getCertificate().getCert(), KeyUsage.cRLSign) == false) {
            final String msg = "CRL signer does not have keyusage cRLSign";
            LOG.error(msg);
            throw new OperationException(ErrorCode.SYSTEM_FAILURE, msg);
        }
    }

    this.cf = new CertificateFactory();

    if (caInfo.useRandomSerialNumber() == false) {
        nextSerialCommitService = caManager.getScheduledThreadPoolExecutor()
                .scheduleAtFixedRate(new ScheduledNextSerialCommitService(), 1, 1, TimeUnit.MINUTES); // commit the next_serial every 1 minute
    }

    if (masterMode == false) {
        return;
    }

    for (IdentifiedX509CertPublisher publisher : getPublishers()) {
        publisher.issuerAdded(caCert);
    }

    // CRL generation services
    crlGenerationService = caManager.getScheduledThreadPoolExecutor()
            .scheduleAtFixedRate(new ScheduledCRLGenerationService(), 1, 1, TimeUnit.MINUTES);

    expiredCertsRemover = caManager.getScheduledThreadPoolExecutor()
            .scheduleAtFixedRate(new ScheduledExpiredCertsRemover(), 10, 10, TimeUnit.MINUTES);
}

From source file:strat.mining.stratum.proxy.Launcher.java

License:Open Source License

/**
 * Check that a valid SSl certificate already exists. If not, create a new
 * one.//from  w  w w.j a  v  a  2  s .c  om
 * 
 * @throws Exception
 */
private static void checkCertificate() throws Exception {
    File storeFile = new File(ConfigurationManager.getInstance().getDatabaseDirectory(), KEYSTORE_FILE_NAME);
    KeyStore keyStore = KeyStore.getInstance("JKS");
    if (!storeFile.exists()) {
        LOGGER.info("KeyStore does not exist. Create {}", storeFile.getAbsolutePath());
        storeFile.getParentFile().mkdirs();
        storeFile.createNewFile();
        keyStore.load(null, null);

        LOGGER.info("Generating new SSL certificate.");
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

        RSAKeyPairGenerator keyGenerator = new RSAKeyPairGenerator();
        keyGenerator
                .init(new RSAKeyGenerationParameters(BigInteger.valueOf(101), new SecureRandom(), 2048, 14));
        AsymmetricCipherKeyPair keysPair = keyGenerator.generateKeyPair();

        RSAKeyParameters rsaPrivateKey = (RSAKeyParameters) keysPair.getPrivate();
        RSAPrivateKeySpec rsaPrivSpec = new RSAPrivateKeySpec(rsaPrivateKey.getModulus(),
                rsaPrivateKey.getExponent());
        RSAKeyParameters rsaPublicKey = (RSAKeyParameters) keysPair.getPublic();
        RSAPublicKeySpec rsaPublicSpec = new RSAPublicKeySpec(rsaPublicKey.getModulus(),
                rsaPublicKey.getExponent());
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey rsaPriv = kf.generatePrivate(rsaPrivSpec);
        PublicKey rsaPub = kf.generatePublic(rsaPublicSpec);

        X500Name issuerDN = new X500Name("CN=localhost, OU=None, O=None, L=None, C=None");
        Integer randomNumber = new SecureRandom().nextInt();
        BigInteger serialNumber = BigInteger.valueOf(randomNumber >= 0 ? randomNumber : randomNumber * -1);
        Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30);
        Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10));
        X500Name subjectDN = new X500Name("CN=localhost, OU=None, O=None, L=None, C=None");
        byte[] publickeyb = rsaPub.getEncoded();
        ASN1Sequence sequence = (ASN1Sequence) ASN1Primitive.fromByteArray(publickeyb);
        SubjectPublicKeyInfo subPubKeyInfo = new SubjectPublicKeyInfo(sequence);
        X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(issuerDN, serialNumber, notBefore,
                notAfter, subjectDN, subPubKeyInfo);

        ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
                .build(keysPair.getPrivate());
        X509CertificateHolder certificateHolder = v3CertGen.build(contentSigner);

        Certificate certificate = new CertificateFactory()
                .engineGenerateCertificate(new ByteBufferBackedInputStream(
                        ByteBuffer.wrap(certificateHolder.toASN1Structure().getEncoded())));

        LOGGER.info("Certificate generated.");

        keyStore.setKeyEntry(KEYSTORE_KEY_ENTRY_ALIAS, rsaPriv, KEYSTORE_PASSWORD.toCharArray(),
                new java.security.cert.Certificate[] { certificate });

        keyStore.store(new FileOutputStream(storeFile), KEYSTORE_PASSWORD.toCharArray());
    }
}