org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider Java Examples

The following examples show how to use org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider. 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: CertificateGeneratorTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
private void setupMocksForRootCA(final KeyPair childCertificateKeyPair) throws Exception {
  when(certificateAuthorityService.findActiveVersion("/my-ca-name")).thenReturn(rootCa);
  when(keyGenerator.generateKeyPair(anyInt())).thenReturn(childCertificateKeyPair);
  final X509CertificateHolder childCertificateHolder = generateChildCertificateSignedByCa(
    childCertificateKeyPair,
    rootCaKeyPair.getPrivate(),
    rootCaDn
  );

  childX509Certificate = new JcaX509CertificateConverter()
    .setProvider(BouncyCastleFipsProvider.PROVIDER_NAME)
    .getCertificate(childCertificateHolder);

  when(
    signedCertificateGenerator
      .getSignedByIssuer(childCertificateKeyPair, inputParameters, rootCaX509Certificate, rootCaKeyPair.getPrivate())
  ).thenReturn(childX509Certificate);
}
 
Example #2
Source File: CertificateGeneratorTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Test
public void whenSelfSignIsTrue_itGeneratesAValidSelfSignedCertificate() throws Exception {
  final X509Certificate certificate = new JcaX509CertificateConverter().setProvider(BouncyCastleFipsProvider.PROVIDER_NAME)
    .getCertificate(generateX509SelfSignedCert());

  generationParameters.setCaName(null);
  generationParameters.setSelfSigned(true);
  inputParameters = new CertificateGenerationParameters(generationParameters);
  when(keyGenerator.generateKeyPair(anyInt())).thenReturn(rootCaKeyPair);
  when(signedCertificateGenerator.getSelfSigned(rootCaKeyPair, inputParameters))
    .thenReturn(certificate);

  final CertificateCredentialValue certificateCredential = subject.generateCredential(inputParameters);
  assertThat(certificateCredential.getPrivateKey(),
    equalTo(CertificateFormatter.pemOf(rootCaKeyPair.getPrivate())));
  assertThat(certificateCredential.getCertificate(),
    equalTo(CertificateFormatter.pemOf(certificate)));
  assertThat(certificateCredential.getCa(), equalTo(CertificateFormatter.pemOf(certificate)));
  verify(signedCertificateGenerator, times(1)).getSelfSigned(rootCaKeyPair, inputParameters);
}
 
Example #3
Source File: DefaultCertificateAuthorityServiceTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Before
public void beforeEach() {
  if (Security.getProvider(BouncyCastleFipsProvider.PROVIDER_NAME) == null) {
    Security.addProvider(new BouncyCastleFipsProvider());
  }

  certificate = new CertificateCredentialValue(null, SELF_SIGNED_CA_CERT, "my-key", null, true, true, false, false);
  certificateCredential = mock(CertificateCredentialVersion.class);
  transitionalCertificateCredential = mock(CertificateCredentialVersion.class);

  when(certificateCredential.getName()).thenReturn(CREDENTIAL_NAME);
  when(transitionalCertificateCredential.getName()).thenReturn(TRANSITIONAL_CREDENTIAL_NAME);
  when(transitionalCertificateCredential.isVersionTransitional()).thenReturn(true);

  certificateVersionDataService = mock(DefaultCertificateVersionDataService.class);
  certificateAuthorityService = new DefaultCertificateAuthorityService(certificateVersionDataService);
}
 
Example #4
Source File: RsaKeyPairGenerator.java    From credhub with Apache License 2.0 5 votes vote down vote up
public synchronized KeyPair generateKeyPair(final int keyLength)
  throws NoSuchProviderException, NoSuchAlgorithmException {
  final BouncyCastleFipsProvider bouncyCastleProvider = new BouncyCastleFipsProvider();
  Security.addProvider(bouncyCastleProvider);

  final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", BouncyCastleFipsProvider.PROVIDER_NAME);
  generator.initialize(keyLength);
  return generator.generateKeyPair();
}
 
Example #5
Source File: CredentialFactoryTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws JsonProcessingException {

  if (Security.getProvider(BouncyCastleFipsProvider.PROVIDER_NAME) == null) {
    Security.addProvider(new BouncyCastleFipsProvider());
  }

  final Encryptor encryptor = mock(Encryptor.class);
  subject = new CredentialFactory(encryptor);
  objectMapper = new JsonObjectMapper();

  generationParameters = new StringGenerationParameters();
  generationParameters.setExcludeNumber(true);
  generationParameters.setLength(PLAINTEXT_VALUE.length());

  final UUID encryptionKeyUuid = UUID.randomUUID();
  final EncryptedValue encryption = new EncryptedValue(encryptionKeyUuid, PLAINTEXT_VALUE.getBytes(UTF_8), "test-nonce".getBytes(UTF_8));
  when(encryptor.encrypt(PLAINTEXT_VALUE)).thenReturn(encryption);
  when(encryptor.decrypt(encryption)).thenReturn(PLAINTEXT_VALUE);

  final String generationParametersJsonString = objectMapper.writeValueAsString(generationParameters);
  final EncryptedValue parametersEncryption = new EncryptedValue(encryptionKeyUuid, "test-parameters".getBytes(UTF_8), "test-parameters-nonce".getBytes(UTF_8));
  when(encryptor.encrypt(generationParametersJsonString)).thenReturn(parametersEncryption);
  when(encryptor.decrypt(parametersEncryption)).thenReturn(generationParametersJsonString);

  final EncryptedValue jsonEncryption = new EncryptedValue(encryptionKeyUuid, jsonValueJsonString.getBytes(UTF_8), "test-nonce".getBytes(UTF_8));
  when(encryptor.encrypt(jsonValueJsonString)).thenReturn(jsonEncryption);
  when(encryptor.decrypt(jsonEncryption)).thenReturn(jsonValueJsonString);
}
 
