Search in sources :

Example 61 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project gitblit by gitblit.

the class X509Utils method newClientCertificate.

/**
 * Creates a new client certificate PKCS#12 and PEM store.  Any existing
 * stores are destroyed.
 *
 * @param clientMetadata a container for dynamic parameters needed for generation
 * @param caKeystoreFile
 * @param caKeystorePassword
 * @param targetFolder
 * @return
 */
public static X509Certificate newClientCertificate(X509Metadata clientMetadata, PrivateKey caPrivateKey, X509Certificate caCert, File targetFolder) {
    try {
        KeyPair pair = newKeyPair();
        X500Name userDN = buildDistinguishedName(clientMetadata);
        X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());
        // create a new certificate signed by the Gitblit CA certificate
        X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerDN, BigInteger.valueOf(System.currentTimeMillis()), clientMetadata.notBefore, clientMetadata.notAfter, userDN, pair.getPublic());
        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
        certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
        certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()));
        certBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature));
        if (!StringUtils.isEmpty(clientMetadata.emailAddress)) {
            GeneralNames subjectAltName = new GeneralNames(new GeneralName(GeneralName.rfc822Name, clientMetadata.emailAddress));
            certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
        }
        ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPrivateKey);
        X509Certificate userCert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certBuilder.build(signer));
        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) pair.getPrivate();
        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
        // confirm the validity of the user certificate
        userCert.checkValidity();
        userCert.verify(caCert.getPublicKey());
        userCert.getIssuerDN().equals(caCert.getSubjectDN());
        // verify user certificate chain
        verifyChain(userCert, caCert);
        targetFolder.mkdirs();
        // save certificate, stamped with unique name
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String id = date;
        File certFile = new File(targetFolder, id + ".cer");
        int count = 0;
        while (certFile.exists()) {
            id = date + "_" + Character.toString((char) (0x61 + count));
            certFile = new File(targetFolder, id + ".cer");
            count++;
        }
        // save user private key, user certificate and CA certificate to a PKCS#12 store
        File p12File = new File(targetFolder, clientMetadata.commonName + ".p12");
        if (p12File.exists()) {
            p12File.delete();
        }
        KeyStore userStore = openKeyStore(p12File, clientMetadata.password);
        userStore.setKeyEntry(MessageFormat.format("Gitblit ({0}) {1} {2}", clientMetadata.serverHostname, clientMetadata.userDisplayname, id), pair.getPrivate(), null, new Certificate[] { userCert });
        userStore.setCertificateEntry(MessageFormat.format("Gitblit ({0}) Certificate Authority", clientMetadata.serverHostname), caCert);
        saveKeyStore(p12File, userStore, clientMetadata.password);
        // save user private key, user certificate, and CA certificate to a PEM store
        File pemFile = new File(targetFolder, clientMetadata.commonName + ".pem");
        if (pemFile.exists()) {
            pemFile.delete();
        }
        JcePEMEncryptorBuilder builder = new JcePEMEncryptorBuilder("DES-EDE3-CBC");
        builder.setSecureRandom(new SecureRandom());
        PEMEncryptor pemEncryptor = builder.build(clientMetadata.password.toCharArray());
        JcaPEMWriter pemWriter = new JcaPEMWriter(new FileWriter(pemFile));
        pemWriter.writeObject(pair.getPrivate(), pemEncryptor);
        pemWriter.writeObject(userCert);
        pemWriter.writeObject(caCert);
        pemWriter.flush();
        pemWriter.close();
        // save certificate after successfully creating the key stores
        saveCertificate(userCert, certFile);
        // update serial number in metadata object
        clientMetadata.serialNumber = userCert.getSerialNumber().toString();
        return userCert;
    } catch (Throwable t) {
        throw new RuntimeException("Failed to generate client certificate!", t);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) FileWriter(java.io.FileWriter) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) PKCS12BagAttributeCarrier(org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier) PEMEncryptor(org.bouncycastle.openssl.PEMEncryptor) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) JcePEMEncryptorBuilder(org.bouncycastle.openssl.jcajce.JcePEMEncryptorBuilder) KeyPair(java.security.KeyPair) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) SimpleDateFormat(java.text.SimpleDateFormat) File(java.io.File)

