Search in sources :

Example 1 with KeyPair

use of java.security.KeyPair in project OpenAttestation by OpenAttestation.

the class CertificateUtils method generateSelfSignedX509Certificate.

/**
	 * Generate a self signed X509 certificate with Bouncy Castle.
	 * @throws SignatureException 
	 * @throws IllegalStateException 
	 * @throws InvalidKeyException 
	 * @throws CertificateEncodingException 
	 */
public static X509Certificate generateSelfSignedX509Certificate() throws NoSuchAlgorithmException, NoSuchProviderException, CertificateEncodingException, InvalidKeyException, IllegalStateException, SignatureException {
    Security.addProvider(new BouncyCastleProvider());
    int validityDays = 3652;
    // GENERATE THE PUBLIC/PRIVATE RSA KEY PAIR
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
    keyPairGenerator.initialize(1024, new SecureRandom());
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    // GENERATE THE X509 CERTIFICATE
    X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
    X500Principal dnName = new X500Principal("CN=OATServer");
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setSubjectDN(dnName);
    // use the same
    certGen.setIssuerDN(dnName);
    certGen.setNotBefore(new java.sql.Time(System.currentTimeMillis()));
    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, validityDays);
    certGen.setNotAfter(expiry.getTime());
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
    X509Certificate cert = certGen.generate(keyPair.getPrivate(), "BC");
    return cert;
}
Also used : KeyPair(java.security.KeyPair) X509V1CertificateGenerator(org.bouncycastle.x509.X509V1CertificateGenerator) Calendar(java.util.Calendar) SecureRandom(java.security.SecureRandom) X500Principal(javax.security.auth.x500.X500Principal) KeyPairGenerator(java.security.KeyPairGenerator) X509Certificate(java.security.cert.X509Certificate) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 2 with KeyPair

use of java.security.KeyPair in project OpenAttestation by OpenAttestation.

the class Diagnostic method trySignature.

private static void trySignature() {
    String algorithmName = "SHA1withRSA";
    try {
        // generate keypair
        // NoSuchAlgorithmException, NoSuchProviderException
        KeyPair keyPair = KeyPairGenerator.getInstance("RSA", "BC").generateKeyPair();
        PrivateKey privateKey = keyPair.getPrivate();
        String plaintext = "This is the message being signed";
        // generate signature
        // NoSuchAlgorithmException, NoSuchProviderException
        Signature instance = Signature.getInstance("SHA1withRSAEncryption", "BC");
        // InvalidKeyException
        instance.initSign(privateKey);
        // SignatureException
        instance.update((plaintext).getBytes());
        byte[] signature = instance.sign();
        System.out.println("Generated SHA1 with RSA signature of length: " + signature.length);
    } catch (NoSuchProviderException e) {
        System.err.println("Cannot use provider: BC: " + e.toString());
    } catch (NoSuchAlgorithmException e) {
        System.err.println("Cannot use algorithm: " + algorithmName + ": " + e.toString());
    } catch (InvalidKeyException e) {
        System.err.println("Cannot use key: " + e.toString());
    } catch (SignatureException e) {
        System.err.println("Cannot generate signature: " + e.toString());
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) Signature(java.security.Signature) JDKDigestSignature(org.bouncycastle.jce.provider.JDKDigestSignature) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) NoSuchProviderException(java.security.NoSuchProviderException) InvalidKeyException(java.security.InvalidKeyException)

Example 3 with KeyPair

use of java.security.KeyPair in project hadoop by apache.

the class TestReloadingX509TrustManager method testReload.

