List of usage examples for java.security KeyPair getPrivate
public PrivateKey getPrivate()
From source file:edu.vt.middleware.crypt.util.CryptReaderWriterTest.java
/** * @return Private key test data./* ww w . ja v a2 s .c om*/ * * @throws Exception On test data generation failure. */ @DataProvider(name = "privkeydata") public Object[][] createPrivKeyTestData() throws Exception { final KeyPairGenerator rsaKeyGen = KeyPairGenerator.getInstance("RSA"); final KeyPair rsaKeys = rsaKeyGen.generateKeyPair(); final KeyPairGenerator dsaKeyGen = KeyPairGenerator.getInstance("DSA"); final KeyPair dsaKeys = dsaKeyGen.generateKeyPair(); return new Object[][] { { rsaKeys.getPrivate(), "S33Kr1t!" }, { dsaKeys.getPrivate(), "S33Kr1t!" }, { rsaKeys.getPrivate(), null }, { dsaKeys.getPrivate(), null }, }; }
From source file:org.guanxi.idp.Bootstrap.java
public boolean createSelfSignedKeystore(String cn, String keystoreFile, String keystorePassword, String privateKeyPassword, String privateKeyAlias) { KeyStore ks = null;/*from w w w.ja v a2 s . co m*/ try { ks = KeyStore.getInstance("JKS"); ks.load(null, null); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); keyGen.initialize(1024, new SecureRandom()); KeyPair keypair = keyGen.generateKeyPair(); PrivateKey privkey = keypair.getPrivate(); PublicKey pubkey = keypair.getPublic(); Hashtable<DERObjectIdentifier, String> attrs = new Hashtable<DERObjectIdentifier, String>(); Vector<DERObjectIdentifier> ordering = new Vector<DERObjectIdentifier>(); ordering.add(X509Name.CN); attrs.put(X509Name.CN, cn); X509Name issuerDN = new X509Name(ordering, attrs); X509Name subjectDN = new X509Name(ordering, attrs); Date validFrom = new Date(); validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000)); Date validTo = new Date(); validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000))); X509V3CertificateGenerator x509 = new X509V3CertificateGenerator(); x509.setSignatureAlgorithm("SHA1withDSA"); x509.setIssuerDN(issuerDN); x509.setSubjectDN(subjectDN); x509.setPublicKey(pubkey); x509.setNotBefore(validFrom); x509.setNotAfter(validTo); x509.setSerialNumber(new BigInteger(128, new Random())); X509Certificate[] cert = new X509Certificate[1]; cert[0] = x509.generate(privkey, "BC"); java.security.cert.Certificate[] chain = new java.security.cert.Certificate[1]; chain[0] = cert[0]; ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), cert); ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), chain); ks.store(new FileOutputStream(keystoreFile), keystorePassword.toCharArray()); String IDP_RFC_CERT = "WEB-INF/guanxi_idp/keystore/guanxi_idp_cert.txt"; PEMWriter pemWriter = new PEMWriter(new FileWriter(servletContext.getRealPath(IDP_RFC_CERT))); pemWriter.writeObject(cert[0]); pemWriter.close(); return true; } catch (Exception se) { return false; } }
From source file:mitm.common.security.ca.SMIMECABuilder.java
@Override public synchronized CABuilderResult buildCA(CABuilderParameters parameters) throws CAException { try {/*from w ww . ja v a2 s . c o m*/ checkState(parameters); KeyPair rootKeyPair = generateKeyPair(parameters.getRootKeyLength()); KeyPair intermediateKeyPair = generateKeyPair(parameters.getIntermediateKeyLength()); Date creationDate = new Date(); X509Certificate root = createCertificate(rootKeyPair.getPublic(), null, rootKeyPair.getPrivate(), parameters.getRootSubject(), parameters.getRootSubject(), parameters.getRootValidity(), creationDate, 1, parameters.getSignatureAlgorithm(), null); X509Certificate intermediate = createCertificate(intermediateKeyPair.getPublic(), root, rootKeyPair.getPrivate(), parameters.getRootSubject(), parameters.getIntermediateSubject(), parameters.getIntermediateValidity(), creationDate, 0, parameters.getSignatureAlgorithm(), parameters.getCRLDistributionPoints()); return new CABuilderResultImpl(new KeyAndCertificateImpl(rootKeyPair.getPrivate(), root), new KeyAndCertificateImpl(intermediateKeyPair.getPrivate(), intermediate)); } catch (NoSuchProviderException e) { throw new CAException(e); } catch (NoSuchAlgorithmException e) { throw new CAException(e); } }
From source file:com.subgraph.vega.internal.http.proxy.ssl.CertificateCreator.java
private HostCertificateData createSelfSignedCertificateDataFor(X500Principal subject, KeyPair subjectKeys) throws CertificateException { final X509Certificate[] chain = new X509Certificate[1]; chain[0] = generateCertificate(subject, subjectKeys.getPublic(), subject, subjectKeys.getPublic(), subjectKeys.getPrivate(), false); return new HostCertificateData(subject.getName(), subjectKeys.getPrivate(), chain); }
From source file:org.apache.hadoop.hdfs.TestDFSStartupWithCRL.java
@Test(timeout = 20000) public void testDFSStartup() throws Exception { String hostname = NetUtils.getLocalCanonicalHostname(); Path keyStore = Paths.get(BASE_DIR, hostname + "__kstore.jks"); Path trustStore = Paths.get(BASE_DIR, hostname + "__tstore.jks"); Path sslServerConfPath = Paths.get(confDir, TestDFSStartupWithCRL.class.getSimpleName() + ".ssl-server.xml"); Path inputCRLPath = Paths.get(BASE_DIR, "input.crl.pem"); Path fetchedCRLPath = Paths.get(BASE_DIR, "fetched.crl.pem"); // Generate server certificate KeyPair keyPair = KeyStoreTestUtil.generateKeyPair(keyAlgorithm); X509Certificate cert = KeyStoreTestUtil.generateCertificate("CN=" + hostname, keyPair, 10, signatureAlgorithm);//w w w. ja v a 2 s. c o m // Create server keystore and truststore KeyStoreTestUtil.createKeyStore(keyStore.toString(), password, "server", keyPair.getPrivate(), cert); KeyStoreTestUtil.createTrustStore(trustStore.toString(), password, "server", cert); // Generate CRL X509CRL crl = KeyStoreTestUtil.generateCRL(cert, keyPair.getPrivate(), signatureAlgorithm, null, null); FileWriter fw = new FileWriter(inputCRLPath.toFile(), false); PemWriter pw = new PemWriter(fw); pw.writeObject(new JcaMiscPEMGenerator(crl)); pw.flush(); fw.flush(); pw.close(); fw.close(); // RPC TLS with CRL configuration conf.set(CommonConfigurationKeysPublic.HADOOP_RPC_SOCKET_FACTORY_CLASS_DEFAULT_KEY, "org.apache.hadoop.net.HopsSSLSocketFactory"); conf.setBoolean(CommonConfigurationKeysPublic.IPC_SERVER_SSL_ENABLED, true); conf.set(SSLFactory.SSL_HOSTNAME_VERIFIER_KEY, "ALLOW_ALL"); String superUser = UserGroupInformation.getCurrentUser().getUserName(); conf.set(ProxyUsers.CONF_HADOOP_PROXYUSER + "." + superUser, "*"); conf.set(SSLFactory.SSL_ENABLED_PROTOCOLS, "TLSv1.2,TLSv1.1"); conf.set(HopsSSLSocketFactory.CryptoKeys.SOCKET_ENABLED_PROTOCOL.getValue(), "TLSv1.2"); Configuration sslServerConf = KeyStoreTestUtil.createServerSSLConfig(keyStore.toString(), password, password, trustStore.toString(), password, ""); KeyStoreTestUtil.saveConfig(sslServerConfPath.toFile(), sslServerConf); conf.set(SSLFactory.SSL_SERVER_CONF_KEY, TestDFSStartupWithCRL.class.getSimpleName() + ".ssl-server.xml"); conf.setBoolean(CommonConfigurationKeysPublic.HOPS_CRL_VALIDATION_ENABLED_KEY, true); conf.set(CommonConfigurationKeys.HOPS_CRL_FETCHER_CLASS_KEY, "org.apache.hadoop.security.ssl.RemoteCRLFetcher"); conf.set(CommonConfigurationKeysPublic.HOPS_CRL_FETCHER_INTERVAL_KEY, "1s"); conf.set(CommonConfigurationKeys.HOPS_CRL_INPUT_URI_KEY, "file://" + inputCRLPath.toString()); conf.set(CommonConfigurationKeys.HOPS_CRL_OUTPUT_FILE_KEY, fetchedCRLPath.toString()); // Start MiniDFS cluster cluster = new MiniDFSCluster.Builder(conf).build(); cluster.waitClusterUp(); Assert.assertEquals(1, cluster.getDataNodes().size()); }
From source file:hudson.cli.Connection.java
/** * Used in conjunction with {@link #verifyIdentity(byte[])} to prove * that we actually own the private key of the given key pair. */// ww w . j a va 2 s.c o m public void proveIdentity(byte[] sharedSecret, KeyPair key) throws IOException, GeneralSecurityException { String algorithm = detectKeyAlgorithm(key); writeUTF(algorithm); writeKey(key.getPublic()); Signature sig = Signature.getInstance("SHA1with" + algorithm); sig.initSign(key.getPrivate()); sig.update(key.getPublic().getEncoded()); sig.update(sharedSecret); writeObject(sig.sign()); }
From source file:org.apache.hadoop.yarn.server.TestYarnStartupWithCRL.java
@Test(timeout = 20000) public void testYarnStartup() throws Exception { String hostname = NetUtils.getLocalCanonicalHostname(); Path keyStore = Paths.get(BASE_DIR, hostname + "__kstore.jks"); Path trustStore = Paths.get(BASE_DIR, hostname + "__tstore.jks"); Path sslServerConfPath = Paths.get(confDir, TestYarnStartupWithCRL.class.getSimpleName() + ".ssl-server.xml"); Path inputCRLPath = Paths.get(BASE_DIR, "input.crl.pem"); Path fetchedCRLPath = Paths.get(BASE_DIR, "fetched.crl.pem"); // Generate server certificate KeyPair keyPair = KeyStoreTestUtil.generateKeyPair(keyAlgorithm); X509Certificate cert = KeyStoreTestUtil.generateCertificate("CN=" + hostname, keyPair, 10, signatureAlgorithm);// w w w. j a va 2 s . co m // Create server keystore and truststore KeyStoreTestUtil.createKeyStore(keyStore.toString(), password, "server", keyPair.getPrivate(), cert); KeyStoreTestUtil.createTrustStore(trustStore.toString(), password, "server", cert); // Generate CRL X509CRL crl = KeyStoreTestUtil.generateCRL(cert, keyPair.getPrivate(), signatureAlgorithm, null, null); FileWriter fw = new FileWriter(inputCRLPath.toFile(), false); PemWriter pw = new PemWriter(fw); pw.writeObject(new JcaMiscPEMGenerator(crl)); pw.flush(); fw.flush(); pw.close(); fw.close(); // RPC TLS with CRL configuration conf.set(CommonConfigurationKeysPublic.HADOOP_RPC_SOCKET_FACTORY_CLASS_DEFAULT_KEY, "org.apache.hadoop.net.HopsSSLSocketFactory"); conf.setBoolean(CommonConfigurationKeysPublic.IPC_SERVER_SSL_ENABLED, true); conf.set(SSLFactory.SSL_HOSTNAME_VERIFIER_KEY, "ALLOW_ALL"); String superUser = UserGroupInformation.getCurrentUser().getUserName(); conf.set(ProxyUsers.CONF_HADOOP_PROXYUSER + "." + superUser, "*"); Configuration sslServerConf = KeyStoreTestUtil.createServerSSLConfig(keyStore.toString(), password, password, trustStore.toString(), password, ""); KeyStoreTestUtil.saveConfig(sslServerConfPath.toFile(), sslServerConf); conf.set(SSLFactory.SSL_SERVER_CONF_KEY, TestYarnStartupWithCRL.class.getSimpleName() + ".ssl-server.xml"); conf.setBoolean(CommonConfigurationKeysPublic.HOPS_CRL_VALIDATION_ENABLED_KEY, true); conf.set(CommonConfigurationKeys.HOPS_CRL_FETCHER_CLASS_KEY, "org.apache.hadoop.security.ssl.RemoteCRLFetcher"); conf.set(CommonConfigurationKeysPublic.HOPS_CRL_FETCHER_INTERVAL_KEY, "1s"); conf.set(CommonConfigurationKeys.HOPS_CRL_INPUT_URI_KEY, "file://" + inputCRLPath.toString()); conf.set(CommonConfigurationKeys.HOPS_CRL_OUTPUT_FILE_KEY, fetchedCRLPath.toString()); // Start MiniYarn cluster cluster = new MiniYARNCluster(TestYarnStartupWithCRL.class.getSimpleName(), 1, 1, 1); cluster.init(conf); cluster.start(); cluster.waitForNodeManagersToConnect(2000); Assert.assertTrue(cluster.getResourceManager().areSchedulerServicesRunning()); Assert.assertEquals(1, cluster.getResourceManager().getResourceScheduler().getNumClusterNodes()); }
From source file:com.thoughtworks.go.server.util.HttpTestUtil.java
private void prepareCertStore(File serverKeyStore) { KeyPair keyPair = generateKeyPair(); X509Certificate cert = generateCert(keyPair); FileOutputStream os = null;//from w w w . j a v a2s.c om try { KeyStore store = KeyStore.getInstance("JKS"); store.load(null, null); store.setKeyEntry("test", keyPair.getPrivate(), STORE_PASSWORD.toCharArray(), new Certificate[] { cert }); os = new FileOutputStream(serverKeyStore); store.store(os, STORE_PASSWORD.toCharArray()); } catch (Exception e) { throw new RuntimeException(e); } finally { if (os != null) { IOUtils.closeQuietly(os); } } }
From source file:netinf.common.security.impl.CryptographyTest.java
@Test public void testBadPrivateKeyAlgorithm() throws NetInfCheckedSecurityException { Attribute attribute = createTestAttribute(); Attribute encryptedAttribute = crypto.encrypt(attribute, publicKeys); IdentityManager wrongIdentityManager = EasyMock.createMock(IdentityManager.class); EasyMock.expect(wrongIdentityManager.hasPrivateKey((String) EasyMock.anyObject())).andReturn(true) .anyTimes();//w w w.j a va 2s . c om EasyMock.expect(wrongIdentityManager.hasPrivateKey((String) EasyMock.anyObject(), (String) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(true).anyTimes(); try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA"); keyPairGenerator.initialize(1024); KeyPair pair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = pair.getPrivate(); try { EasyMock.expect(wrongIdentityManager.getPrivateKey((String) EasyMock.anyObject())) .andReturn(privateKey).anyTimes(); EasyMock.expect(wrongIdentityManager.getPrivateKey((String) EasyMock.anyObject(), (String) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(privateKey) .anyTimes(); } catch (NetInfCheckedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } catch (Exception e) { throw new NetInfUncheckedException("error creating keys"); } EasyMock.replay(wrongIdentityManager); try { // FIXME added dummy-port! needs adjustment! CryptographyImpl crypto = new CryptographyImpl(wrongIdentityManager, algorithm, factory, convenienceCommunicator); crypto.decrypt(encryptedAttribute); Assert.fail("Exception expected. Wrong private key given."); } catch (NetInfCheckedSecurityException securityException) { System.out.println(securityException.getMessage()); } }
From source file:netinf.common.security.impl.CryptographyTest.java
@Test public void testBadPrivateKey() throws NetInfCheckedSecurityException { Attribute attribute = createTestAttribute(); Attribute encryptedAttribute = crypto.encrypt(attribute, publicKeys); // String keyName = identityObject.getIdentifier().toString() + "?" + DefinedAttributeIdentification.PUBLIC_KEY.getURI(); IdentityManager wrongIdentityManager = EasyMock.createMock(IdentityManager.class); EasyMock.expect(wrongIdentityManager.hasPrivateKey((String) EasyMock.anyObject())).andReturn(true) .anyTimes();/*from ww w . j a va2 s . co m*/ EasyMock.expect(wrongIdentityManager.hasPrivateKey((String) EasyMock.anyObject(), (String) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(true).anyTimes(); try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair pair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = pair.getPrivate(); try { EasyMock.expect(wrongIdentityManager.getPrivateKey((String) EasyMock.anyObject())) .andReturn(privateKey).anyTimes(); EasyMock.expect(wrongIdentityManager.getPrivateKey((String) EasyMock.anyObject(), (String) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(privateKey) .anyTimes(); } catch (NetInfCheckedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } catch (Exception e) { throw new NetInfUncheckedException("error creating keys"); } EasyMock.replay(wrongIdentityManager); try { // FIXME added dummy-port! needs adjustment! CryptographyImpl crypto = new CryptographyImpl(wrongIdentityManager, algorithm, factory, convenienceCommunicator); crypto.decrypt(encryptedAttribute); Assert.fail("Exception expected. Wrong private key given."); } catch (NetInfCheckedSecurityException securityException) { System.out.println(securityException.getMessage()); } }