Example 62 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project ozone by apache.

the class TestRootCertificate method testCACert.

@Test
public void testCACert() throws SCMSecurityException, NoSuchProviderException, NoSuchAlgorithmException, IOException, CertificateException {
    LocalDate notBefore = LocalDate.now();
    LocalDate notAfter = notBefore.plus(365, ChronoUnit.DAYS);
    String clusterID = UUID.randomUUID().toString();
    String scmID = UUID.randomUUID().toString();
    String subject = "testRootCert";
    HDDSKeyGenerator keyGen = new HDDSKeyGenerator(securityConfig.getConfiguration());
    KeyPair keyPair = keyGen.generateKey();
    SelfSignedCertificate.Builder builder = SelfSignedCertificate.newBuilder().setBeginDate(notBefore).setEndDate(notAfter).setClusterID(clusterID).setScmID(scmID).setSubject(subject).setKey(keyPair).setConfiguration(conf).makeCA();
    try {
        DomainValidator validator = DomainValidator.getInstance();
        // Add all valid ips.
        OzoneSecurityUtil.getValidInetsForCurrentHost().forEach(ip -> {
            builder.addIpAddress(ip.getHostAddress());
            if (validator.isValid(ip.getCanonicalHostName())) {
                builder.addDnsName(ip.getCanonicalHostName());
            }
        });
    } catch (IOException e) {
        throw new org.apache.hadoop.hdds.security.x509.exceptions.CertificateException("Error while adding ip to CA self signed certificate", e, CSR_ERROR);
    }
    X509CertificateHolder certificateHolder = builder.build();
    // This time we asked for a CertificateServer Certificate, make sure that
    // extension is
    // present and valid.
    Extension basicExt = certificateHolder.getExtension(Extension.basicConstraints);
    Assert.assertNotNull(basicExt);
    Assert.assertTrue(basicExt.isCritical());
    // Since this code assigns ONE for the root certificate, we check if the
    // serial number is the expected number.
    Assert.assertEquals(certificateHolder.getSerialNumber(), BigInteger.ONE);
    CertificateCodec codec = new CertificateCodec(securityConfig, "scm");
    String pemString = codec.getPEMEncodedString(certificateHolder);
    File basePath = temporaryFolder.newFolder();
    if (!basePath.exists()) {
        Assert.assertTrue(basePath.mkdirs());
    }
    codec.writeCertificate(basePath.toPath(), "pemcertificate.crt", pemString, false);
    X509CertificateHolder loadedCert = codec.readCertificate(basePath.toPath(), "pemcertificate.crt");
    assertNotNull(loadedCert);
    assertEquals(certificateHolder.getSerialNumber(), loadedCert.getSerialNumber());
}
Also used : KeyPair(java.security.KeyPair) HDDSKeyGenerator(org.apache.hadoop.hdds.security.x509.keys.HDDSKeyGenerator) SelfSignedCertificate(org.apache.hadoop.hdds.security.x509.certificates.utils.SelfSignedCertificate) CertificateCodec(org.apache.hadoop.hdds.security.x509.certificate.utils.CertificateCodec) IOException(java.io.IOException) LocalDate(java.time.LocalDate) Extension(org.bouncycastle.asn1.x509.Extension) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) DomainValidator(org.apache.commons.validator.routines.DomainValidator) File(java.io.File) Test(org.junit.Test)

Example 63 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project credhub by cloudfoundry.

the class CertificateGenerateTest method certificateGeneration_shouldGenerateCorrectCertificate.

