org.bouncycastle.asn1.x500.style.RFC4519Style Java Examples

The following examples show how to use org.bouncycastle.asn1.x500.style.RFC4519Style. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TlsResourceBuilder.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
private static X509Certificate createSelfSignedCertificate(final KeyPair keyPair,
                                                           final String dn,
                                                           final ValidityPeriod period,
                                                           final AlternativeName... alternativeName)
        throws CertificateException
{
    try
    {
        final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
                new X500Name(RFC4519Style.INSTANCE, dn),
                generateSerialNumber(),
                new Date(period.getFrom().toEpochMilli()),
                new Date(period.getTo().toEpochMilli()),
                new X500Name(RFC4519Style.INSTANCE, dn),
                keyPair.getPublic());
        builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
        builder.addExtension(createKeyUsageExtension());
        builder.addExtension(createSubjectKeyExtension(keyPair.getPublic()));
        builder.addExtension(createAlternateNamesExtension(alternativeName));
        return buildX509Certificate(builder, keyPair.getPrivate());
    }
    catch (OperatorException | IOException e)
    {
        throw new CertificateException(e);
    }
}
 
Example #2
Source File: TlsResourceBuilder.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
private static X509Certificate createRootCACertificate(final KeyPair keyPair,
                                                       final String dn,
                                                       final ValidityPeriod validityPeriod)
        throws CertificateException
{
    try
    {
        final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
                new X500Name(RFC4519Style.INSTANCE, dn),
                generateSerialNumber(),
                new Date(validityPeriod.getFrom().toEpochMilli()),
                new Date(validityPeriod.getTo().toEpochMilli()),
                new X500Name(RFC4519Style.INSTANCE, dn),
                keyPair.getPublic());

        builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
        builder.addExtension(createSubjectKeyExtension(keyPair.getPublic()));
        builder.addExtension(createAuthorityKeyExtension(keyPair.getPublic()));
        return buildX509Certificate(builder, keyPair.getPrivate());
    }
    catch (OperatorException | IOException e)
    {
        throw new CertificateException(e);
    }
}
 
Example #3
Source File: HttpBaseTest.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
private X509Certificate generateCert(String keyName, KeyPair kp, boolean isCertAuthority,
                                     PublicKey signerPublicKey, PrivateKey signerPrivateKey)
    throws IOException, OperatorCreationException, CertificateException,
    NoSuchAlgorithmException {
  Calendar startDate = DateTimeUtils.calendar();
  Calendar endDate = DateTimeUtils.calendar();
  endDate.add(Calendar.YEAR, 100);

  BigInteger serialNumber = BigInteger.valueOf(startDate.getTimeInMillis());
  X500Name issuer = new X500Name(
      IETFUtils.rDNsFromString("cn=localhost", RFC4519Style.INSTANCE));
  JcaX509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(issuer,
      serialNumber, startDate.getTime(), endDate.getTime(), issuer, kp.getPublic());
  JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
  certGen.addExtension(Extension.subjectKeyIdentifier, false,
      extensionUtils.createSubjectKeyIdentifier(kp.getPublic()));
  certGen.addExtension(Extension.basicConstraints, false,
      new BasicConstraints(isCertAuthority));
  certGen.addExtension(Extension.authorityKeyIdentifier, false,
      extensionUtils.createAuthorityKeyIdentifier(signerPublicKey));
  if (isCertAuthority) {
    certGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign));
  }
  X509CertificateHolder certificateHolder = certGen.build(
      new JcaContentSignerBuilder(SIGNING_ALGORITHM).build(signerPrivateKey));
  return new JcaX509CertificateConverter().getCertificate(certificateHolder);
}
 
Example #4
Source File: TlsResourceBuilder.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private static X509Certificate generateIntermediateCertificate(final KeyPair keyPair,
                                                               final KeyCertificatePair rootCA,
                                                               final String dn,
                                                               final ValidityPeriod validityPeriod,
                                                               final String crlUri)
        throws CertificateException
{
    try
    {
        final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
                rootCA.getCertificate(),
                generateSerialNumber(),
                new Date(validityPeriod.getFrom().toEpochMilli()),
                new Date(validityPeriod.getTo().toEpochMilli()),
                new X500Name(RFC4519Style.INSTANCE, dn),
                keyPair.getPublic());
        //builder.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign));
        builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
        builder.addExtension(createSubjectKeyExtension(keyPair.getPublic()));
        builder.addExtension(createAuthorityKeyExtension(rootCA.getCertificate().getPublicKey()));
        if (crlUri != null)
        {
            builder.addExtension(createDistributionPointExtension(crlUri));
        }

        return buildX509Certificate(builder, rootCA.getPrivateKey());
    }
    catch (OperatorException | IOException e)
    {
        throw new CertificateException(e);
    }
}
 
