org.bouncycastle.pkcs.PKCS10CertificationRequest Java Examples

The following examples show how to use org.bouncycastle.pkcs.PKCS10CertificationRequest. 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: CsrBuilderImpl.java    From java-certificate-authority with Apache License 2.0 7 votes vote down vote up
@Override
public CsrWithPrivateKey generateRequest(final DistinguishedName dn) {
  final KeyPair pair = KeysUtil.generateKeyPair();
  try {
    final PrivateKey privateKey = pair.getPrivate();
    final PublicKey publicKey = pair.getPublic();
    final X500Name x500Name = dn.getX500Name();
    final ContentSigner signGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM)
        .build(privateKey);
    final PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(
        x500Name, publicKey);
    final PKCS10CertificationRequest csr = builder.build(signGen);
    return new CsrWithPrivateKeyImpl(csr, privateKey);
  } catch (final OperatorCreationException e) {
    throw new CaException(e);
  }
}
 
Example #2
Source File: HddsDatanodeService.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Creates CSR for DN.
 * @param config
 * */
@VisibleForTesting
public PKCS10CertificationRequest getCSR(ConfigurationSource config)
    throws IOException {
  CertificateSignRequest.Builder builder = dnCertClient.getCSRBuilder();
  KeyPair keyPair = new KeyPair(dnCertClient.getPublicKey(),
      dnCertClient.getPrivateKey());

  String hostname = InetAddress.getLocalHost().getCanonicalHostName();
  String subject = UserGroupInformation.getCurrentUser()
      .getShortUserName() + "@" + hostname;

  builder.setCA(false)
      .setKey(keyPair)
      .setConfiguration(config)
      .setSubject(subject);

  LOG.info("Creating csr for DN-> subject:{}", subject);
  return builder.build();
}
 
Example #3
Source File: CreateCertificationTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void createCert() throws IOException {
    KeyPair keyPair = PkiUtil.generateKeypair();
    LOGGER.info("Key: \n{}", PkiUtil.convert(keyPair.getPrivate()));
    LOGGER.info("Pub: \n{}", PkiUtil.convert(keyPair.getPublic()));
    String domain = ".tb-local.xcu2-8y8x.workload-dev.cloudera.com";
    String commonName = "a7c2a45fc8f917fe";
    String endpointName = "really-really-long-named-cluster-tbihari2";
    List<String> subjectAlternativeNames = List.of(
            commonName + domain,
            endpointName + domain
    );
    PKCS10CertificationRequest csr = PkiUtil.csr(keyPair, commonName, subjectAlternativeNames);
    List<String> strings = certificateCreationService.create(actorCrn,
            accountId,
            commonName,
            "env-tb",
            csr);
    LOGGER.info("CERT: \n" + String.join("\n", strings));
}
 
Example #4
Source File: TestDefaultProfile.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that  invalid extensions cause a failure in validation. We will fail
 * if CA extension is enabled.
 *
 * @throws SCMSecurityException - on Error.
 */

@Test
public void testInvalidExtensionsWithCA() throws SCMSecurityException {
  PKCS10CertificationRequest csr = new CertificateSignRequest.Builder()
      .addDnsName("hadoop.apache.org")
      .addIpAddress("192.10.234.6")
      .setCA(true)
      .setClusterID("ClusterID")
      .setScmID("SCMID")
      .setSubject("Ozone Cluster")
      .setConfiguration(configuration)
      .setKey(keyPair)
      .build();
  assertFalse(testApprover.verfiyExtensions(csr));
}
 
Example #5
Source File: TestDefaultProfile.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Assert that if DNS is marked critical our PKI profile will reject it.
 * @throws IOException - on Error.
 * @throws OperatorCreationException - on Error.
 */
@Test
public void testInvalidExtensionsWithCriticalDNS() throws IOException,
    OperatorCreationException {
  Extensions dnsExtension = getSANExtension(GeneralName.dNSName,
      "ozone.hadoop.org",
      true);
  PKCS10CertificationRequest csr = getInvalidCSR(keyPair, dnsExtension);
  assertFalse(testApprover.verfiyExtensions(csr));
  // This tests should pass, hence the assertTrue
  dnsExtension = getSANExtension(GeneralName.dNSName,
      "ozone.hadoop.org",
      false);
  csr = getInvalidCSR(keyPair, dnsExtension);
  assertTrue(testApprover.verfiyExtensions(csr));
}
 