@Test(timeout = 30000)
public void testReload() throws Exception {
    KeyPair kp = generateKeyPair("RSA");
    cert1 = generateCertificate("CN=Cert1", kp, 30, "SHA1withRSA");
    cert2 = generateCertificate("CN=Cert2", kp, 30, "SHA1withRSA");
    String truststoreLocation = BASEDIR + "/testreload.jks";
    createTrustStore(truststoreLocation, "password", "cert1", cert1);
    final ReloadingX509TrustManager tm = new ReloadingX509TrustManager("jks", truststoreLocation, "password", 10);
    try {
        tm.init();
        assertEquals(1, tm.getAcceptedIssuers().length);
        // Wait so that the file modification time is different
        Thread.sleep((tm.getReloadInterval() + 1000));
        // Add another cert
        Map<String, X509Certificate> certs = new HashMap<String, X509Certificate>();
        certs.put("cert1", cert1);
        certs.put("cert2", cert2);
        createTrustStore(truststoreLocation, "password", certs);
        GenericTestUtils.waitFor(new Supplier<Boolean>() {

            @Override
            public Boolean get() {
                return tm.getAcceptedIssuers().length == 2;
            }
        }, (int) tm.getReloadInterval(), 10000);
    } finally {
        tm.destroy();
    }
}
Also used : KeyPair(java.security.KeyPair) KeyStoreTestUtil.generateKeyPair(org.apache.hadoop.security.ssl.KeyStoreTestUtil.generateKeyPair) HashMap(java.util.HashMap) X509Certificate(java.security.cert.X509Certificate) Test(org.junit.Test)

Example 4 with KeyPair

use of java.security.KeyPair in project hadoop by apache.

the class TestReloadingX509TrustManager method testReloadCorruptTrustStore.

@Test(timeout = 30000)
public void testReloadCorruptTrustStore() throws Exception {
    KeyPair kp = generateKeyPair("RSA");
    cert1 = generateCertificate("CN=Cert1", kp, 30, "SHA1withRSA");
    cert2 = generateCertificate("CN=Cert2", kp, 30, "SHA1withRSA");
    String truststoreLocation = BASEDIR + "/testcorrupt.jks";
    createTrustStore(truststoreLocation, "password", "cert1", cert1);
    ReloadingX509TrustManager tm = new ReloadingX509TrustManager("jks", truststoreLocation, "password", 10);
    try {
        tm.init();
        assertEquals(1, tm.getAcceptedIssuers().length);
        final X509Certificate cert = tm.getAcceptedIssuers()[0];
        // Wait so that the file modification time is different
        Thread.sleep((tm.getReloadInterval() + 1000));
        assertFalse(reloaderLog.getOutput().contains(ReloadingX509TrustManager.RELOAD_ERROR_MESSAGE));
        OutputStream os = new FileOutputStream(truststoreLocation);
        os.write(1);
        os.close();
        waitForFailedReloadAtLeastOnce((int) tm.getReloadInterval());
        assertEquals(1, tm.getAcceptedIssuers().length);
        assertEquals(cert, tm.getAcceptedIssuers()[0]);
    } finally {
        reloaderLog.stopCapturing();
        tm.destroy();
    }
}
Also used : KeyPair(java.security.KeyPair) KeyStoreTestUtil.generateKeyPair(org.apache.hadoop.security.ssl.KeyStoreTestUtil.generateKeyPair) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) X509Certificate(java.security.cert.X509Certificate) Test(org.junit.Test)

Example 5 with KeyPair

use of java.security.KeyPair in project hadoop by apache.

the class TestSSLFactory method checkSSLFactoryInitWithPasswords.

/**
   * Checks that SSLFactory initialization is successful with the given
   * arguments.  This is a helper method for writing test cases that cover
   * different combinations of settings for the store password and key password.
   * It takes care of bootstrapping a keystore, a truststore, and SSL client or
   * server configuration.  Then, it initializes an SSLFactory.  If no exception
   * is thrown, then initialization was successful.
   *
   * @param mode SSLFactory.Mode mode to test
   * @param password String store password to set on keystore
   * @param keyPassword String key password to set on keystore
   * @param confPassword String store password to set in SSL config file, or null
   *   to avoid setting in SSL config file
   * @param confKeyPassword String key password to set in SSL config file, or
   *   null to avoid setting in SSL config file
   * @param useCredProvider boolean to indicate whether passwords should be set
   * into the config or not. When set to true nulls are set and aliases are
   * expected to be resolved through credential provider API through the
   * Configuration.getPassword method
   * @throws Exception for any error
   */