Example #5
Source File: CertificateGeneratorTest.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
private static JcaX509v3CertificateBuilder createRootCert(KeyPair keypair) throws Exception {
    X500NameBuilder ib = new X500NameBuilder(RFC4519Style.INSTANCE);
    ib.addRDN(RFC4519Style.c, "AQ");
    ib.addRDN(RFC4519Style.o, "Test");
    ib.addRDN(RFC4519Style.l, "Vostok Station");
    ib.addRDN(PKCSObjectIdentifiers.pkcs_9_at_emailAddress, "[email protected]");
    X500Name issuer = ib.build();
    return createCert(keypair, issuer, issuer);
}
 
Example #6
Source File: KafkaTestUtils.java    From ranger with Apache License 2.0 5 votes vote down vote up
public static String createAndStoreKey(String subjectName, String issuerName, BigInteger serial, String keystorePassword,
		String keystoreAlias, String keyPassword, KeyStore trustStore) throws Exception {
	
	// Create KeyPair
	KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
	keyPairGenerator.initialize(2048, new SecureRandom());
	KeyPair keyPair = keyPairGenerator.generateKeyPair();
	
	Date currentDate = new Date();
	Date expiryDate = new Date(currentDate.getTime() + 365L * 24L * 60L * 60L * 1000L);
	
	// Create X509Certificate
	X509v3CertificateBuilder certBuilder =
			new X509v3CertificateBuilder(new X500Name(RFC4519Style.INSTANCE, issuerName), serial, currentDate, expiryDate, 
					new X500Name(RFC4519Style.INSTANCE, subjectName), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));
	ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());
	X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(certBuilder.build(contentSigner));
	
	// Store Private Key + Certificate in Keystore
	KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
	keystore.load(null, keystorePassword.toCharArray());
	keystore.setKeyEntry(keystoreAlias, keyPair.getPrivate(), keyPassword.toCharArray(), new Certificate[] {certificate});
	
	File keystoreFile = File.createTempFile("kafkakeystore", ".jks");
	try (OutputStream output = new FileOutputStream(keystoreFile)) {
		keystore.store(output, keystorePassword.toCharArray());
	}
	
	// Now store the Certificate in the truststore
	trustStore.setCertificateEntry(keystoreAlias, certificate);
	
	return keystoreFile.getPath();
	
}
 
Example #7
Source File: X509Cert.java    From xipki with Apache License 2.0 5 votes vote down vote up
public String getSubjectRfc4519Text() {
  if (subjectRfc4519Text == null) {
    synchronized (sync) {
      subjectRfc4519Text = RFC4519Style.INSTANCE.toString(subject);
    }
  }

  return subjectRfc4519Text;
}
 
Example #8
Source File: X509Cert.java    From xipki with Apache License 2.0 5 votes vote down vote up
public String getIssuerRfc4519Text() {
  if (issuerRfc4519Text == null) {
    synchronized (sync) {
      issuerRfc4519Text = RFC4519Style.INSTANCE.toString(subject);
    }
  }

  return issuerRfc4519Text;
}
 
Example #9
Source File: ObjectIdentifiers.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static String getName(ASN1ObjectIdentifier type) {
  Args.notNull(type, "type");
  String name = OidNameMap.oidNameMap.get(type);

  if (StringUtil.isBlank(name)) {
    try {
      name = RFC4519Style.INSTANCE.oidToDisplayName(type);
    } catch (IllegalArgumentException ex) { // CHECKSTYLE:SKIP
    }
  }
  return name;
}
 
Example #10
Source File: ObjectIdentifiers.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static ASN1ObjectIdentifier nameToOid(String name) {
  Args.notNull(name, "name");
  for (ASN1ObjectIdentifier oid : OidNameMap.oidNameMap.keySet()) {
    if (OidNameMap.oidNameMap.get(oid).equalsIgnoreCase(name)) {
      return oid;
    }
  }

  try {
    return RFC4519Style.INSTANCE.attrNameToOID(name);
  } catch (IllegalArgumentException ex) {
    return null;
  }
}
 
Example #11
Source File: DeviceCertificateManager.java    From enmasse with Apache License 2.0 4 votes vote down vote up
public Device createDevice(final String deviceName, final Instant notBefore, final Instant notAfter, final Consumer<X509v3CertificateBuilder> customizer) throws Exception {

        // create the fill device name

        final X500NameBuilder builder = new X500NameBuilder(RFC4519Style.INSTANCE);
        Arrays
                .asList(new X500Name(this.baseName.getName()).getRDNs())
                .forEach(e -> builder.addMultiValuedRDN(e.getTypesAndValues()));
        builder.addRDN(RFC4519Style.cn, deviceName);
        final X500Principal name = new X500Principal(builder.build().toString());

        // create a new key pair for the device

        final KeyPair deviceKey = this.keyPairGenerator.generateKeyPair();

        // sign certificate with CA key

        final ContentSigner contentSigner = new JcaContentSignerBuilder(mode.getSignatureAlgorithm())
                .build(this.keyPair.getPrivate());

        // create certificate

        final X509v3CertificateBuilder deviceCertificateBuilder = new JcaX509v3CertificateBuilder(
                this.baseName,
                BigInteger.valueOf(this.serialNumber.getAndIncrement()),
                Date.from(notBefore),
                Date.from(notAfter),
                name,
                deviceKey.getPublic())
                        .addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyId(deviceKey.getPublic()))
                        .addExtension(Extension.authorityKeyIdentifier, false, createAuthorityKeyId(this.keyPair.getPublic()));

        // customize

        if (customizer != null) {
            customizer.accept(deviceCertificateBuilder);
        }

        // convert to JCA certificate

        final X509Certificate deviceCertificate = new JcaX509CertificateConverter()
                .setProvider(new BouncyCastleProvider())
                .getCertificate(deviceCertificateBuilder.build(contentSigner));

        // return result

        return new Device(deviceKey, deviceCertificate);

    }
 