@Test
public void certificateGeneration_shouldGenerateCorrectCertificate() throws Exception {
    final MockHttpServletRequestBuilder caPost = post("/api/v1/data").header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN).accept(APPLICATION_JSON).contentType(APPLICATION_JSON).content("{\n" + "  \"name\" : \"picard\",\n" + "  \"type\" : \"certificate\",\n" + "  \"parameters\" : {\n" + "    \"common_name\" : \"federation\",\n" + "    \"is_ca\" : true,\n" + "    \"self_sign\" : true,\n" + "    \"duration\" : 1 \n" + "  }\n" + "}");
    final String caResult = this.mockMvc.perform(caPost).andDo(print()).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
    JSONObject result = new JSONObject(caResult);
    final String picardCert = result.getJSONObject("value").getString("certificate");
    final String picardCA = result.getJSONObject("value").getString("ca");
    assertThat(picardCert, equalTo(picardCA));
    final String expiryDate = result.getString("expiry_date");
    final String truncatedExpiryDate = expiryDate.substring(0, expiryDate.indexOf('T'));
    final Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, 1);
    final String expectedTime = calendar.getTime().toInstant().truncatedTo(ChronoUnit.SECONDS).toString();
    final String truncatedExpected = expectedTime.substring(0, expectedTime.indexOf('T'));
    assertThat(truncatedExpiryDate, equalTo(truncatedExpected));
    assertThat(result.getBoolean("certificate_authority"), equalTo(true));
    assertThat(result.getBoolean("self_signed"), equalTo(true));
    assertThat(result.getBoolean("generated"), equalTo(true));
    assertThat(picardCert, notNullValue());
    final MockHttpServletRequestBuilder certPost = post("/api/v1/data").header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN).accept(APPLICATION_JSON).contentType(APPLICATION_JSON).content("{\n" + "  \"name\" : \"riker\",\n" + "  \"type\" : \"certificate\",\n" + "  \"parameters\" : {\n" + "    \"common_name\" : \"federation\",\n" + "    \"ca\" : \"picard\"\n" + "  }\n" + "}");
    final String certResult = this.mockMvc.perform(certPost).andDo(print()).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
    final String certCa = (new JSONObject(certResult)).getJSONObject("value").getString("ca");
    final String cert = (new JSONObject(certResult)).getJSONObject("value").getString("certificate");
    assertThat(certCa, equalTo(picardCert));
    final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    final X509Certificate caPem = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(picardCert.getBytes(UTF_8)));
    final X509Certificate certPem = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(cert.getBytes(UTF_8)));
    final byte[] subjectKeyIdDer = caPem.getExtensionValue(Extension.subjectKeyIdentifier.getId());
    final SubjectKeyIdentifier subjectKeyIdentifier = SubjectKeyIdentifier.getInstance(JcaX509ExtensionUtils.parseExtensionValue(subjectKeyIdDer));
    final byte[] subjectKeyId = subjectKeyIdentifier.getKeyIdentifier();
    final byte[] authorityKeyIdDer = certPem.getExtensionValue(Extension.authorityKeyIdentifier.getId());
    final AuthorityKeyIdentifier authorityKeyIdentifier = AuthorityKeyIdentifier.getInstance(JcaX509ExtensionUtils.parseExtensionValue(authorityKeyIdDer));
    final byte[] authKeyId = authorityKeyIdentifier.getKeyIdentifier();
    assertThat(subjectKeyId, equalTo(authKeyId));
}
Also used : JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) Calendar(java.util.Calendar) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) Test(org.junit.Test)

Example 64 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project apksig by venshine.

the class X509CertificateUtils method generateCertificates.

/**
 * Generates a {@code Collection} of {@code Certificate} objects from the encoded {@code
 * InputStream} using the provided {@code CertificateFactory}.
 *
 * @throws CertificateException if the InputStream cannot be decoded to zero or more valid
 *                              {@code Certificates} objects.
 */