Example #6
Source File: CertificateGeneratorTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
private X509CertificateHolder makeCert(final KeyPair certKeyPair,
                                       final PrivateKey caPrivateKey,
                                       final X500Name caDn,
                                       final X500Name subjectDn,
                                       final boolean isCa) throws OperatorCreationException, NoSuchAlgorithmException, CertIOException {
  final SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(certKeyPair.getPublic()
    .getEncoded());
  final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA")
    .setProvider(BouncyCastleFipsProvider.PROVIDER_NAME)
    .build(caPrivateKey);

  final CurrentTimeProvider currentTimeProvider = new CurrentTimeProvider();

  final Instant now = Instant.from(currentTimeProvider.getInstant());

  final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(
    caDn,
    BigInteger.TEN,
    Date.from(now),
    Date.from(now.plus(Duration.ofDays(365))),
    subjectDn,
    publicKeyInfo
  );
  x509v3CertificateBuilder
    .addExtension(Extension.basicConstraints, true, new BasicConstraints(isCa));
  return x509v3CertificateBuilder.build(contentSigner);
}
 
Example #7
Source File: CertificateGeneratorTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
@Test
public void whenCAExists_andHasATransitionalVersion_aValidChildCertificateIsGenerated() throws Exception {
  final KeyPair childCertificateKeyPair = setupKeyPair();
  setupMocksForRootCA(childCertificateKeyPair);

  KeyPair transitionalCaKeyPair = fakeKeyPairGenerator.generate();
  final X509CertificateHolder caX509CertHolder = makeCert(transitionalCaKeyPair, transitionalCaKeyPair.getPrivate(),
    rootCaDn, rootCaDn, true);
  X509Certificate transitionalCaX509Certificate = new JcaX509CertificateConverter()
    .setProvider(BouncyCastleFipsProvider.PROVIDER_NAME).getCertificate(caX509CertHolder);
  CertificateCredentialValue transitionalCa = new CertificateCredentialValue(
    null,
    CertificateFormatter.pemOf(transitionalCaX509Certificate),
    CertificateFormatter.pemOf(transitionalCaKeyPair.getPrivate()),
    null,
    true,
    true,
    false,
    true);

  generationParameters.setKeyLength(4096);
  final CertificateGenerationParameters params = new CertificateGenerationParameters(generationParameters);

  when(
    signedCertificateGenerator
      .getSignedByIssuer(childCertificateKeyPair, params, rootCaX509Certificate, rootCaKeyPair.getPrivate())
  ).thenReturn(childX509Certificate);

  when(certificateAuthorityService.findTransitionalVersion("/my-ca-name")).thenReturn(transitionalCa);

  final CertificateCredentialValue certificateWithTrustedCa = subject.generateCredential(inputParameters);

  assertThat(certificateWithTrustedCa.getCa(),
    equalTo(rootCa.getCertificate()));

  assertThat(certificateWithTrustedCa.getTrustedCa(),
    equalTo(transitionalCa.getCertificate()));
}
 
Example #8
Source File: DefaultCertificateVersionDataServiceTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeEach() {
  if (Security.getProvider(BouncyCastleFipsProvider.PROVIDER_NAME) == null) {
    Security.addProvider(new BouncyCastleFipsProvider());
  }

  versionRepository = mock(CredentialVersionRepository.class);
  factory = mock(CredentialFactory.class);
  dataService = mock(CredentialDataService.class);
  subject = new DefaultCertificateVersionDataService(
    versionRepository,
    factory,
    dataService
  );
}
 