Example #6
Source File: SM2PfxMakerTest.java    From gmhelper with Apache License 2.0 6 votes vote down vote up
@Test
public void testMakePfx() {
    try {
        KeyPair subKP = SM2Util.generateKeyPair();
        X500Name subDN = SM2X509CertMakerTest.buildSubjectDN();
        SM2PublicKey sm2SubPub = new SM2PublicKey(subKP.getPublic().getAlgorithm(),
            (BCECPublicKey) subKP.getPublic());
        byte[] csr = CommonUtil.createCSR(subDN, sm2SubPub, subKP.getPrivate(),
            SM2X509CertMaker.SIGN_ALGO_SM3WITHSM2).getEncoded();
        SM2X509CertMaker certMaker = SM2X509CertMakerTest.buildCertMaker();
        X509Certificate cert = certMaker.makeSSLEndEntityCert(csr);

        SM2PfxMaker pfxMaker = new SM2PfxMaker();
        PKCS10CertificationRequest request = new PKCS10CertificationRequest(csr);
        PublicKey subPub = BCECUtil.createPublicKeyFromSubjectPublicKeyInfo(request.getSubjectPublicKeyInfo());
        PKCS12PfxPdu pfx = pfxMaker.makePfx(subKP.getPrivate(), subPub, cert, TEST_PFX_PASSWD);
        byte[] pfxDER = pfx.getEncoded(ASN1Encoding.DER);
        FileUtil.writeFile(TEST_PFX_FILENAME, pfxDER);
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail();
    }
}
 
Example #7
Source File: TestDefaultProfile.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Test valid keys are validated correctly.
 *
 * @throws SCMSecurityException      - on Error.
 * @throws PKCSException             - on Error.
 * @throws OperatorCreationException - on Error.
 */
@Test
public void testVerifyCertificate() throws SCMSecurityException,
    PKCSException, OperatorCreationException {
  PKCS10CertificationRequest csr = new CertificateSignRequest.Builder()
      .addDnsName("hadoop.apache.org")
      .addIpAddress("8.8.8.8")
      .addServiceName("OzoneMarketingCluster001")
      .setCA(false)
      .setClusterID("ClusterID")
      .setScmID("SCMID")
      .setSubject("Ozone Cluster")
      .setConfiguration(configuration)
      .setKey(keyPair)
      .build();
  assertTrue(testApprover.verifyPkcs10Request(csr));
}
 
Example #8
Source File: CryptoTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateX509CertificateReqPrivateKey() throws IOException {

    Path path = Paths.get("src/test/resources/valid.csr");
    String certStr = new String(Files.readAllBytes(path));

    PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(certStr);
    X509Certificate caCertificate = Crypto.loadX509Certificate(ecPublicX509Cert);
    PrivateKey caPrivateKey = Crypto.loadPrivateKey(rsaPrivateKey);

    X509Certificate cert = Crypto.generateX509Certificate(certReq, caPrivateKey,
            caCertificate, 600, false);
    assertNotNull(cert);
    assertEquals(cert.getIssuerX500Principal().getName(),
            "CN=athenz.syncer,O=My Test Company,L=Sunnyvale,ST=CA,C=US");
}
 
Example #9
Source File: CertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
public PKCS10CertificationRequest build() throws SCMSecurityException {
  Preconditions.checkNotNull(key, "KeyPair cannot be null");
  Preconditions.checkArgument(Strings.isNotBlank(subject), "Subject " +
      "cannot be blank");

  try {
    CertificateSignRequest csr = new CertificateSignRequest(subject, scmID,
        clusterID, key, config, createExtensions());
    return csr.generateCSR();
  } catch (IOException ioe) {
    throw new CertificateException(String.format("Unable to create " +
        "extension for certificate sign request for %s.", SecurityUtil
        .getDistinguishedName(subject, scmID, clusterID)), ioe.getCause());
  } catch (OperatorCreationException ex) {
    throw new CertificateException(String.format("Unable to create " +
        "certificate sign request for %s.", SecurityUtil
        .getDistinguishedName(subject, scmID, clusterID)),
        ex.getCause());
  }
}
 
