List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
From source file:com.streamsets.pipeline.lib.remote.FTPAndSSHDUnitTest.java
private X509Certificate generateCertificate(KeyPair keyPair) throws Exception { Date from = new Date(); Date to = new GregorianCalendar(2037, Calendar.DECEMBER, 31).getTime(); X500Name subject = new X500Name("CN=localhost"); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(subject, new BigInteger(64, new SecureRandom()), from, to, subject, subPubKeyInfo); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA512WITHRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId) .build(PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded())); X509CertificateHolder certHolder = certBuilder.build(contentSigner); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder); }
From source file:org.openengsb.core.services.internal.security.FileKeySource.java
private void generateKeysIfRequired(File keyDirectoryFile) { File privateKeyFile = new File(keyDirectoryFile, DEFAULT_PRIVATE_KEY_FILENAME); File publicKeyFile = new File(keyDirectoryFile, DEFAULT_PUBLIC_KEY_FILENAME); if (privateKeyFile.exists() && publicKeyFile.exists()) { LOGGER.info("skipping key-generation, because there already are some"); return;// w w w .j a va 2s . co m } KeyPairGenerator generator; try { LOGGER.info("generating new keypair"); generator = KeyPairGenerator.getInstance(DEFAULT_ALGORITHM); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("failed to generate keypair", e); } generator.initialize(DEFAULT_KEY_SIZE); KeyPair generatedKeyPair = generator.generateKeyPair(); try { LOGGER.trace("saving new keypair to files"); FileUtils.writeByteArrayToFile(privateKeyFile, generatedKeyPair.getPrivate().getEncoded()); FileUtils.writeByteArrayToFile(publicKeyFile, generatedKeyPair.getPublic().getEncoded()); } catch (IOException e) { throw new IllegalStateException("failed to write keys to key-directory", e); } }
From source file:mitm.common.security.ca.SMIMECABuilder.java
@Override public synchronized CABuilderResult buildCA(CABuilderParameters parameters) throws CAException { try {/*from www .ja va 2 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.streamsets.datacollector.publicrestapi.TestCredentialsDeploymentResource.java
@Test public void testSuccess() throws Exception { Properties sdcProps = new Properties(); sdcProps.setProperty("a", "b"); sdcProps.setProperty("c", "d"); sdcProps.setProperty("kerberos.client.keytab", "sdc.keytab"); sdcProps.setProperty("kerberos.client.enabled", "false"); sdcProps.setProperty("kerberos.client.principal", "sdc/_HOST@EXAMPLE.COM"); File sdcFile = new File(RuntimeInfoTestInjector.confDir, "sdc.properties"); Properties dpmProps = new Properties(); dpmProps.setProperty("x", "y"); dpmProps.setProperty("z", "a"); dpmProps.setProperty("dpm.enabled", "false"); dpmProps.setProperty("dpm.base.url", "http://localhost:18631"); File dpmFile = new File(RuntimeInfoTestInjector.confDir, "dpm.properties"); try (FileWriter fw = new FileWriter(sdcFile)) { sdcProps.store(fw, ""); }/*from w w w . j a v a 2 s.co m*/ try (FileWriter fw = new FileWriter(dpmFile)) { dpmProps.store(fw, ""); } Response response = null; KeyPair keys = generateKeys(); mockCheckForCredentialsRequiredToTrue(); System.setProperty(DPM_AGENT_PUBLIC_KEY, Base64.getEncoder().encodeToString(keys.getPublic().getEncoded())); String token = "Frenchies and Pandas"; Signature sig = Signature.getInstance("SHA256withRSA"); sig.initSign(keys.getPrivate()); sig.update(token.getBytes(Charsets.UTF_8)); List<String> labels = Arrays.asList("deployment-prod-1", "deployment-prod-2"); CredentialsBeanJson json = new CredentialsBeanJson(token, "streamsets/172.1.1.0@EXAMPLE.COM", Base64.getEncoder().encodeToString("testKeytab".getBytes(Charsets.UTF_8)), Base64.getEncoder().encodeToString(sig.sign()), "https://dpm.streamsets.com:18631", Arrays.asList("deployment-prod-1", "deployment-prod-2"), "deployment1:org"); try { response = target("/v1/deployment/deployCredentials").request().post(Entity.json(json)); Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); CredentialDeploymentResponseJson responseJson = OBJECT_MAPPER .readValue((InputStream) response.getEntity(), CredentialDeploymentResponseJson.class); Assert.assertEquals(CredentialDeploymentStatus.CREDENTIAL_USED_AND_DEPLOYED, responseJson.getCredentialDeploymentStatus()); // Verify sdc.properties sdcProps = new Properties(); try (FileReader fr = new FileReader(sdcFile)) { sdcProps.load(fr); } Assert.assertEquals("b", sdcProps.getProperty("a")); Assert.assertEquals("d", sdcProps.getProperty("c")); Assert.assertEquals("streamsets/172.1.1.0@EXAMPLE.COM", sdcProps.getProperty("kerberos.client.principal")); Assert.assertEquals("true", sdcProps.getProperty("kerberos.client.enabled")); Assert.assertEquals("sdc.keytab", sdcProps.getProperty("kerberos.client.keytab")); byte[] keyTab = Files.toByteArray(new File(RuntimeInfoTestInjector.confDir, "sdc.keytab")); Assert.assertEquals("testKeytab", new String(keyTab, Charsets.UTF_8)); response = target("/v1/definitions").request().get(); Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); dpmProps = new Properties(); try (FileReader fr = new FileReader(dpmFile)) { dpmProps.load(fr); } Assert.assertEquals("y", dpmProps.getProperty("x")); Assert.assertEquals("a", dpmProps.getProperty("z")); Assert.assertEquals("true", dpmProps.getProperty("dpm.enabled")); Assert.assertEquals( Configuration.FileRef.PREFIX + "application-token.txt" + Configuration.FileRef.SUFFIX, dpmProps.getProperty("dpm.appAuthToken")); Assert.assertEquals("https://dpm.streamsets.com:18631", dpmProps.getProperty("dpm.base.url")); Assert.assertEquals(StringUtils.join(labels.toArray(), ","), dpmProps.getProperty(RemoteEventHandlerTask.REMOTE_JOB_LABELS)); Assert.assertEquals("deployment1:org", dpmProps.getProperty(RemoteSSOService.DPM_DEPLOYMENT_ID)); File tokenFile = new File(RuntimeInfoTestInjector.confDir, "application-token.txt"); try (FileInputStream fr = new FileInputStream(tokenFile)) { int len = token.length(); byte[] tokenBytes = new byte[len]; Assert.assertEquals(len, fr.read(tokenBytes)); Assert.assertEquals(token, new String(tokenBytes, Charsets.UTF_8)); } //Test redeploying the credentials again response = target("/v1/deployment/deployCredentials").request().post(Entity.json(json)); responseJson = OBJECT_MAPPER.readValue((InputStream) response.getEntity(), CredentialDeploymentResponseJson.class); Assert.assertEquals(CredentialDeploymentStatus.CREDENTIAL_NOT_USED_ALREADY_DEPLOYED, responseJson.getCredentialDeploymentStatus()); } finally { if (response != null) { response.close(); } } }
From source file:org.aon.esolutions.appconfig.web.controller.EnvironmentController.java
private Map<String, String> updateKeys(Environment env) throws Exception { Map<String, String> answer = new HashMap<String, String>(); if (env != null) { // First, get private key - Performs ACL Checking PrivateKeyHolder holder = null;//from w w w. ja v a 2 s . co m if (env.getPrivateKeyHolder() != null) holder = privateKeyRepository.findOne(env.getPrivateKeyHolder().getId()); if (holder != null) { Key key = RSAEncryptUtil.getPrivateKeyFromString(holder.getPrivateKey()); for (String encryptedVariable : env.getEncryptedVariables()) { String encryptedValue = env.get(encryptedVariable); if (encryptedValue != null) { String decryptedValue = RSAEncryptUtil.decrypt(encryptedValue, key); env.put(encryptedVariable, decryptedValue); } } } else { holder = new PrivateKeyHolder(); env.setPrivateKeyHolder(holder); holder.setEnvironment(env); } // Generate the new keys KeyPair keyPair = RSAEncryptUtil.generateKey(); env.setPublicKey(RSAEncryptUtil.getKeyAsString(keyPair.getPublic())); holder.setPrivateKey(RSAEncryptUtil.getKeyAsString(keyPair.getPrivate())); // Re-encrypt with the new values for (String encryptedVariable : env.getEncryptedVariables()) { String decryptedValue = env.get(encryptedVariable); if (decryptedValue != null) { String encryptedValue = RSAEncryptUtil.encrypt(decryptedValue, keyPair.getPublic()); env.put(encryptedVariable, encryptedValue); } } updateUtility.savePrivateKeyHolder(holder); answer.put("publicKey", env.getPublicKey()); answer.put("privateKey", holder.getPrivateKey()); } return answer; }
From source file:edu.vt.middleware.crypt.util.CryptReaderWriterTest.java
/** * @return Public key test data./* www.j a v a 2 s .co m*/ * * @throws Exception On test data generation failure. */ @DataProvider(name = "pubkeydata") public Object[][] createPubKeyTestData() 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.getPublic() }, { dsaKeys.getPublic() }, }; }
From source file:com.POLIS.licensing.frontend.AnnotationEnabledFrontendTest.java
@Before public void setUp() throws NoSuchAlgorithmException, NoSuchProviderException, SystemStateException, OperationException { frontend = new AnnotationEnabledFrontend<>(new TestFactory(), new TestConnector(), new TestDecorator()); SecureRandom random = new SecureRandom(); KeyPairGenerator rsagenerator = KeyPairGenerator.getInstance("RSA", "BC"); rsagenerator.initialize(1024, random); KeyPair pair = rsagenerator.generateKeyPair(); serverPubKey = pair.getPublic(); serverPrivKey = pair.getPrivate();//from w w w . j av a 2 s . co m frontend.initialize(serverPubKey); }
From source file:org.oscarehr.sharingcenter.actions.SecurityInfrastructureServlet.java
private String createNewInfrastructure(String alias, String commonName, String organizationalUnit, String organization, String locality, String state, String country) { InfrastructureDao dao = SpringUtils.getBean(InfrastructureDao.class); if (alias == null) { return "error"; }/*from www . ja va2 s . co m*/ if (dao.aliasExists(alias)) { return "exists"; } else { InfrastructureDataObject infrastructure = new InfrastructureDataObject(); infrastructure.setAlias(alias); infrastructure.setCommonName(commonName); infrastructure.setOrganizationalUnit(organizationalUnit); infrastructure.setOrganization(organization); infrastructure.setLocality(locality); infrastructure.setState(state); infrastructure.setCountry(country); //Generate, encode, and set the public and private keys try { KeyPair keyPair = SslUtility.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); Base64 base64 = new Base64(); String encodedPubKey = new String(base64.encode(publicKey.getEncoded()), MiscUtils.DEFAULT_UTF8_ENCODING); String encodedPrivKey = new String(base64.encode(privateKey.getEncoded()), MiscUtils.DEFAULT_UTF8_ENCODING); infrastructure.setBase64EncodedPublicKey(encodedPubKey); infrastructure.setBase64EncodedPrivateKey(encodedPrivKey); dao.persist(infrastructure); } catch (SslException e) { return "sslerror"; } catch (UnsupportedEncodingException e) { return "encodingerror"; } } return "success"; }
From source file:com.kuzumeji.platform.standard.SecurityService.java
/** * RSA???/* w ww .ja v a 2 s .c o m*/ * <dl> * <dt>? * <dd>RSA??? * </dl> * @param name RSA??? * @param keyPair RSA? */ public void saveKeyPair(final String name, final KeyPair keyPair) { try { final Properties property = new PropertyService(PROPERTY_NAME).getProperty(); final RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); property.setProperty(String.format(KEY_PUBLIC_ENCODED, name), Hex.encodeHexString(publicKey.getEncoded())); final RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); property.setProperty(String.format(KEY_PRIVATE_ENCODED, name), Hex.encodeHexString(privateKey.getEncoded())); try (FileOutputStream stream = new FileOutputStream( Thread.currentThread().getContextClassLoader().getResource(PROPERTY_NAME).getPath());) { property.store(stream, "RSAPublicKey and RSAPrivateKey"); } } catch (final IOException e) { throw new RuntimeException(e); } }