Example #9
Source File: common.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static String calculateHMAC(String secret, String data) {
    try {
        SecretKeySpec signingKey = new SecretKeySpec(Hex.decode(secret), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256", new BouncyCastleFipsProvider());
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(data.getBytes());
        return Base64.toBase64String(rawHmac);
    } catch (NoSuchAlgorithmException | InvalidKeyException | IllegalStateException ex) {
        System.out.println("Unexpected error while creating hash: " + ex.getMessage());
        throw new IllegalArgumentException();
    }
}
 
Example #10
Source File: CertificateSetAndRegenerateTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
@Test
public void certificateSetRequest_returnsWithExpiryDate() throws Exception {
    final String setJson = JSONObject.toJSONString(
            ImmutableMap.<String, String>builder()
                    .put("ca_name", "")
                    .put("certificate", TEST_CERTIFICATE)
                    .put("private_key", TEST_PRIVATE_KEY)
                    .build());

    final MockHttpServletRequestBuilder certificateSetRequest = put("/api/v1/data")
            .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
            .accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON)
            //language=JSON
            .content("{\n"
                    + "  \"name\" : \"/certificate\",\n"
                    + "  \"type\" : \"certificate\",\n"
                    + "  \"value\" : " + setJson + "}");

    final X509Certificate certificate = (X509Certificate) CertificateFactory
            .getInstance("X.509", BouncyCastleFipsProvider.PROVIDER_NAME)
            .generateCertificate(new ByteArrayInputStream(TEST_CERTIFICATE.getBytes(UTF_8)));

    this.mockMvc.perform(certificateSetRequest)
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.expiry_date", equalTo(certificate.getNotAfter().toInstant().toString())));
}
 
Example #11
Source File: JWTTest.java    From fusionauth-jwt with Apache License 2.0 5 votes vote down vote up
@Test
public void test_ES256_BC_FIPS() {
  Security.addProvider(new BouncyCastleFipsProvider());
  String encodedJWT = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkifQ.vPn7xrCNOLWbBRaWdVn53ddj2hW0E87FYl4gPnWy5d1Qj3WgyF8FS6I_hj_3kIJ77tbvy0GXdr7fO91NeWMD1A";
  Verifier verifier = ECVerifier.newVerifier(Paths.get("src/test/resources/ec_public_key_p_256.pem"), new BCFIPSCryptoProvider());
  JWT jwt = JWT.getDecoder().decode(encodedJWT, verifier);
  assertEquals(jwt.subject, "123456789");

  // Re-test using a pre-built EC Public Key
  assertEquals(JWT.getDecoder().decode(encodedJWT, ECVerifier.newVerifier((ECPublicKey) PEM.decode(Paths.get("src/test/resources/ec_public_key_p_256.pem")).getPublicKey())).subject, "123456789");
}
 
Example #12
Source File: GenericCryptoModule.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Constructor for the class.
 *
 * @param cryptomodule - The hardware cryptographic module
 */
public GenericCryptoModule(CryptoModule cryptomodule) {
    Security.addProvider(new BouncyCastleFipsProvider());
    if (fipsmode) {
        CryptoServicesRegistrar.setApprovedOnlyMode(true);
    }
    this.cryptomodule = cryptomodule;
}
 
Example #13
Source File: GenericCryptoModule.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Constructor for the class.
 *
 * @param cryptomodule - The hardware cryptographic module
 * @param fipsmode - The fipsmode to set
 */
public GenericCryptoModule(CryptoModule cryptomodule, Boolean fipsmode) {
    Security.addProvider(new BouncyCastleFipsProvider());
    if (fipsmode) {
        CryptoServicesRegistrar.setApprovedOnlyMode(true);
    }
    this.cryptomodule = cryptomodule;
}
 
Example #14
Source File: common.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static String calculateHMAC(String secret, String data) {
    try {
        SecretKeySpec signingKey = new SecretKeySpec(Hex.decode(secret), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256", new BouncyCastleFipsProvider());
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(data.getBytes());
        return Base64.toBase64String(rawHmac);
    } catch (NoSuchAlgorithmException | InvalidKeyException | IllegalStateException ex) {
        System.out.println("Unexpected error while creating hash: " + ex.getMessage());
        throw new IllegalArgumentException();
    }
}
 
Example #15
Source File: EncryptionUtils.java    From snowflake-kafka-connector with Apache License 2.0 5 votes vote down vote up
public static PrivateKey parseEncryptedPrivateKey(String key, String passphrase)
{
  //remove header, footer, and line breaks
  key = key.replaceAll("-+[A-Za-z ]+-+", "");
  key = key.replaceAll("\\s", "");

  StringBuilder builder = new StringBuilder();
  builder.append("-----BEGIN ENCRYPTED PRIVATE KEY-----");
  for (int i = 0; i < key.length(); i++)
  {
    if (i % 64 == 0)
    {
      builder.append("\n");
    }
    builder.append(key.charAt(i));
  }
  builder.append("\n-----END ENCRYPTED PRIVATE KEY-----");
  key = builder.toString();
  Security.addProvider(new BouncyCastleFipsProvider());
  try
  {
    PEMParser pemParser = new PEMParser(new StringReader(key));
    PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo =
      (PKCS8EncryptedPrivateKeyInfo) pemParser.readObject();
    pemParser.close();
    InputDecryptorProvider pkcs8Prov =
      new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passphrase.toCharArray());
    JcaPEMKeyConverter converter =
      new JcaPEMKeyConverter().setProvider(BouncyCastleFipsProvider.PROVIDER_NAME);
    PrivateKeyInfo decryptedPrivateKeyInfo =
      encryptedPrivateKeyInfo.decryptPrivateKeyInfo(pkcs8Prov);
    return converter.getPrivateKey(decryptedPrivateKeyInfo);
  } catch (Exception e)
  {
    throw SnowflakeErrors.ERROR_0018.getException(e);
  }
}
 
