org.bouncycastle.pkcs.PKCSException Java Examples

The following examples show how to use org.bouncycastle.pkcs.PKCSException. 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: 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 #2
Source File: TestDefaultProfile.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Test invalid keys fail in the validation.
 *
 * @throws SCMSecurityException      - on Error.
 * @throws PKCSException             - on Error.
 * @throws OperatorCreationException - on Error.
 * @throws NoSuchProviderException   - on Error.
 * @throws NoSuchAlgorithmException  - on Error.
 */
@Test
public void testVerifyCertificateInvalidKeys() throws SCMSecurityException,
    PKCSException, OperatorCreationException,
    NoSuchProviderException, NoSuchAlgorithmException {
  KeyPair newKeyPair = new HDDSKeyGenerator(securityConfig).generateKey();
  KeyPair wrongKey = new KeyPair(keyPair.getPublic(),
      newKeyPair.getPrivate());
  PKCS10CertificationRequest csr = new CertificateSignRequest.Builder()
      .addDnsName("hadoop.apache.org")
      .addIpAddress("8.8.8.8")
      .setCA(false)
      .setClusterID("ClusterID")
      .setScmID("SCMID")
      .setSubject("Ozone Cluster")
      .setConfiguration(configuration)
      .setKey(wrongKey)
      .build();
  // Signature verification should fail here, since the public/private key
  // does not match.
  assertFalse(testApprover.verifyPkcs10Request(csr));
}
 
Example #3
Source File: PEMImporter.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
public static KeyStore loadKeyStore(File certificateChainFile, File privateKeyFile, String keyPassword)
    throws IOException, GeneralSecurityException
{
    PrivateKey key;
    try {
        key = createPrivateKey(privateKeyFile, keyPassword);
    } catch (OperatorCreationException | IOException | GeneralSecurityException | PKCSException e) {
        throw new GeneralSecurityException("Private Key issues", e);
    }

    List<X509Certificate> certificateChain = readCertificateChain(certificateChainFile);
    if (certificateChain.isEmpty()) {
        throw new CertificateException("Certificate file does not contain any certificates: " + certificateChainFile);
    }

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);
    keyStore.setKeyEntry("key", key, keyPassword.toCharArray(), certificateChain.stream().toArray(Certificate[]::new));
    return keyStore;
}
 
Example #4
Source File: CryptoExceptionTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testCryptoExceptions() {

    CryptoException ex = new CryptoException();
    assertNotNull(ex);
    assertEquals(ex.getCode(), CryptoException.CRYPTO_ERROR);

    assertNotNull(new CryptoException(new NoSuchAlgorithmException()));
    assertNotNull(new CryptoException(new InvalidKeyException()));
    assertNotNull(new CryptoException(new NoSuchProviderException()));
    assertNotNull(new CryptoException(new SignatureException()));
    assertNotNull(new CryptoException(new FileNotFoundException()));
    assertNotNull(new CryptoException(new IOException()));
    assertNotNull(new CryptoException(new CertificateException()));
    assertNotNull(new CryptoException(new InvalidKeySpecException()));
    assertNotNull(new CryptoException(new OperatorCreationException("unit-test")));
    assertNotNull(new CryptoException(new PKCSException("unit-test")));
    assertNotNull(new CryptoException(new CMSException("unit-test")));

    ex = new CryptoException(CryptoException.CERT_HASH_MISMATCH, "X.509 Certificate hash mismatch");
    assertEquals(ex.getCode(), CryptoException.CERT_HASH_MISMATCH);
}
 
Example #5
Source File: AadAuthenticationHelperTest.java    From azure-kusto-java with MIT License 6 votes vote down vote up
@Test
@DisplayName("validate auth with certificate throws exception when missing or invalid parameters")
void acquireWithClientCertificateNullKey() throws CertificateException, OperatorCreationException,
        PKCSException, IOException, URISyntaxException {

    String certFilePath = Paths.get("src", "test", "resources", "cert.cer").toString();
    String privateKeyPath = Paths.get("src", "test", "resources", "key.pem").toString();

    X509Certificate x509Certificate = readPem(certFilePath, "basic").getCertificate();
    PrivateKey privateKey = readPem(privateKeyPath, "basic").getKey();

    ConnectionStringBuilder csb = ConnectionStringBuilder
            .createWithAadApplicationCertificate("resource.uri", "client-id", x509Certificate, privateKey);

    AadAuthenticationHelper aadAuthenticationHelper = new AadAuthenticationHelper(csb);

    Assertions.assertThrows(ExecutionException.class,
            () -> aadAuthenticationHelper.acquireWithClientCertificate());
}
 
