List of usage examples for java.security KeyPair getPrivate
public PrivateKey getPrivate()
From source file:info.magnolia.cms.security.SecurityUtil.java
public static MgnlKeyPair generateKeyPair(int keyLength) throws NoSuchAlgorithmException { KeyPairGenerator kgen = KeyPairGenerator.getInstance(ALGORITHM); kgen.initialize(keyLength);//from w ww .java 2 s . c o m KeyPair key = kgen.genKeyPair(); return new MgnlKeyPair(byteArrayToHex(key.getPrivate().getEncoded()), byteArrayToHex(key.getPublic().getEncoded())); }
From source file:netinf.common.security.impl.CryptographyTest.java
@BeforeClass public static void classSetUp() throws Exception { final Properties properties = Utils.loadProperties(NETINFNODE_PROPERTIES); injector = Guice.createInjector(new LogModule(properties), new DatamodelImplModule(), new CommunicationModule(), new SecurityModule(), new AbstractModule() { @Override/*from www . j a v a 2 s .c o m*/ protected void configure() { bind(NetInfNodeConnection.class).annotatedWith(SecurityModule.Security.class) .to(RemoteNodeConnection.class).in(Singleton.class); Names.bindProperties(binder(), properties); } }); factory = injector.getInstance(DatamodelFactory.class); identityObject = factory.createIdentityObject(); Identifier id = factory.createIdentifier(); IdentifierLabel label = factory.createIdentifierLabel(); label.setLabelName(DefinedLabelName.UNIQUE_LABEL.getLabelName()); label.setLabelValue("Test-Identity"); id.addIdentifierLabel(label); identityObject.setIdentifier(id); try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair pair = keyPairGenerator.generateKeyPair(); privateKey = pair.getPrivate(); publicKey = pair.getPublic(); String keyName = identityObject.getIdentifier().toString() + "?" + DefinedAttributeIdentification.PUBLIC_KEY.getURI(); publicKeys.put(keyName, publicKey); identityObject.setPublicMasterKey(pair.getPublic()); } catch (Exception e) { throw new NetInfUncheckedException("error creating keys"); } convenienceCommunicator = EasyMock.createMock(RemoteNodeConnection.class); convenienceCommunicator.setHostAndPort("localhost", 5000); EasyMock.expectLastCall().anyTimes(); convenienceCommunicator.setSerializeFormat(SerializeFormat.JAVA); EasyMock.expectLastCall().anyTimes(); EasyMock.expect(convenienceCommunicator.getIO((Identifier) EasyMock.anyObject())).andReturn(identityObject) .anyTimes(); EasyMock.replay(convenienceCommunicator); identityManager = EasyMock.createMock(IdentityManager.class); EasyMock.expect(identityManager.getPrivateKey((String) EasyMock.anyObject())).andReturn(privateKey) .anyTimes(); EasyMock.expect(identityManager.hasPrivateKey((String) EasyMock.anyObject())).andReturn(true).anyTimes(); EasyMock.expect(identityManager.getPrivateKey(((String) EasyMock.anyObject()), (String) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(privateKey).anyTimes(); EasyMock.expect(identityManager.hasPrivateKey(((String) EasyMock.anyObject()), (String) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(true).anyTimes(); EasyMock.replay(identityManager); crypto = new CryptographyImpl(identityManager, algorithm, factory, convenienceCommunicator); }
From source file:com.github.aynu.yukar.framework.util.SecurityHelper.java
/** * RSA???/*from www. j a va 2s . c om*/ * <dl> * <dt>? * <dd>RSA??????2048?????? * </dl> * @return RSA? */ public static KeyPair createKeyPair() { try { final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048); final KeyPair pair = generator.generateKeyPair(); if (LOG.isDebugEnabled()) { final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic(); final RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate(); LOG.debug("public-modulus={}", Base64.encodeBase64String(publicKey.getModulus().toByteArray())); LOG.debug("public-exponent={}", Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray())); LOG.debug("private-modulus={}", Base64.encodeBase64String(privateKey.getModulus().toByteArray())); LOG.debug("private-exponent={}", Base64.encodeBase64String(privateKey.getPrivateExponent().toByteArray())); } return pair; } catch (final NoSuchAlgorithmException e) { throw new StandardRuntimeException(e); } }
From source file:cn.util.RSAUtils.java
/** * ??// w ww. j a v a 2s .c om * @throws NoSuchAlgorithmException * */ public static HashMap<String, Object> getKeys() throws NoSuchAlgorithmException { HashMap<String, Object> map = new HashMap<String, Object>(); KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); keyPairGen.initialize(1024); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); map.put("public", publicKey); map.put("private", privateKey); return map; }
From source file:com.glaf.core.security.RSAUtils.java
/** ?? */ public static RSAPrivateKey getDefaultPrivateKey() { KeyPair keyPair = getKeyPair(); if (keyPair != null) { return (RSAPrivateKey) keyPair.getPrivate(); }/*from ww w. j ava 2 s . c om*/ return null; }
From source file:co.cask.cdap.security.tools.KeyStores.java
/** * Create a Java key store with a stored self-signed certificate. * @return Java keystore which has a self signed X.509 certificate *//* w w w . j ava 2 s. c o m*/ public static KeyStore generatedCertKeyStore(SConfiguration sConf, String password) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KEY_PAIR_ALGORITHM); SecureRandom random = SecureRandom.getInstance(SECURE_RANDOM_ALGORITHM, SECURE_RANDOM_PROVIDER); keyGen.initialize(KEY_SIZE, random); // generate a key pair KeyPair pair = keyGen.generateKeyPair(); int validity = sConf.getInt(Constants.Security.SSL.CERT_VALIDITY, VALIDITY); X509Certificate cert = getCertificate(DISTINGUISHED_NAME, pair, validity, SIGNATURE_ALGORITHM); KeyStore keyStore = KeyStore.getInstance(SSL_KEYSTORE_TYPE); keyStore.load(null, password.toCharArray()); keyStore.setKeyEntry(CERT_ALIAS, pair.getPrivate(), password.toCharArray(), new java.security.cert.Certificate[] { cert }); return keyStore; } catch (Exception e) { throw new RuntimeException( "SSL is enabled but a key store file could not be created. A keystore is required " + "for SSL to be used.", e); } }
From source file:org.mitre.jwt.signer.service.impl.KeyStoreTest.java
/** * Create an RSA KeyPair and insert into specified KeyStore * // w w w. j av a 2 s . co m * @param location * @param domainName * @param alias * @param keystorePassword * @param aliasPassword * @param daysNotValidBefore * @param daysNotValidAfter * @return * @throws GeneralSecurityException * @throws IOException */ public static java.security.KeyStore generateKeyPair(KeyStore keystore, String keyPairAlgorithm, int keySize, String signatureAlgorithm, String domainName, String alias, String aliasPassword, int daysNotValidBefore, int daysNotValidAfter) throws GeneralSecurityException, IOException { java.security.KeyStore ks; if (keystore != null) { ks = keystore.getKeystore(); } else { ks = java.security.KeyStore.getInstance(java.security.KeyStore.getDefaultType()); ks.load(null, null); } KeyPairGenerator rsaKeyPairGenerator = null; rsaKeyPairGenerator = KeyPairGenerator.getInstance(keyPairAlgorithm); rsaKeyPairGenerator.initialize(keySize); KeyPair rsaKeyPair = rsaKeyPairGenerator.generateKeyPair(); // BC sez X509V3CertificateGenerator is deprecated and the docs say to // use another, but it seemingly isn't included jar... X509V3CertificateGenerator v3CertGen = createCertificate(domainName, daysNotValidBefore, daysNotValidAfter); PrivateKey privateKey = rsaKeyPair.getPrivate(); v3CertGen.setPublicKey(rsaKeyPair.getPublic()); v3CertGen.setSignatureAlgorithm(signatureAlgorithm); // BC docs say to use another, but it seemingly isn't included... X509Certificate certificate = v3CertGen.generateX509Certificate(privateKey); // if exist, overwrite ks.setKeyEntry(alias, privateKey, aliasPassword.toCharArray(), new java.security.cert.Certificate[] { certificate }); if (keystore != null) { keystore.setKeystore(ks); } return ks; }
From source file:Main.java
public static String getJwkPrivate(KeyPair kp) { try {//from w w w . j a v a2 s.co m JSONObject jk = new JSONObject(); jk.put("kty", "RSA"); // generate random kid SecureRandom random = new SecureRandom(); String kid = new BigInteger(130, random).toString(32); jk.put("kid", kid); jk.put("e", "AQAB"); KeyFactory kfactory = KeyFactory.getInstance("RSA"); RSAPrivateKeySpec privkspec = (RSAPrivateKeySpec) kfactory.getKeySpec(kp.getPrivate(), RSAPrivateKeySpec.class); RSAPublicKeySpec pubkspec = (RSAPublicKeySpec) kfactory.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class); // Log.d("getJwkPrivate n",pubkspec.getPublicExponent().toString()); // Log.d("getJwkPrivate d",privkspec.getPrivateExponent().toString()); jk.put("n", encodeB64(pubkspec.getModulus().toByteArray())); jk.put("d", encodeB64(privkspec.getPrivateExponent().toByteArray())); JSONArray ja = new JSONArray(); ja.put(jk); JSONObject jo = new JSONObject(); jo.put("keys", ja); return jo.toString(); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:io.vertx.config.vault.utils.Certificates.java
/** * Constructs a Java truststore in JKS format, containing the Vault server certificate generated by * {@link #createVaultCertAndKey()}, so that Vault clients configured with this JKS will trust that * certificate./*from w w w. ja v a 2 s . c o m*/ */ public static void createClientCertAndKey() throws Exception { if (SSL_DIRECTORY.isDirectory() && CLIENT_CERT_PEMFILE.isFile()) { return; } // Store the Vault's server certificate as a trusted cert in the truststore final KeyStore trustStore = KeyStore.getInstance("jks"); trustStore.load(null); trustStore.setCertificateEntry("cert", vaultCertificate); try (final FileOutputStream keystoreOutputStream = new FileOutputStream(CLIENT_TRUSTSTORE)) { trustStore.store(keystoreOutputStream, "password".toCharArray()); } // Generate a client certificate, and store it in a Java keystore final KeyPair keyPair = generateKeyPair(); final X509Certificate clientCertificate = generateCert(keyPair, "C=AU, O=The Legion of the Bouncy Castle, OU=Client Certificate, CN=localhost"); final KeyStore keyStore = KeyStore.getInstance("jks"); keyStore.load(null); keyStore.setKeyEntry("privatekey", keyPair.getPrivate(), "password".toCharArray(), new java.security.cert.Certificate[] { clientCertificate }); keyStore.setCertificateEntry("cert", clientCertificate); try (final FileOutputStream keystoreOutputStream = new FileOutputStream(CLIENT_KEYSTORE)) { keyStore.store(keystoreOutputStream, "password".toCharArray()); } // Also write the client certificate to a PEM file, so it can be registered with Vault writeCertToPem(clientCertificate, CLIENT_CERT_PEMFILE); writePrivateKeyToPem(keyPair.getPrivate(), CLIENT_PRIVATE_KEY_PEMFILE); }
From source file:net.nicholaswilliams.java.licensing.licensor.TestLicenseCreator.java
@BeforeClass public static void setUpClass() throws Exception { TestLicenseCreator.control = EasyMock.createStrictControl(); TestLicenseCreator.passwordProvider = TestLicenseCreator.control.createMock(PasswordProvider.class); TestLicenseCreator.keyDataProvider = TestLicenseCreator.control.createMock(PrivateKeyDataProvider.class); try {/*from www . java 2 s. c o m*/ LicenseCreator.getInstance(); fail("Expected java.lang.IllegalArgumentException, got no exception."); } catch (IllegalArgumentException ignore) { } LicenseCreatorProperties.setPrivateKeyDataProvider(TestLicenseCreator.keyDataProvider); try { LicenseCreator.getInstance(); fail("Expected java.lang.IllegalArgumentException, got no exception."); } catch (IllegalArgumentException ignore) { } LicenseCreatorProperties.setPrivateKeyPasswordProvider(TestLicenseCreator.passwordProvider); LicenseCreator.getInstance(); KeyPair keyPair = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair(); TestLicenseCreator.publicKey = keyPair.getPublic(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyPair.getPrivate().getEncoded()); IOUtils.write(Encryptor.encryptRaw(pkcs8EncodedKeySpec.getEncoded(), keyPassword), outputStream); TestLicenseCreator.encryptedPrivateKey = outputStream.toByteArray(); }