Example #16
Source File: FIPSTest.java    From snowflake-kafka-connector with Apache License 2.0 5 votes vote down vote up
public static String generateAESKey(PrivateKey key, char[] passwd) throws IOException, OperatorCreationException
{
  Security.addProvider(new BouncyCastleFipsProvider());
  StringWriter writer = new StringWriter();
  JcaPEMWriter pemWriter = new JcaPEMWriter(writer);
  PKCS8EncryptedPrivateKeyInfoBuilder pkcs8EncryptedPrivateKeyInfoBuilder =
    new JcaPKCS8EncryptedPrivateKeyInfoBuilder(key);
  pemWriter.writeObject(pkcs8EncryptedPrivateKeyInfoBuilder
    .build(new JcePKCSPBEOutputEncryptorBuilder(NISTObjectIdentifiers.id_aes256_CBC)
      .setProvider("BCFIPS").build(passwd)));
  pemWriter.close();
  return writer.toString();
}
 
Example #17
Source File: JWTTest.java    From fusionauth-jwt with Apache License 2.0 5 votes vote down vote up
@Test
public void test_RS256_BC_FIPS() throws Exception {
  Security.addProvider(new BouncyCastleFipsProvider());
  JWT jwt = new JWT().setSubject("123456789");
  Signer signer = RSASigner.newSHA256Signer(new String(Files.readAllBytes(Paths.get("src/test/resources/rsa_private_key_4096.pem"))), new BCFIPSCryptoProvider());

  assertEquals(JWT.getEncoder().encode(jwt, signer), "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkifQ.kRXJkOHC98D0LCT2oPg5fTmQJDFXkMRQJopbt7QM6prmQDHwjJL_xO-_EXRXnbvf5NLORto45By3XNn2ZzWmY3pAOxj46MlQ5elhROx2S-EnHZNLfQhoG8ZXPZ54q-Obz_6K7ZSlkAQ8jmeZUO3Ryi8jRlHQ2PT4LbBtLpaf982SGJfeTyUMw1LbvowZUTZSF-E6JARaokmmx8M2GeLuKcFhU-YsBTXUarKp0IJCy3jpMQ2zW_HGjyVWH8WwSIbSdpBn7ztoQEJYO-R5H3qVaAz2BsTuGLRxoyIu1iy2-QcDp5uTufmX1roXM8ciQMpcfwKGiyNpKVIZm-lF8aROXRL4kk4rqp6KUzJuOPljPXRU--xKSua-DeR0BEerKzI9hbwIMWiblCslAciNminoSc9G7pUyVwV5Z5IT8CGJkVgoyVGELeBmYCDy7LHwXrr0poc0hPbE3mJXhzolga4BB84nCg2Hb9tCNiHU8F-rKgZWCONaSSIdhQ49x8OiPafFh2DJBEBe5Xbm6xdCfh3KVG0qe4XL18R5s98aIP9UIC4i62UEgPy6W7Fr7QgUxpXrjRCERBV3MiNu4L8NNJb3oZleq5lQi72EfdS-Bt8ZUOVInIcAvSmu-3i8jB_2sF38XUXdl8gkW8k_b9dJkzDcivCFehvSqGmm3vBm5X4bNmk");
}
 
Example #18
Source File: BouncyCastleProviderConfigurationTest.java    From credhub with Apache License 2.0 4 votes vote down vote up
@Before
public void beforeEach() throws Exception {
  generator = KeyPairGenerator
    .getInstance("RSA", BouncyCastleFipsProvider.PROVIDER_NAME);
  generator.initialize(1024);
}
 
Example #19
Source File: CertificateReader.java    From credhub with Apache License 2.0 4 votes vote down vote up
private X509Certificate parseStringIntoCertificate(final String pemString) throws CertificateException, NoSuchProviderException {
  return (X509Certificate) CertificateFactory
    .getInstance("X.509", BouncyCastleFipsProvider.PROVIDER_NAME)
    .generateCertificate(new ByteArrayInputStream(pemString.getBytes(UTF_8)));
}
 
Example #20
Source File: CertificateReaderTest.java    From credhub with Apache License 2.0 4 votes vote down vote up
@Before
public void beforeEach() {
  if (Security.getProvider(BouncyCastleFipsProvider.PROVIDER_NAME) == null) {
    Security.addProvider(new BouncyCastleFipsProvider());
  }
}
 