Example #6
Source File: X509CertUtil.java    From portecle with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Load a CSR from the specified URL.
 *
 * @param url The URL to load CSR from
 * @return The CSR
 * @throws CryptoException Problem encountered while loading the CSR
 * @throws FileNotFoundException If the CSR file does not exist, is a directory rather than a regular file, or for
 *             some other reason cannot be opened for reading
 * @throws IOException An I/O error occurred
 */
public static PKCS10CertificationRequest loadCSR(URL url)
    throws CryptoException, IOException
{
	// TODO: handle DER encoded requests too?
	try (PEMParser pr = new PEMParser(new InputStreamReader(NetUtil.openGetStream(url))))
	{
		PKCS10CertificationRequest csr = (PKCS10CertificationRequest) pr.readObject();
		ContentVerifierProvider prov = new JcaContentVerifierProviderBuilder().build(csr.getSubjectPublicKeyInfo());

		if (!csr.isSignatureValid(prov))
		{
			throw new CryptoException(RB.getString("NoVerifyCsr.exception.message"));
		}

		return csr;
	}
	catch (ClassCastException | OperatorCreationException | PKCSException ex)
	{
		throw new CryptoException(RB.getString("NoLoadCsr.exception.message"), ex);
	}
}
 
Example #7
Source File: AadAuthenticationHelperTest.java    From azure-kusto-java with MIT License 5 votes vote down vote up
@Test
@DisplayName("validate cached token. Refresh if needed. Call regularly if no refresh token")
void useCachedTokenAndRefreshWhenNeeded() throws InterruptedException, ExecutionException, ServiceUnavailableException, IOException, DataServiceException, URISyntaxException, CertificateException, OperatorCreationException, PKCSException {
    String certFilePath = Paths.get("src", "test", "resources", "cert.cer").toString();
    String privateKeyPath = Paths.get("src", "test", "resources", "key.pem").toString();

    X509Certificate x509Certificate = readPem(certFilePath, "basic").getCertificate();
    PrivateKey privateKey = readPem(privateKeyPath, "basic").getKey();

    ConnectionStringBuilder csb = ConnectionStringBuilder
            .createWithAadApplicationCertificate("resource.uri", "client-id", x509Certificate, privateKey);

    AadAuthenticationHelper aadAuthenticationHelperSpy = spy(new AadAuthenticationHelper(csb));

    AuthenticationResult authenticationResult = new AuthenticationResult("testType", "firstToken", "refreshToken", 0, "id", mock(UserInfo.class), false);
    AuthenticationResult authenticationResultFromRefresh = new AuthenticationResult("testType", "fromRefresh", null, 90, "id", mock(UserInfo.class), false);
    AuthenticationResult authenticationResultNullRefreshTokenResult = new AuthenticationResult("testType", "nullRefreshResult", null, 0, "id", mock(UserInfo.class), false);

    doReturn(authenticationResultFromRefresh).when(aadAuthenticationHelperSpy).acquireAccessTokenByRefreshToken();
    doReturn(authenticationResult).when(aadAuthenticationHelperSpy).acquireWithClientCertificate();

    assertEquals("firstToken", aadAuthenticationHelperSpy.acquireAccessToken());

    // Token was passed as expired - expected to be refreshed
    assertEquals("fromRefresh", aadAuthenticationHelperSpy.acquireAccessToken());

    // Token is still valid - expected to return the same
    assertEquals("fromRefresh", aadAuthenticationHelperSpy.acquireAccessToken());

    doReturn(new Date(System.currentTimeMillis() + MIN_ACCESS_TOKEN_VALIDITY_IN_MILLISECS * 2)).when(aadAuthenticationHelperSpy).dateInAMinute();
    doReturn(authenticationResultNullRefreshTokenResult).when(aadAuthenticationHelperSpy).acquireWithClientCertificate();

    // Null refresh token + token is now expired- expected to authenticate again and reacquire token
    assertEquals("nullRefreshResult", aadAuthenticationHelperSpy.acquireAccessToken());
}
 