Example #10
Source File: Crypto.java    From athenz with Apache License 2.0 6 votes vote down vote up
public static List<String> extractX509CSRIPAddresses(PKCS10CertificationRequest certReq) {

        List<String> ipAddresses = new ArrayList<>();
        Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        for (Attribute attribute : attributes) {
            for (ASN1Encodable value : attribute.getAttributeValues()) {
                Extensions extensions = Extensions.getInstance(value);
                GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
                ///CLOVER:OFF
                if (gns == null) {
                    continue;
                }
                ///CLOVER:ON
                for (GeneralName name : gns.getNames()) {
                    if (name.getTagNo() == GeneralName.iPAddress) {
                        try {
                            InetAddress addr = InetAddress.getByAddress(((DEROctetString) name.getName()).getOctets());
                            ipAddresses.add(addr.getHostAddress());
                        } catch (UnknownHostException ignored) {
                        }
                    }
                }
            }
        }
        return ipAddresses;
    }
 
Example #11
Source File: CertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
public static String getEncodedString(PKCS10CertificationRequest request)
    throws IOException {
  PemObject pemObject =
      new PemObject("CERTIFICATE REQUEST", request.getEncoded());
  StringWriter str = new StringWriter();
  try(JcaPEMWriter pemWriter = new JcaPEMWriter(str)) {
    pemWriter.writeObject(pemObject);
  }
  return str.toString();
}
 
Example #12
Source File: CsrLoaderImpl.java    From java-certificate-authority with Apache License 2.0 6 votes vote down vote up
@Override
public CSR getCsr() {
  try {
    try (Reader pemReader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
      try (final PEMParser pemParser = new PEMParser(pemReader)) {
        final Object parsedObj = pemParser.readObject();

        if (parsedObj instanceof PKCS10CertificationRequest) {
          final PKCS10CertificationRequest csr = (PKCS10CertificationRequest) parsedObj;
          return new CsrImpl(csr);
        } else
          throw new CaException("Not a PKCS10CertificationRequest");
      }
    }
  } catch (final IOException e) {
    throw new CaException(e);
  }
}
 
Example #13
Source File: ZTSClientTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateInstanceRefreshRequestSubDomain() {

    File privkey = new File("./src/test/resources/unit_test_private_k0.pem");
    PrivateKey privateKey = Crypto.loadPrivateKey(privkey);

    InstanceRefreshRequest req = ZTSClient.generateInstanceRefreshRequest("coretech.system",
            "test", privateKey, "aws", 3600);
    assertNotNull(req);

    PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(req.getCsr());
    assertEquals("coretech.system.test", Crypto.extractX509CSRCommonName(certReq));

    X500Name x500name = certReq.getSubject();
    RDN cnRdn = x500name.getRDNs(BCStyle.CN)[0];
    assertEquals("coretech.system.test", IETFUtils.valueToString(cnRdn.getFirst().getValue()));
    assertEquals("test.coretech-system.aws.athenz.cloud", Crypto.extractX509CSRDnsNames(certReq).get(0));
}
 
Example #14
Source File: Crypto.java    From athenz with Apache License 2.0 6 votes vote down vote up
public static PKCS10CertificationRequest getPKCS10CertRequest(String csr) {

        if (csr == null || csr.isEmpty()) {
            LOG.error("getPKCS10CertRequest: CSR is null or empty");
            throw new CryptoException("CSR is null or empty");
        }

        try {
            Reader csrReader = new StringReader(csr);
            try (PEMParser pemParser = new PEMParser(csrReader)) {
                Object pemObj = pemParser.readObject();
                ///CLOVER:OFF
                if (pemObj instanceof PKCS10CertificationRequest) {
                    return (PKCS10CertificationRequest) pemObj;
                }
                ///CLOVER:ON
            }
        } catch (IOException ex) {
            LOG.error("getPKCS10CertRequest: unable to parse csr: " + ex.getMessage());
            throw new CryptoException(ex);
        }
        ///CLOVER:OFF
        return null;
        ///CLOVER:ON
    }
 
Example #15
Source File: X509CertRequestTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidatePublicKeysCertCSRFailure() throws IOException {
    
    Path path = Paths.get("src/test/resources/valid_provider_refresh.csr");
    String csr = new String(Files.readAllBytes(path));
    
    X509CertRequest certReq = new X509CertRequest(csr);
    assertNotNull(certReq);
    
    PKCS10CertificationRequest req = Mockito.mock(PKCS10CertificationRequest.class);
    Mockito.when(req.getSubjectPublicKeyInfo()).thenReturn(null);
    certReq.setCertReq(req);

    path = Paths.get("src/test/resources/valid_provider_refresh.pem");
    String pem = new String(Files.readAllBytes(path));
    X509Certificate cert = Crypto.loadX509Certificate(pem);
    
    assertFalse(certReq.validatePublicKeys(cert));
}
 