Example #21
Source File: DefaultCertificateServiceTest.java    From credhub with Apache License 2.0 4 votes vote down vote up
@Before
public void beforeEach() {
  if (Security.getProvider(BouncyCastleFipsProvider.PROVIDER_NAME) == null) {
    Security.addProvider(new BouncyCastleFipsProvider());
  }

  uuid = UUID.randomUUID();
  credentialService = mock(DefaultCredentialService.class);
  certificateDataService = mock(CertificateDataService.class);
  certificateDataService = mock(CertificateDataService.class);
  userContextHolder = mock(UserContextHolder.class);
  certificateVersionDataService = mock(DefaultCertificateVersionDataService.class);
  certificateCredentialFactory = mock(CertificateCredentialFactory.class);
  credentialVersionDataService = mock(CredentialVersionDataService.class);
  userContext = mock(UserContext.class);
  when(userContext.getActor()).thenReturn(actor);
  when(userContextHolder.getUserContext()).thenReturn(userContext);
  subjectWithoutConcatenateCas = new DefaultCertificateService(
    credentialService,
    certificateDataService,
    certificateVersionDataService,
    certificateCredentialFactory,
    credentialVersionDataService,
    new CEFAuditRecord(), false
  );
  subjectWithConcatenateCas = new DefaultCertificateService(
    credentialService,
    certificateDataService,
    certificateVersionDataService,
    certificateCredentialFactory,
    credentialVersionDataService,
    new CEFAuditRecord(), true
  );

  certVersionUuid = UUID.randomUUID();
  newCertVersionUuid = UUID.randomUUID();
  caUuid = UUID.randomUUID();
  certUuid = UUID.randomUUID();
  nonTransitionalVersionId = UUID.randomUUID();
  transitionalVersionId = UUID.randomUUID();

  credential = mock(Credential.class);
  when(credential.getName()).thenReturn("some-ca");
  when(credential.getUuid()).thenReturn(caUuid);

  childCredential = mock(Credential.class);
  when(childCredential.getName()).thenReturn("some-cert");
  when(childCredential.getUuid()).thenReturn(certUuid);

  value = mock(CertificateCredentialValue.class);
  when(value.getCa()).thenReturn(TestConstants.TEST_CA);
  when(value.getCertificate()).thenReturn(TestConstants.TEST_CERTIFICATE);
  when(value.getPrivateKey()).thenReturn(TestConstants.TEST_PRIVATE_KEY);
  when(value.getCaName()).thenReturn("some-ca");
  when(value.getGenerated()).thenReturn(true);

  nonTransitionalCa = mock(CertificateCredentialVersion.class);
  when(nonTransitionalCa.getCertificate())
    .thenReturn(TestConstants.TEST_CERTIFICATE);
  when(nonTransitionalCa.isVersionTransitional()).thenReturn(false);
  when(nonTransitionalCa.getName()).thenReturn("some-ca");
  when(nonTransitionalCa.getUuid()).thenReturn(nonTransitionalVersionId);
  when(nonTransitionalCa.getCredential()).thenReturn(credential);

  transitionalCa = mock(CertificateCredentialVersion.class);
  when(transitionalCa.getCertificate())
    .thenReturn(TestConstants.OTHER_TEST_CERTIFICATE);
  when(transitionalCa.isVersionTransitional()).thenReturn(true);
  when(transitionalCa.getName()).thenReturn("some-ca");
  when(transitionalCa.getUuid()).thenReturn(transitionalVersionId);
  when(transitionalCa.getCredential()).thenReturn(credential);

  childCert = mock(CertificateCredentialVersion.class);
  when(childCert.getCaName()).thenReturn("some-ca");
  when(childCert.getCredential()).thenReturn(childCredential);
  when(childCert.getName()).thenReturn("some-cert");
  when(childCert.getUuid()).thenReturn(certVersionUuid);
  when(childCert.getCertificate()).thenReturn(TestConstants.TEST_CERTIFICATE);
  when(childCert.getPrivateKey()).thenReturn(TestConstants.TEST_PRIVATE_KEY);
  when(childCert.getGenerated()).thenReturn(true);
  when(childCert.getValue()).thenReturn(value);


  newChildCert = mock(CertificateCredentialVersion.class);
  when(newChildCert.getCaName()).thenReturn("some-ca");
  when(newChildCert.getName()).thenReturn("some-cert");
  when(newChildCert.getUuid()).thenReturn(newCertVersionUuid);
  when(newChildCert.getValue()).thenReturn(value);
}
 