Example #8
Source File: CaEmulator.java    From xipki with Apache License 2.0 5 votes vote down vote up
private boolean verifyPopo(CertificationRequest csr) {
  Args.notNull(csr, "csr");
  try {
    PKCS10CertificationRequest p10Req = new PKCS10CertificationRequest(csr);
    SubjectPublicKeyInfo pkInfo = p10Req.getSubjectPublicKeyInfo();
    PublicKey pk = generatePublicKey(pkInfo);

    ContentVerifierProvider cvp = getContentVerifierProvider(pk);
    return p10Req.isSignatureValid(cvp);
  } catch (InvalidKeyException | PKCSException | InvalidKeySpecException ex) {
    LOG.error("could not validate POPO of CSR", ex);
    return false;
  }
}
 
Example #9
Source File: AzureKeyVaultClientAuthenticator.java    From ranger with Apache License 2.0 5 votes vote down vote up
private KeyCert readPem(String path, String password) throws IOException, CertificateException, OperatorCreationException, PKCSException {
	Security.addProvider(new BouncyCastleProvider());
	PEMParser pemParser = new PEMParser(new FileReader(new File(path)));
	PrivateKey privateKey = null;
	X509Certificate cert = null;
	Object object = pemParser.readObject();
	
	while (object != null) {
		JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
		if (object instanceof X509CertificateHolder) {
			cert = new JcaX509CertificateConverter().getCertificate((X509CertificateHolder) object);
		}
		if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
			PKCS8EncryptedPrivateKeyInfo pinfo = (PKCS8EncryptedPrivateKeyInfo) object;
			InputDecryptorProvider provider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(password.toCharArray());
			PrivateKeyInfo info = pinfo.decryptPrivateKeyInfo(provider);
			privateKey = converter.getPrivateKey(info);
		} 
		if (object instanceof PrivateKeyInfo) {
			privateKey = converter.getPrivateKey((PrivateKeyInfo) object);
		}
		object = pemParser.readObject();
	}
	KeyCert keycert = new KeyCert();
	keycert.setCertificate(cert);
	keycert.setKey(privateKey);
	pemParser.close();
	return keycert;
}
 
Example #10
Source File: Pkcs10Util.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Verify a PKCS #10 certificate signing request (CSR).
 *
 * @param csr The certificate signing request
 * @return True if successfully verified
 * @throws CryptoException
 * 				If there was a problem verifying the CSR
 */
public static boolean verifyCsr(PKCS10CertificationRequest csr) throws CryptoException {
	try {
		PublicKey pubKey = new JcaPKCS10CertificationRequest(csr).getPublicKey();

		ContentVerifierProvider contentVerifierProvider =
				new JcaContentVerifierProviderBuilder().setProvider("BC").build(pubKey);
		return csr.isSignatureValid(contentVerifierProvider);
	} catch (InvalidKeyException | OperatorCreationException | NoSuchAlgorithmException | PKCSException e) {
		throw new CryptoException(res.getString("NoVerifyPkcs10Csr.exception.message"), e);
	}
}
 
Example #11
Source File: X509CertUtil.java    From portecle with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a PKCS #10 certification request (CSR) using the supplied certificate and private key.
 *
 * @param cert The certificate
 * @param privateKey The private key
 * @throws CryptoException If there was a problem generating the CSR
 * @return The CSR
 */
public static PKCS10CertificationRequest generatePKCS10CSR(X509Certificate cert, PrivateKey privateKey)
    throws CryptoException
{
	X500Name subject = new X500Name(cert.getSubjectDN().toString());

	JcaPKCS10CertificationRequestBuilder csrBuilder =
	    new JcaPKCS10CertificationRequestBuilder(subject, cert.getPublicKey());
	JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(cert.getSigAlgName());

	try
	{
		ContentVerifierProvider prov = new JcaContentVerifierProviderBuilder().build(cert);
		PKCS10CertificationRequest csr = csrBuilder.build(signerBuilder.build(privateKey));

		if (!csr.isSignatureValid(prov))
		{
			throw new CryptoException(RB.getString("NoVerifyGenCsr.exception.message"));
		}

		return csr;
	}
	catch (OperatorCreationException | PKCSException ex)
	{
		throw new CryptoException(RB.getString("NoGenerateCsr.exception.message"), ex);
	}
}
 