public static Collection<? extends java.security.cert.Certificate> generateCertificates(InputStream in, CertificateFactory certFactory) throws CertificateException {
    // Since the InputStream is not guaranteed to support mark / reset operations first read it
    // into a byte array to allow using the BER parser / DER encoder if it cannot be read by
    // the CertificateFactory.
    byte[] encodedCerts;
    try {
        encodedCerts = ByteStreams.toByteArray(in);
    } catch (IOException e) {
        throw new CertificateException("Failed to read the input stream", e);
    }
    try {
        return certFactory.generateCertificates(new ByteArrayInputStream(encodedCerts));
    } catch (CertificateException e) {
    // This could be expected if the certificates are encoded using a BER encoding that does
    // not use the minimum number of bytes to represent the length of the contents; attempt
    // to decode the certificates using the BER parser and re-encode using the DER encoder
    // below.
    }
    try {
        Collection<X509Certificate> certificates = new ArrayList<>(1);
        ByteBuffer encodedCertsBuffer = ByteBuffer.wrap(encodedCerts);
        while (encodedCertsBuffer.hasRemaining()) {
            ByteBuffer certBuffer = getNextDEREncodedCertificateBlock(encodedCertsBuffer);
            int startingPos = certBuffer.position();
            Certificate reencodedCert = Asn1BerParser.parse(certBuffer, Certificate.class);
            byte[] reencodedForm = Asn1DerEncoder.encode(reencodedCert);
            X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(reencodedForm));
            byte[] originalEncoding = new byte[certBuffer.position() - startingPos];
            certBuffer.position(startingPos);
            certBuffer.get(originalEncoding);
            GuaranteedEncodedFormX509Certificate guaranteedEncodedCert = new GuaranteedEncodedFormX509Certificate(certificate, originalEncoding);
            certificates.add(guaranteedEncodedCert);
        }
        return certificates;
    } catch (Asn1DecodingException | Asn1EncodingException e) {
        throw new CertificateException("Failed to parse certificates", e);
    }
}
Also used : Asn1EncodingException(com.android.apksig.internal.asn1.Asn1EncodingException) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) X509Certificate(java.security.cert.X509Certificate) ByteArrayInputStream(java.io.ByteArrayInputStream) Asn1DecodingException(com.android.apksig.internal.asn1.Asn1DecodingException) X509Certificate(java.security.cert.X509Certificate) Certificate(com.android.apksig.internal.x509.Certificate)

Example 65 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project kafka by apache.

the class TestSslUtils method generateCertificate.

/**
     * Create a self-signed X.509 Certificate.
     * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
     *
     * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
     * @param pair the KeyPair
     * @param days how many days from now the Certificate is valid for
     * @param algorithm the signing algorithm, eg "SHA1withRSA"
     * @return the self-signed certificate
     * @throws CertificateException thrown if a security error or an IO error occurred.
     */
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm) throws CertificateException {
    try {
        Security.addProvider(new BouncyCastleProvider());
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
        ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
        X500Name name = new X500Name(dn);
        Date from = new Date();
        Date to = new Date(from.getTime() + days * 86400000L);
        BigInteger sn = new BigInteger(64, new SecureRandom());
        X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);
        X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
    } catch (CertificateException ce) {
        throw ce;
    } catch (Exception e) {
        throw new CertificateException(e);
    }
}
Also used : ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) EOFException(java.io.EOFException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) BcRSAContentSignerBuilder(org.bouncycastle.operator.bc.BcRSAContentSignerBuilder) AsymmetricKeyParameter(org.bouncycastle.crypto.params.AsymmetricKeyParameter) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) X509v1CertificateBuilder(org.bouncycastle.cert.X509v1CertificateBuilder) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Aggregations

IOException (java.io.IOException)242 X509Certificate (java.security.cert.X509Certificate)216 Date (java.util.Date)133 X500Name (org.bouncycastle.asn1.x500.X500Name)133 BigInteger (java.math.BigInteger)120 ContentSigner (org.bouncycastle.operator.ContentSigner)102 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)101 GeneralName (org.bouncycastle.asn1.x509.GeneralName)100 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)96 CertificateException (java.security.cert.CertificateException)95 ArrayList (java.util.ArrayList)90 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)85 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)82 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)78 GeneralSecurityException (java.security.GeneralSecurityException)69 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)62 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)62 Extension (org.bouncycastle.asn1.x509.Extension)61 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)60 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)59