Example #22
Source File: ConnectionFipsIT.java    From snowflake-jdbc with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setup() throws Exception {
    System.setProperty("javax.net.debug", "ssl");
    // get keystore types for BouncyCastle libraries
    JAVA_SYSTEM_PROPERTY_SSL_KEYSTORE_TYPE_ORIGINAL_VALUE =
            System.getProperty(JAVA_SYSTEM_PROPERTY_SSL_KEYSTORE_TYPE);
    JAVA_SYSTEM_PROPERTY_SSL_TRUSTSTORE_TYPE_ORIGINAL_VALUE =
            System.getProperty(JAVA_SYSTEM_PROPERTY_SSL_TRUSTSTORE_TYPE);

    // set keystore types for BouncyCastle libraries
    System.setProperty(JAVA_SYSTEM_PROPERTY_SSL_KEYSTORE_TYPE,
            JCE_KEYSTORE_BOUNCY_CASTLE);
    System.setProperty(JAVA_SYSTEM_PROPERTY_SSL_TRUSTSTORE_TYPE,
            JCE_KEYSTORE_JKS);
    // remove Java's standard encryption and SSL providers
    List<Provider> providers = Arrays.asList(Security.getProviders());
    JCE_PROVIDER_SUN_JCE_PROVIDER_VALUE = Security.getProvider(JCE_PROVIDER_SUN_JCE);
    JCE_PROVIDER_SUN_JCE_PROVIDER_POSITION = providers.indexOf(JCE_PROVIDER_SUN_JCE_PROVIDER_VALUE);
    JCE_PROVIDER_SUN_RSA_SIGN_PROVIDER_VALUE = Security.getProvider(JCE_PROVIDER_SUN_RSA_SIGN);
    JCE_PROVIDER_SUN_RSA_SIGN_PROVIDER_POSITION = providers.indexOf(JCE_PROVIDER_SUN_RSA_SIGN_PROVIDER_VALUE);
    Security.removeProvider(JCE_PROVIDER_SUN_JCE);
    Security.removeProvider(JCE_PROVIDER_SUN_RSA_SIGN);

    // workaround to connect to accounts.google.com over HTTPS, which consists
    // of disabling TLS 1.3 and disabling default SSL cipher suites that are
    // using CHACHA20_POLY1305 algorithms
    JAVA_SYSTEM_PROPERTY_SSL_PROTOCOLS_ORIGINAL_VALUE =
            System.getProperty(JAVA_SYSTEM_PROPERTY_SSL_PROTOCOLS);
    JAVA_SYSTEM_PROPERTY_SSL_CIPHERSUITES_ORIGINAL_VALUE =
            System.getProperty(JAVA_SYSTEM_PROPERTY_SSL_CIPHERSUITES);
    System.setProperty(JAVA_SYSTEM_PROPERTY_SSL_PROTOCOLS,
            SSL_ENABLED_PROTOCOLS);
    System.setProperty(JAVA_SYSTEM_PROPERTY_SSL_CIPHERSUITES,
            SSL_ENABLED_CIPHERSUITES);
    /*
     * Insert BouncyCastle's FIPS-compliant encryption and SSL providers.
     */
    BouncyCastleFipsProvider bcFipsProvider =
            new BouncyCastleFipsProvider(BOUNCY_CASTLE_RNG_HYBRID_MODE);

    /*
     * We remove BCFIPS provider pessimistically. This is a no-op if provider
     * does not exist. This is necessary to always add it to the first
     * position when calling insertProviderAt.
     *
     * JavaDoc for insertProviderAt states:
     *   "A provider cannot be added if it is already installed."
     */
    Security.removeProvider(JCE_PROVIDER_BOUNCY_CASTLE_FIPS);
    Security.insertProviderAt(bcFipsProvider, 1);
    if (!CryptoServicesRegistrar.isInApprovedOnlyMode()) {
        if (FipsStatus.isReady()) {
            CryptoServicesRegistrar.setApprovedOnlyMode(true);
        } else {
            throw new RuntimeException("FIPS is not ready to be enabled and FIPS " +
                    "mode is required for this test to run");
        }
    }

    // attempts an SSL connection to Google
    connectToGoogle();
}
 
Example #23
Source File: BaseTest.java    From fusionauth-jwt with Apache License 2.0 4 votes vote down vote up
@AfterMethod
public void afterMethod() {
  Security.removeProvider(BouncyCastleFipsProvider.PROVIDER_NAME);
}
 
Example #24
Source File: CertificateGeneratorTest.java    From credhub with Apache License 2.0 4 votes vote down vote up
@Before
public void beforeEach() throws Exception {
  TestHelper.getBouncyCastleFipsProvider();
  keyGenerator = mock(RsaKeyPairGenerator.class);
  signedCertificateGenerator = mock(SignedCertificateGenerator.class);
  certificateAuthorityService = mock(DefaultCertificateAuthorityService.class);

  subject = new CertificateGenerator(
    keyGenerator,
    signedCertificateGenerator,
    certificateAuthorityService
  );


  fakeKeyPairGenerator = new FakeKeyPairGenerator();

  rootCaDn = new X500Name("O=foo,ST=bar,C=root");
  signeeDn = new X500Name("O=foo,ST=bar,C=mars");
  rootCaKeyPair = fakeKeyPairGenerator.generate();
  final X509CertificateHolder caX509CertHolder = makeCert(rootCaKeyPair, rootCaKeyPair.getPrivate(),
    rootCaDn, rootCaDn, true);
  rootCaX509Certificate = new JcaX509CertificateConverter()
    .setProvider(BouncyCastleFipsProvider.PROVIDER_NAME).getCertificate(caX509CertHolder);
  rootCa = new CertificateCredentialValue(
    null,
    CertificateFormatter.pemOf(rootCaX509Certificate),
    CertificateFormatter.pemOf(rootCaKeyPair.getPrivate()),
    null,
    true,
    true,
    false,
    false);

  generationParameters = new CertificateGenerationRequestParameters();
  generationParameters.setOrganization("foo");
  generationParameters.setState("bar");
  generationParameters.setCaName("my-ca-name");
  generationParameters.setCountry("mars");
  generationParameters.setDuration(365);

  inputParameters = new CertificateGenerationParameters(generationParameters);
}
 