Example #12
Source File: ConnectionStringBuilderTest.java    From azure-kusto-java with MIT License 5 votes vote down vote up
@Test
@DisplayName("validate createWithAadApplicationCertificate throws IllegalArgumentException exception when missing or invalid parameters")
void createWithAadApplicationCertificate() throws CertificateException, OperatorCreationException,
        PKCSException, IOException {

    String certFilePath = Paths.get("src","test","resources", "cert.cer").toString();
    String privateKeyPath = Paths.get("src","test","resources","key.pem").toString();

    X509Certificate x509Certificate = readPem(certFilePath, "basic").getCertificate();
    PrivateKey privateKey = readPem(privateKeyPath, "basic").getKey();

    //nullOrEmpty resourceUri
    Assertions.assertThrows(IllegalArgumentException.class,
            () -> ConnectionStringBuilder
                    .createWithAadApplicationCertificate(null, "appId", x509Certificate, privateKey));
    Assertions.assertThrows(IllegalArgumentException.class,
            () -> ConnectionStringBuilder
                    .createWithAadApplicationCertificate("", "appId", x509Certificate, privateKey));

    //nullOrEmpty appId
    Assertions.assertThrows(IllegalArgumentException.class,
            () -> ConnectionStringBuilder
                    .createWithAadApplicationCertificate("resource.uri", null, x509Certificate, privateKey));
    Assertions.assertThrows(IllegalArgumentException.class,
            () -> ConnectionStringBuilder
                    .createWithAadApplicationCertificate("resource.uri", "", x509Certificate, privateKey));
    //null certificate
    Assertions.assertThrows(IllegalArgumentException.class,
            () -> ConnectionStringBuilder
                    .createWithAadApplicationCertificate("resource.uri", "appID", null, privateKey));
    //null privateKey
    Assertions.assertThrows(IllegalArgumentException.class,
            () -> ConnectionStringBuilder
                    .createWithAadApplicationCertificate("resource.uri", "appID", x509Certificate, null));
}
 
Example #13
Source File: BaseApprover.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the Signature on the CSR is valid.
 *
 * @param pkcs10Request - PCKS10 Request.
 * @return True if it is valid, false otherwise.
 * @throws OperatorCreationException - On Error.
 * @throws PKCSException             - on Error.
 */
boolean verifyPkcs10Request(PKCS10CertificationRequest pkcs10Request)
    throws OperatorCreationException, PKCSException {
  ContentVerifierProvider verifierProvider = new
      JcaContentVerifierProviderBuilder()
      .setProvider(this.securityConfig.getProvider())
      .build(pkcs10Request.getSubjectPublicKeyInfo());
  return
      pkcs10Request.isSignatureValid(verifierProvider);
}
 
Example #14
Source File: AadAuthenticationHelperTest.java    From azure-kusto-java with MIT License 5 votes vote down vote up
static KeyCert readPem(String path, String password)
        throws IOException, CertificateException, OperatorCreationException, PKCSException {

    Security.addProvider(new BouncyCastleProvider());
    PEMParser pemParser = new PEMParser(new FileReader(new File(path)));
    PrivateKey privateKey = null;
    X509Certificate cert = null;
    Object object = pemParser.readObject();

    while (object != null) {
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
        if (object instanceof X509CertificateHolder) {
            cert = new JcaX509CertificateConverter().getCertificate((X509CertificateHolder) object);
        }
        if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
            PKCS8EncryptedPrivateKeyInfo pinfo = (PKCS8EncryptedPrivateKeyInfo) object;
            InputDecryptorProvider provider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(password.toCharArray());
            PrivateKeyInfo info = pinfo.decryptPrivateKeyInfo(provider);
            privateKey = converter.getPrivateKey(info);
        }
        if (object instanceof PrivateKeyInfo) {
            privateKey = converter.getPrivateKey((PrivateKeyInfo) object);
        }
        object = pemParser.readObject();
    }

    KeyCert keycert = new KeyCert(null, null);
    keycert.setCertificate(cert);
    keycert.setKey(privateKey);
    pemParser.close();
    return keycert;
}
 