Example #16
Source File: TestHddsSecureDatanodeInit.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCSR() throws Exception {
  keyCodec.writePublicKey(publicKey);
  keyCodec.writePrivateKey(privateKey);
  service.setCertificateClient(client);
  PKCS10CertificationRequest csr =
      service.getCSR(conf);
  Assert.assertNotNull(csr);

  csr = service.getCSR(conf);
  Assert.assertNotNull(csr);

  csr = service.getCSR(conf);
  Assert.assertNotNull(csr);

  csr = service.getCSR(conf);
  Assert.assertNotNull(csr);
}
 
Example #17
Source File: GatewayPublicEndpointManagementService.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private boolean generateCertAndSaveForStack(Stack stack) {
    boolean result = false;
    LOGGER.info("Acquire certificate from PEM service and save for stack");
    String userCrn = ThreadBasedUserCrnProvider.getUserCrn();
    String accountId = ThreadBasedUserCrnProvider.getAccountId();
    SecurityConfig securityConfig = stack.getSecurityConfig();
    try {
        KeyPair keyPair = getKeyPairForStack(stack);
        String endpointName = getEndpointNameForStack(stack);
        DetailedEnvironmentResponse environment = environmentClientService.getByCrn(stack.getEnvironmentCrn());
        String environmentName = environment.getName();
        String workloadSubdomain = getWorkloadSubdomain(userCrn);
        String commonName = getDomainNameProvider().getCommonName(endpointName, environmentName, workloadSubdomain);
        String fullyQualifiedEndpointName = getDomainNameProvider().getFullyQualifiedEndpointName(endpointName, environmentName, workloadSubdomain);
        List<String> subjectAlternativeNames = List.of(commonName, fullyQualifiedEndpointName);
        LOGGER.info("Acquiring certificate with common name:{} and SANs: {}", commonName, String.join(",", subjectAlternativeNames));
        PKCS10CertificationRequest csr = PkiUtil.csr(keyPair, commonName, subjectAlternativeNames);
        List<String> certs = getCertificateCreationService().create(userCrn, accountId, endpointName, environmentName, csr);
        securityConfig.setUserFacingCert(String.join("", certs));
        securityConfigService.save(securityConfig);
        result = true;
    } catch (Exception e) {
        LOGGER.info("The certification could not be generated by Public Endpoint Management service: " + e.getMessage(), e);
    }
    return result;
}
 
Example #18
Source File: BaseApprover.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * This function verifies all extensions in the certificate.
 *
 * @param request - CSR
 * @return - true if the extensions are acceptable by the profile, false
 * otherwise.
 */
boolean verfiyExtensions(PKCS10CertificationRequest request) {
  Objects.requireNonNull(request);
  /*
   * Inside a CSR we have
   *  1. A list of Attributes
   *    2. Inside each attribute a list of extensions.
   *      3. We need to walk thru the each extension and verify they
   *      are expected and we can put that into a certificate.
   */

  for (Attribute attr : getAttributes(request)) {
    for (Extensions extensionsList : getExtensionsList(attr)) {
      for (Extension extension : getIndividualExtension(extensionsList)) {
        if (!profile.validateExtension(extension)) {
          LOG.error("Failed to verify extension. {}",
              extension.getExtnId().getId());
          return false;
        }
      }
    }
  }
  return true;
}
 
Example #19
Source File: TestCertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Test
public void testCsrSerialization() throws NoSuchProviderException,
    NoSuchAlgorithmException, SCMSecurityException, IOException {
  String clusterID = UUID.randomUUID().toString();
  String scmID = UUID.randomUUID().toString();
  String subject = "DN001";
  HDDSKeyGenerator keyGen =
      new HDDSKeyGenerator(securityConfig.getConfiguration());
  KeyPair keyPair = keyGen.generateKey();

  CertificateSignRequest.Builder builder =
      new CertificateSignRequest.Builder()
          .setSubject(subject)
          .setScmID(scmID)
          .setClusterID(clusterID)
          .setKey(keyPair)
          .setConfiguration(conf);

  PKCS10CertificationRequest csr = builder.build();
  byte[] csrBytes = csr.getEncoded();

  // Verify de-serialized CSR matches with the original CSR
  PKCS10CertificationRequest dsCsr = new PKCS10CertificationRequest(csrBytes);
  Assert.assertEquals(csr, dsCsr);
}
 