Example #25
Source File: CertificateGeneratorTest.java    From credhub with Apache License 2.0 4 votes vote down vote up
@Test
public void whenCAExists_andItIsAIntermediateCA_aValidChildCertificateIsGenerated()
  throws Exception {
  final KeyPair childCertificateKeyPair = setupKeyPair();

  final X500Name intermediateCaDn = new X500Name("O=foo,ST=bar,C=intermediate");
  final KeyPair intermediateCaKeyPair = fakeKeyPairGenerator.generate();
  final X509CertificateHolder intermediateCaCertificateHolder = makeCert(intermediateCaKeyPair,
    rootCaKeyPair.getPrivate(), rootCaDn, intermediateCaDn, true);
  final X509Certificate intermediateX509Certificate = new JcaX509CertificateConverter()
    .setProvider(BouncyCastleFipsProvider.PROVIDER_NAME)
    .getCertificate(intermediateCaCertificateHolder);
  final CertificateCredentialValue intermediateCa = new CertificateCredentialValue(
    null,
    CertificateFormatter.pemOf(intermediateX509Certificate),
    CertificateFormatter.pemOf(intermediateCaKeyPair.getPrivate()),
    null,
    true,
    false,
    false,
    false);
  when(certificateAuthorityService.findActiveVersion("/my-ca-name")).thenReturn(intermediateCa);

  when(keyGenerator.generateKeyPair(anyInt())).thenReturn(childCertificateKeyPair);

  final X509CertificateHolder childCertificateHolder = generateChildCertificateSignedByCa(
    childCertificateKeyPair,
    intermediateCaKeyPair.getPrivate(),
    intermediateCaDn
  );

  childX509Certificate = new JcaX509CertificateConverter()
    .setProvider(BouncyCastleFipsProvider.PROVIDER_NAME)
    .getCertificate(childCertificateHolder);

  when(
    signedCertificateGenerator
      .getSignedByIssuer(childCertificateKeyPair, inputParameters, intermediateX509Certificate, intermediateCaKeyPair.getPrivate())
  ).thenReturn(childX509Certificate);


  final CertificateCredentialValue certificateSignedByIntermediate = subject.generateCredential(inputParameters);

  assertThat(certificateSignedByIntermediate.getCa(),
    equalTo(intermediateCa.getCertificate()));

  assertThat(certificateSignedByIntermediate.getPrivateKey(),
    equalTo(CertificateFormatter.pemOf(childCertificateKeyPair.getPrivate())));

  assertThat(certificateSignedByIntermediate.getCertificate(),
    equalTo(CertificateFormatter.pemOf(childX509Certificate)));

  verify(keyGenerator, times(1)).generateKeyPair(2048);
}
 
Example #26
Source File: BouncyCastleProviderConfiguration.java    From credhub with Apache License 2.0 4 votes vote down vote up
@Bean
public JcaX509CertificateConverter jcaX509CertificateConverter(final BouncyCastleFipsProvider jceProvider) {
  return new JcaX509CertificateConverter().setProvider(jceProvider);
}
 
Example #27
Source File: BouncyCastleProviderConfiguration.java    From credhub with Apache License 2.0 4 votes vote down vote up
@Bean
public JcaContentSignerBuilder jcaContentSignerBuilder(final BouncyCastleFipsProvider jceProvider) {
  return new JcaContentSignerBuilder("SHA256withRSA").setProvider(jceProvider);
}
 
Example #28
Source File: DefaultRegenerateHandlerTest.java    From credhub with Apache License 2.0 4 votes vote down vote up
@Before
public void beforeEach() {
  if (Security.getProvider(BouncyCastleFipsProvider.PROVIDER_NAME) == null) {
    Security.addProvider(new BouncyCastleFipsProvider());
  }
  credentialService = mock(DefaultCredentialService.class);
  credentialGenerator = mock(UniversalCredentialGenerator.class);
  generationRequestGenerator = mock(GenerationRequestGenerator.class);
  credentialVersion = mock(PasswordCredentialVersion.class);
  cefAuditRecord = mock(CEFAuditRecord.class);
  permissionCheckingService = mock(PermissionCheckingService.class);
  UserContextHolder userContextHolder = mock(UserContextHolder.class);
  credValue = new StringCredentialValue("secret");
  subjectWithAclsEnabled = new DefaultRegenerateHandler(
    credentialService,
    credentialGenerator,
    generationRequestGenerator,
    cefAuditRecord,
    permissionCheckingService,
    userContextHolder,
    true,
    false
    );
  subjectWithAclsDisabled = new DefaultRegenerateHandler(
    credentialService,
    credentialGenerator,
    generationRequestGenerator,
    cefAuditRecord,
    permissionCheckingService,
    userContextHolder,
    false,
    false
    );
  subjectWithconcatenateCasDisabled = new DefaultRegenerateHandler(
    credentialService,
    credentialGenerator,
    generationRequestGenerator,
    cefAuditRecord,
    permissionCheckingService,
    userContextHolder,
    false,
    false
  );
  subjectWithConcatenateCasEnabled = new DefaultRegenerateHandler(
    credentialService,
    credentialGenerator,
    generationRequestGenerator,
    cefAuditRecord,
    permissionCheckingService,
    userContextHolder,
    false,
    true
  );

  UserContext userContext = mock(UserContext.class);
  when(userContext.getActor()).thenReturn(USER);
  when(userContextHolder.getUserContext()).thenReturn(userContext);
}
 