Example #15
Source File: SM2PfxMaker.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
/**
 * @param privKey 用户私钥
 * @param pubKey  用户公钥
 * @param cert    X509证书
 * @param passwd  口令
 * @return
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws PKCSException
 */
public PKCS12PfxPdu makePfx(PrivateKey privKey, PublicKey pubKey, X509Certificate cert, String passwd)
    throws NoSuchAlgorithmException, IOException, PKCSException {
    JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();

    PKCS12SafeBagBuilder eeCertBagBuilder = new JcaPKCS12SafeBagBuilder(cert);
    eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
        new DERBMPString("User Key"));
    eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
        extUtils.createSubjectKeyIdentifier(pubKey));

    char[] passwdChars = passwd.toCharArray();
    PKCS12SafeBagBuilder keyBagBuilder = new JcaPKCS12SafeBagBuilder(privKey,
        new BcPKCS12PBEOutputEncryptorBuilder(
            PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC,
            new CBCBlockCipher(new DESedeEngine())).build(passwdChars));
    keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
        new DERBMPString("User Key"));
    keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
        extUtils.createSubjectKeyIdentifier(pubKey));

    PKCS12PfxPduBuilder pfxPduBuilder = new PKCS12PfxPduBuilder();
    PKCS12SafeBag[] certs = new PKCS12SafeBag[1];
    certs[0] = eeCertBagBuilder.build();
    pfxPduBuilder.addEncryptedData(new BcPKCS12PBEOutputEncryptorBuilder(
            PKCSObjectIdentifiers.pbeWithSHAAnd40BitRC2_CBC,
            new CBCBlockCipher(new RC2Engine())).build(passwdChars),
        certs);
    pfxPduBuilder.addData(keyBagBuilder.build());
    return pfxPduBuilder.build(new BcPKCS12MacCalculatorBuilder(), passwdChars);
}
 
Example #16
Source File: CryptoException.java    From athenz with Apache License 2.0 4 votes vote down vote up
public CryptoException(PKCSException e) {
    super(e);
}
 
Example #17
Source File: SM2PfxMaker.java    From gmhelper with Apache License 2.0 4 votes vote down vote up
/**
 * @param privKey 用户私钥
 * @param pubKey  用户公钥
 * @param chain   X509证书数组,切记这里固定了必须是3个元素的数组,且第一个必须是叶子证书、第二个为中级CA证书、第三个为根CA证书
 * @param passwd  口令
 * @return
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws PKCSException
 */
public PKCS12PfxPdu makePfx(PrivateKey privKey, PublicKey pubKey, X509Certificate[] chain, String passwd)
    throws NoSuchAlgorithmException, IOException, PKCSException {
    JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();

    PKCS12SafeBagBuilder taCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[2]);
    taCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
        new DERBMPString("Primary Certificate"));

    PKCS12SafeBagBuilder caCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[1]);
    caCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
        new DERBMPString("Intermediate Certificate"));

    PKCS12SafeBagBuilder eeCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[0]);
    eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
        new DERBMPString("User Key"));
    eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
        extUtils.createSubjectKeyIdentifier(pubKey));

    char[] passwdChars = passwd.toCharArray();
    PKCS12SafeBagBuilder keyBagBuilder = new JcaPKCS12SafeBagBuilder(privKey,
        new BcPKCS12PBEOutputEncryptorBuilder(
            PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC,
            new CBCBlockCipher(new DESedeEngine())).build(passwdChars));
    keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
        new DERBMPString("User Key"));
    keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
        extUtils.createSubjectKeyIdentifier(pubKey));

    PKCS12PfxPduBuilder pfxPduBuilder = new PKCS12PfxPduBuilder();
    PKCS12SafeBag[] certs = new PKCS12SafeBag[3];
    certs[0] = eeCertBagBuilder.build();
    certs[1] = caCertBagBuilder.build();
    certs[2] = taCertBagBuilder.build();
    pfxPduBuilder.addEncryptedData(new BcPKCS12PBEOutputEncryptorBuilder(
            PKCSObjectIdentifiers.pbeWithSHAAnd40BitRC2_CBC,
            new CBCBlockCipher(new RC2Engine())).build(passwdChars),
        certs);
    pfxPduBuilder.addData(keyBagBuilder.build());
    return pfxPduBuilder.build(new BcPKCS12MacCalculatorBuilder(), passwdChars);
}
 