Example #20
Source File: CommonUtil.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
public static PKCS10CertificationRequest createCSR(X500Name subject, SM2PublicKey pubKey, PrivateKey priKey,
    String signAlgo) throws OperatorCreationException {
    PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(subject, pubKey);
    ContentSigner signerBuilder = new JcaContentSignerBuilder(signAlgo)
        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(priKey);
    return csrBuilder.build(signerBuilder);
}
 
Example #21
Source File: ZTSClientTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenerateRoleCertificateRequest() {

    File privkey = new File("./src/test/resources/unit_test_private_k0.pem");
    PrivateKey privateKey = Crypto.loadPrivateKey(privkey);

    RoleCertificateRequest req = ZTSClient.generateRoleCertificateRequest("coretech",
            "test", "sports", "readers", privateKey, "aws", 3600);
    assertNotNull(req);

    PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(req.getCsr());
    assertEquals("sports:role.readers", Crypto.extractX509CSRCommonName(certReq));
    assertEquals("[email protected]", Crypto.extractX509CSREmail(certReq));
}
 
Example #22
Source File: Pkcs10CsrUtils.java    From vespa with Apache License 2.0 5 votes vote down vote up
public static Pkcs10Csr fromPem(String pem) {
    try (PEMParser pemParser = new PEMParser(new StringReader(pem))) {
        return new Pkcs10Csr((PKCS10CertificationRequest) pemParser.readObject());
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #23
Source File: Crypto.java    From athenz with Apache License 2.0 5 votes vote down vote up
public static String extractX509CSRSubjectOField(PKCS10CertificationRequest certReq) {

        // in case there are multiple Os, we're only looking at the first one
        // in Athenz we should never have multiple Os so we're going to reject
        // any csr that has multiple values

        return extractX509CSRSubjectField(certReq, BCStyle.O);
    }
 
Example #24
Source File: PKCGenerate.java    From ofdrw with Apache License 2.0 5 votes vote down vote up
/**
 * 生成SM2密钥对的证书请求(pkcs10格式)
 *
 * @param kp      SM2密钥对
 * @param subject 证书使用者
 * @return 证书请求
 * @throws OperatorCreationException
 */
public static PKCS10CertificationRequest CertRequest(KeyPair kp, X500Name subject) throws OperatorCreationException {
    // 构造请求信息,主要是由“实体”的DN和公钥构成
    PKCS10CertificationRequestBuilder requestBuilder =
            new JcaPKCS10CertificationRequestBuilder(subject, kp.getPublic());
    // 使用“实体”私钥对请求的信息进行签名,然后组装成ASN.1对象
    return requestBuilder.build(
            new JcaContentSignerBuilder("SM3withSM2")
                    .setProvider("BC")
                    .build(kp.getPrivate()));

}
 
Example #25
Source File: Pkcs10Util.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * DER encode a CSR and PEM the encoding.
 *
 * @return The PEM'd encoding
 * @param csr
 *            The CSR
 * @throws CryptoException
 *             If a problem occurs getting the PEM encoded CSR
 */
public static String getCsrEncodedDerPem(PKCS10CertificationRequest csr) throws CryptoException {
	try {
		// Base 64 encoding of CSR
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DEROutputStream deros = new DEROutputStream(baos);
		deros.writeObject(csr.toASN1Structure().toASN1Primitive());
		String tmp = new String(Base64.encode(baos.toByteArray()));

		// Header
		String csrStr = BEGIN_CSR_FORM_1 + "\n";

		// Limit line lengths between header and footer
		for (int i = 0; i < tmp.length(); i += MAX_PRINTABLE_ENC_LINE_LENGTH) {
			int lineLength;

			if ((i + MAX_PRINTABLE_ENC_LINE_LENGTH) > tmp.length()) {
				lineLength = (tmp.length() - i);
			} else {
				lineLength = MAX_PRINTABLE_ENC_LINE_LENGTH;
			}

			csrStr += tmp.substring(i, (i + lineLength)) + "\n";
		}

		// Footer
		csrStr += END_CSR_FORM_1 + "\n";

		return csrStr;
	} catch (IOException ex) {
		throw new CryptoException(res.getString("NoPemPkcs10Csr.exception.message"), ex);
	}
}
 
Example #26
Source File: PkiUtil.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private static PKCS10CertificationRequest generateCsrWithName(KeyPair identity, String name, List<String> sanList) throws Exception {
    X500Principal principal = new X500Principal(name);
    PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(principal, identity.getPublic());

    if (!CollectionUtils.isEmpty(sanList)) {
        p10Builder = addSubjectAlternativeNames(p10Builder, sanList);
    }

    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
    ContentSigner signer = csBuilder.build(identity.getPrivate());
    return p10Builder.build(signer);
}
 
Example #27
Source File: CertificateUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public static byte[] createCSR(String dn, KeyPair keyPair) {
   String csrSignatureAlgorithm = RaPropertiesLoader.getProperty("csr.signature.algorithm");

   try {
      X500Principal x500Principal = new X500Principal(dn);
      JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(x500Principal, keyPair.getPublic());
      PKCS10CertificationRequest csr = csrBuilder.build((new JcaContentSignerBuilder(csrSignatureAlgorithm)).setProvider(new BouncyCastleProvider()).build(keyPair.getPrivate()));
      return csr.getEncoded();
   } catch (OperatorCreationException var6) {
      throw new IllegalArgumentException(var6);
   } catch (IOException var7) {
      throw new IllegalArgumentException(var7);
   }
}
 
Example #28
Source File: HddsDatanodeService.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Get SCM signed certificate and store it using certificate client.
 * @param config
 * */
private void getSCMSignedCert(OzoneConfiguration config) {
  try {
    PKCS10CertificationRequest csr = getCSR(config);
    // TODO: For SCM CA we should fetch certificate from multiple SCMs.
    SCMSecurityProtocolClientSideTranslatorPB secureScmClient =
        HddsServerUtil.getScmSecurityClient(config);
    SCMGetCertResponseProto response = secureScmClient.
        getDataNodeCertificateChain(datanodeDetails.getProtoBufMessage(),
            getEncodedString(csr));
    // Persist certificates.
    if(response.hasX509CACertificate()) {
      String pemEncodedCert = response.getX509Certificate();
      dnCertClient.storeCertificate(pemEncodedCert, true);
      dnCertClient.storeCertificate(response.getX509CACertificate(), true,
          true);
      datanodeDetails.setCertSerialId(getX509Certificate(pemEncodedCert).
          getSerialNumber().toString());
      persistDatanodeDetails(datanodeDetails);
    } else {
      throw new RuntimeException("Unable to retrieve datanode certificate " +
          "chain");
    }
  } catch (IOException | CertificateException e) {
    LOG.error("Error while storing SCM signed certificate.", e);
    throw new RuntimeException(e);
  }
}
 
Example #29
Source File: CertificateUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public static byte[] createCSR(String dn, KeyPair keyPair) {
   String csrSignatureAlgorithm = RaPropertiesLoader.getProperty("csr.signature.algorithm");

   try {
      X500Principal x500Principal = new X500Principal(dn);
      JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(x500Principal, keyPair.getPublic());
      PKCS10CertificationRequest csr = csrBuilder.build((new JcaContentSignerBuilder(csrSignatureAlgorithm)).setProvider(new BouncyCastleProvider()).build(keyPair.getPrivate()));
      return csr.getEncoded();
   } catch (OperatorCreationException var6) {
      throw new IllegalArgumentException(var6);
   } catch (IOException var7) {
      throw new IllegalArgumentException(var7);
   }
}
 
Example #30
Source File: CryptoTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testExtractX509CSRFieldsWithRfc822s() throws IOException {

    Path path = Paths.get("src/test/resources/valid_emails.csr");
    String csr = new String(Files.readAllBytes(path));
    PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(csr);
    assertNotNull(certReq);

    assertEquals(Crypto.extractX509CSRCommonName(certReq), "athenz.production");
    List<String> emails = Crypto.extractX509CSREmails(certReq);
    assertEquals(2, emails.size());
    assertEquals(emails.get(0), "[email protected]");
    assertEquals(emails.get(1), "[email protected]");
}