Example #29
Source File: SignedCertificateGeneratorTest.java    From credhub with Apache License 2.0 4 votes vote down vote up
@Before
public void beforeEach() throws Exception {
  timeProvider = mock(CurrentTimeProvider.class);
  now = Instant.ofEpochMilli(1493066824);
  later = now.plus(Duration.ofDays(expectedDurationInDays));
  when(timeProvider.getInstant()).thenReturn(now);
  serialNumberGenerator = mock(RandomSerialNumberGenerator.class);
  when(serialNumberGenerator.generate()).thenReturn(BigInteger.valueOf(1337));
  jcaX509ExtensionUtils = new JcaX509ExtensionUtils();

  generator = KeyPairGenerator
    .getInstance("RSA", BouncyCastleFipsProvider.PROVIDER_NAME);
  generator.initialize(1024); // doesn't matter for testing
  issuerKey = generator.generateKeyPair();

  issuerDn = new X500Principal(caName);
  generatedCertificateKeyPair = generator.generateKeyPair();
  certificateGenerationParameters = defaultCertificateParameters();

  subject = new SignedCertificateGenerator(timeProvider,
    serialNumberGenerator,
    jcaContentSignerBuilder,
    jcaX509CertificateConverter
  );

  caSubjectKeyIdentifier =
    jcaX509ExtensionUtils.createSubjectKeyIdentifier(issuerKey.getPublic());

  caSerialNumber = BigInteger.valueOf(42L);
  final JcaX509v3CertificateBuilder x509v3CertificateBuilder = new JcaX509v3CertificateBuilder(
    issuerDn,
    caSerialNumber,
    Date.from(now),
    Date.from(later),
    issuerDn,
    issuerKey.getPublic()
  );

  certificateAuthority = createCertificateAuthority(x509v3CertificateBuilder);

  x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, caSubjectKeyIdentifier);
  certificateAuthorityWithSubjectKeyId = createCertificateAuthority(x509v3CertificateBuilder);
  expectedSubjectKeyIdentifier = certificateAuthorityWithSubjectKeyId.getExtensionValue(Extension.subjectKeyIdentifier.getId());
}
 
Example #30
Source File: DefaultCertificatesHandlerTest.java    From credhub with Apache License 2.0 4 votes vote down vote up
@Before
public void beforeEach() {
  if (Security.getProvider(BouncyCastleFipsProvider.PROVIDER_NAME) == null) {
    Security.addProvider(new BouncyCastleFipsProvider());
  }

  permissionCheckingService = mock(PermissionCheckingService.class);
  userContextHolder = mock(UserContextHolder.class);
  UserContext userContext = mock(UserContext.class);
  when(userContext.getActor()).thenReturn(USER);
  when(userContextHolder.getUserContext()).thenReturn(userContext);
  certificateService = mock(DefaultCertificateService.class);
  universalCredentialGenerator = mock(UniversalCredentialGenerator.class);
  generationRequestGenerator = mock(GenerationRequestGenerator.class);
  subjectWithAcls = new DefaultCertificatesHandler(
    certificateService,
    universalCredentialGenerator,
    generationRequestGenerator,
    new CEFAuditRecord(),
    permissionCheckingService,
    userContextHolder,
    true,
    false
  );
  subjectWithoutAcls = new DefaultCertificatesHandler(
    certificateService,
    universalCredentialGenerator,
    generationRequestGenerator,
    new CEFAuditRecord(),
    permissionCheckingService,
    userContextHolder,
    false,
    false
  );
  subjectWithConcatenateCas = new DefaultCertificatesHandler(
    certificateService,
    universalCredentialGenerator,
    generationRequestGenerator,
    new CEFAuditRecord(),
    permissionCheckingService,
    userContextHolder,
    false,
    true
  );
  subjectWithoutConcatenateCas = new DefaultCertificatesHandler(
    certificateService,
    universalCredentialGenerator,
    generationRequestGenerator,
    new CEFAuditRecord(),
    permissionCheckingService,
    userContextHolder,
    false,
    false
  );
}