Example #18
Source File: TestCertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
@Test
public void testGenerateCSRwithSan() throws NoSuchProviderException,
    NoSuchAlgorithmException, SCMSecurityException,
    OperatorCreationException, PKCSException {
  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);

  // Multi-home
  builder.addIpAddress("192.168.1.1");
  builder.addIpAddress("192.168.2.1");
  builder.addServiceName("OzoneMarketingCluster003");

  builder.addDnsName("dn1.abc.com");

  PKCS10CertificationRequest csr = builder.build();

  // Check the Subject Name is in the expected format.
  String dnName = String.format(SecurityUtil.getDistinguishedNameFormat(),
      subject, scmID, clusterID);
  Assert.assertEquals(csr.getSubject().toString(), dnName);

  // Verify the public key info match
  byte[] encoded = keyPair.getPublic().getEncoded();
  SubjectPublicKeyInfo subjectPublicKeyInfo =
      SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(encoded));
  SubjectPublicKeyInfo csrPublicKeyInfo = csr.getSubjectPublicKeyInfo();
  Assert.assertEquals(csrPublicKeyInfo, subjectPublicKeyInfo);

  // Verify CSR with attribute for extensions
  Assert.assertEquals(1, csr.getAttributes().length);
  Extensions extensions = SecurityUtil.getPkcs9Extensions(csr);

  // Verify key usage extension
  Extension sanExt = extensions.getExtension(Extension.keyUsage);
  Assert.assertEquals(true, sanExt.isCritical());

  verifyServiceId(extensions);

  // Verify signature in CSR
  ContentVerifierProvider verifierProvider =
      new JcaContentVerifierProviderBuilder().setProvider(securityConfig
          .getProvider()).build(csr.getSubjectPublicKeyInfo());
  Assert.assertEquals(true, csr.isSignatureValid(verifierProvider));
}
 
Example #19
Source File: TestCertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
@Test
public void testGenerateCSR() throws NoSuchProviderException,
    NoSuchAlgorithmException, SCMSecurityException,
    OperatorCreationException, PKCSException {
  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();

  // Check the Subject Name is in the expected format.
  String dnName = String.format(SecurityUtil.getDistinguishedNameFormat(),
      subject, scmID, clusterID);
  Assert.assertEquals(csr.getSubject().toString(), dnName);

  // Verify the public key info match
  byte[] encoded = keyPair.getPublic().getEncoded();
  SubjectPublicKeyInfo subjectPublicKeyInfo =
      SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(encoded));
  SubjectPublicKeyInfo csrPublicKeyInfo = csr.getSubjectPublicKeyInfo();
  Assert.assertEquals(csrPublicKeyInfo, subjectPublicKeyInfo);

  // Verify CSR with attribute for extensions
  Assert.assertEquals(1, csr.getAttributes().length);
  Extensions extensions = SecurityUtil.getPkcs9Extensions(csr);

  // Verify key usage extension
  Extension keyUsageExt = extensions.getExtension(Extension.keyUsage);
  Assert.assertEquals(true, keyUsageExt.isCritical());


  // Verify San extension not set
  Assert.assertEquals(null,
      extensions.getExtension(Extension.subjectAlternativeName));

  // Verify signature in CSR
  ContentVerifierProvider verifierProvider =
      new JcaContentVerifierProviderBuilder().setProvider(securityConfig
          .getProvider()).build(csr.getSubjectPublicKeyInfo());
  Assert.assertEquals(true, csr.isSignatureValid(verifierProvider));
}
 
Example #20
Source File: CertificateManager.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Parses a PrivateKey instance from a PEM representation.
 *
 * When the provided key is encrypted, the provided pass phrase is applied.
 *
 * @param pemRepresentation a PEM representation of a private key (cannot be null or empty)
 * @param passPhrase optional pass phrase (must be present if the private key is encrypted).
 * @return a PrivateKey instance (never null)
 * @throws IOException if there was a problem parsing the key
 */