Example #12
Source File: SignerSpecificTest.java    From xades4j with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void signWithNationalCertificate() throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
    keyGen.initialize(1024, new SecureRandom());
    Date validityBeginDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
    long add = (1L * 365L * 24L * 60L * 60L * 1000L);  //1 year
    Date validityEndDate = new Date(System.currentTimeMillis() + add);
    KeyPair keyPair = keyGen.generateKeyPair();


    X509Certificate certWithNationalSymbols;
    {
        //generate certificate with national symbols in DN
        X500NameBuilder x500NameBuilder = new X500NameBuilder();
        AttributeTypeAndValue attr = new AttributeTypeAndValue(RFC4519Style.cn, commonName);
        x500NameBuilder.addRDN(attr);
        X500Name dn = x500NameBuilder.build();
        X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
                dn, // issuer authority
                BigInteger.valueOf(new Random().nextInt()), //serial number of certificate
                validityBeginDate, // start of validity
                validityEndDate, //end of certificate validity
                dn, // subject name of certificate
                keyPair.getPublic()); // public key of certificate
        // key usage restrictions
        builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign
                | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
                | KeyUsage.dataEncipherment | KeyUsage.cRLSign));
        builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
        certWithNationalSymbols = new JcaX509CertificateConverter().getCertificate(builder
                .build(new JcaContentSignerBuilder("SHA256withRSA").setProvider(BouncyCastleProvider.PROVIDER_NAME).
                        build(keyPair.getPrivate())));
    }


    XadesSigner signer = new XadesBesSigningProfile(new DirectKeyingDataProvider(certWithNationalSymbols, keyPair.getPrivate())).newSigner();
    Document doc1 = getTestDocument();
    Element elemToSign = doc1.getDocumentElement();
    DataObjectDesc obj1 = new DataObjectReference('#' + elemToSign.getAttribute("Id")).withTransform(new EnvelopedSignatureTransform());
    SignedDataObjects signDataObject = new SignedDataObjects(obj1);
    signer.sign(signDataObject, doc1.getDocumentElement());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    outputDOM(doc1, baos);
    String str = new String(baos.toByteArray());
    //expected without parsing exception
    Document doc = parseDocument(new ByteArrayInputStream(baos.toByteArray()));

}
 
Example #13
Source File: SAML2ITCase.java    From syncope with Apache License 2.0 4 votes vote down vote up
private static void createKeystores() throws Exception {
    // Create KeyPair
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024, new SecureRandom());
    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    Date currentDate = new Date();
    Date expiryDate = new Date(currentDate.getTime() + 365L * 24L * 60L * 60L * 1000L);

    // Create X509Certificate
    String issuerName = "CN=Issuer";
    String subjectName = "CN=Subject";
    BigInteger serial = new BigInteger("123456");
    X509v3CertificateBuilder certBuilder =
            new X509v3CertificateBuilder(new X500Name(RFC4519Style.INSTANCE, issuerName), serial, currentDate,
                    expiryDate,
                    new X500Name(RFC4519Style.INSTANCE, subjectName),
                    SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));
    ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());
    X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(certBuilder.build(contentSigner));

    // Store Private Key + Certificate in Keystore
    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(null, "security".toCharArray());
    keystore.setKeyEntry("subject", keyPair.getPrivate(), "security".toCharArray(),
            new Certificate[] { certificate });

    File keystoreFile = File.createTempFile("samlkeystore", ".jks");
    try (OutputStream output = Files.newOutputStream(keystoreFile.toPath())) {
        keystore.store(output, "security".toCharArray());
    }
    keystorePath = keystoreFile.toPath();

    // Now store the Certificate in the truststore
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null, "security".toCharArray());

    trustStore.setCertificateEntry("subject", certificate);

    File truststoreFile = File.createTempFile("samltruststore", ".jks");
    try (OutputStream output = Files.newOutputStream(truststoreFile.toPath())) {
        trustStore.store(output, "security".toCharArray());
    }
    truststorePath = truststoreFile.toPath();
}
 
Example #14
Source File: X509Util.java    From xipki with Apache License 2.0 4 votes vote down vote up
public static String getRfc4519Name(X500Name name) {
  Args.notNull(name, "name");
  return RFC4519Style.INSTANCE.toString(name);
}