private void checkSSLFactoryInitWithPasswords(SSLFactory.Mode mode, String password, String keyPassword, String confPassword, String confKeyPassword, boolean useCredProvider) throws Exception {
    String keystore = new File(KEYSTORES_DIR, "keystore.jks").getAbsolutePath();
    String truststore = new File(KEYSTORES_DIR, "truststore.jks").getAbsolutePath();
    String trustPassword = "trustP";
    // Create keys, certs, keystore, and truststore.
    KeyPair keyPair = KeyStoreTestUtil.generateKeyPair("RSA");
    X509Certificate cert = KeyStoreTestUtil.generateCertificate("CN=Test", keyPair, 30, "SHA1withRSA");
    KeyStoreTestUtil.createKeyStore(keystore, password, keyPassword, "Test", keyPair.getPrivate(), cert);
    Map<String, X509Certificate> certs = Collections.singletonMap("server", cert);
    KeyStoreTestUtil.createTrustStore(truststore, trustPassword, certs);
    // Create SSL configuration file, for either server or client.
    final String sslConfFileName;
    final Configuration sslConf;
    // provider
    if (useCredProvider) {
        confPassword = null;
        confKeyPassword = null;
    }
    if (mode == SSLFactory.Mode.SERVER) {
        sslConfFileName = "ssl-server.xml";
        sslConf = KeyStoreTestUtil.createServerSSLConfig(keystore, confPassword, confKeyPassword, truststore);
        if (useCredProvider) {
            File testDir = GenericTestUtils.getTestDir();
            final Path jksPath = new Path(testDir.toString(), "test.jks");
            final String ourUrl = JavaKeyStoreProvider.SCHEME_NAME + "://file" + jksPath.toUri();
            sslConf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, ourUrl);
        }
    } else {
        sslConfFileName = "ssl-client.xml";
        sslConf = KeyStoreTestUtil.createClientSSLConfig(keystore, confPassword, confKeyPassword, truststore);
    }
    KeyStoreTestUtil.saveConfig(new File(sslConfsDir, sslConfFileName), sslConf);
    // Create the master configuration for use by the SSLFactory, which by
    // default refers to the ssl-server.xml or ssl-client.xml created above.
    Configuration conf = new Configuration();
    conf.setBoolean(SSLFactory.SSL_REQUIRE_CLIENT_CERT_KEY, true);
    // Try initializing an SSLFactory.
    SSLFactory sslFactory = new SSLFactory(mode, conf);
    try {
        sslFactory.init();
    } finally {
        sslFactory.destroy();
    }
}
Also used : Path(org.apache.hadoop.fs.Path) KeyPair(java.security.KeyPair) Configuration(org.apache.hadoop.conf.Configuration) File(java.io.File) X509Certificate(java.security.cert.X509Certificate)

Aggregations

KeyPair (java.security.KeyPair)903 KeyPairGenerator (java.security.KeyPairGenerator)345 Test (org.junit.Test)235 PrivateKey (java.security.PrivateKey)189 X509Certificate (java.security.cert.X509Certificate)185 PublicKey (java.security.PublicKey)167 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)127 IOException (java.io.IOException)121 BigInteger (java.math.BigInteger)87 Date (java.util.Date)78 SecureRandom (java.security.SecureRandom)75 KeyStore (java.security.KeyStore)74 GeneralSecurityException (java.security.GeneralSecurityException)63 RSAPublicKey (java.security.interfaces.RSAPublicKey)55 X500Principal (javax.security.auth.x500.X500Principal)53 File (java.io.File)52 KeyFactory (java.security.KeyFactory)52 ECPrivateKey (java.security.interfaces.ECPrivateKey)52 ECPublicKey (java.security.interfaces.ECPublicKey)52 InvalidKeyException (java.security.InvalidKeyException)40