public static PrivateKey parsePrivateKey(InputStream pemRepresentation, String passPhrase) throws IOException {

    if ( passPhrase == null ) {
        passPhrase = "";
    }
    try (Reader reader = new InputStreamReader(pemRepresentation); //
            PEMParser pemParser = new PEMParser(reader)) {

        final Object object = pemParser.readObject();
        final JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider( "BC" );

        final KeyPair kp;

        if ( object instanceof PEMEncryptedKeyPair )
        {
            // Encrypted key - we will use provided password
            final PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build( passPhrase.toCharArray() );
            kp = converter.getKeyPair( ( (PEMEncryptedKeyPair) object ).decryptKeyPair( decProv ) );
        }
        else if ( object instanceof PKCS8EncryptedPrivateKeyInfo )
        {
            // Encrypted key - we will use provided password
            try
            {
                final PKCS8EncryptedPrivateKeyInfo encryptedInfo = (PKCS8EncryptedPrivateKeyInfo) object;
                final InputDecryptorProvider provider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build( passPhrase.toCharArray() );
                final PrivateKeyInfo privateKeyInfo = encryptedInfo.decryptPrivateKeyInfo( provider );
                return converter.getPrivateKey( privateKeyInfo );
            }
            catch ( PKCSException | OperatorCreationException e )
            {
                throw new IOException( "Unable to decrypt private key.", e );
            }
        }
        else if ( object instanceof PrivateKeyInfo )
        {
            return converter.getPrivateKey( (PrivateKeyInfo) object );
        }
        else
        {
            // Unencrypted key - no password needed
            kp = converter.getKeyPair( (PEMKeyPair) object );
        }
        return kp.getPrivate();
    }
}
 
Example #21
Source File: BaseApprover.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public CompletableFuture<X509CertificateHolder>
      inspectCSR(PKCS10CertificationRequest csr) {
  /**
   * The base approver executes the following algorithm to verify that a
   * CSR meets the PKI Profile criteria.
   *
   * 0. For time being (Until we have SCM HA) we will deny all request to
   * become an intermediary CA. So we will not need to verify using CA
   * profile, right now.
   *
   * 1. We verify the proof of possession. That is we verify the entity
   * that sends us the CSR indeed has the private key for the said public key.
   *
   * 2. Then we will verify the RDNs meet the format and the Syntax that
   * PKI profile dictates.
   *
   * 3. Then we decode each and every extension and  ask if the PKI profile
   * approves of these extension requests.
   *
   * 4. If all of these pass, We will return a Future which will point to
   * the Certificate when finished.
   */

  CompletableFuture<X509CertificateHolder> response =
      new CompletableFuture<>();
  try {
    // Step 0: Verify this is not a CA Certificate.
    // Will be done by the Ozone PKI profile for time being.
    // If there are any basicConstraints, they will flagged as not
    // supported for time being.

    // Step 1: Let us verify that Certificate is indeed signed by someone
    // who has access to the private key.
    if (!verifyPkcs10Request(csr)) {
      LOG.error("Failed to verify the signature in CSR.");
      response.completeExceptionally(new SCMSecurityException("Failed to " +
          "verify the CSR."));
    }

    // Step 2: Verify the RDNs are in the correct format.
    // TODO: Ozone Profile does not verify RDN now, so this call will pass.
    for (RDN rdn : csr.getSubject().getRDNs()) {
      if (!profile.validateRDN(rdn)) {
        LOG.error("Failed in verifying RDNs");
        response.completeExceptionally(new SCMSecurityException("Failed to " +
            "verify the RDNs. Please check the subject name."));
      }
    }

    // Step 3: Verify the Extensions.
    if (!verfiyExtensions(csr)) {
      LOG.error("failed in verification of extensions.");
      response.completeExceptionally(new SCMSecurityException("Failed to " +
          "verify extensions."));
    }

  } catch (OperatorCreationException | PKCSException e) {
    LOG.error("Approval Failure.", e);
    response.completeExceptionally(new SCMSecurityException(e));
  }
  return response;
}