List of usage examples for java.security KeyPairGenerator generateKeyPair
public KeyPair generateKeyPair()
From source file:gov.nih.nci.firebird.service.signing.DigitalSigningHelper.java
/** * Generate a random 1024 bit RSA key pair. * * @throws DigitalSigningException//from w ww . j a v a 2s .c om * Customized exception with error message. * * @return a random KeyPair. */ KeyPair generateKeyPair() throws DigitalSigningException { KeyPairGenerator kpGen = null; try { kpGen = KeyPairGenerator.getInstance("RSA", BOUNCY_CASTLE_PROVIDER); kpGen.initialize(KEYSIZE, new SecureRandom()); return kpGen.generateKeyPair(); } catch (NoSuchAlgorithmException e) { throw new DigitalSigningException(KEYPAIR_GENERATION_ERROR_MESSAGE, e); } catch (NoSuchProviderException e) { throw new DigitalSigningException(KEYPAIR_GENERATION_ERROR_MESSAGE, e); } }
From source file:org.apache.drill.exec.server.rest.WebServer.java
/** * Create an HTTPS connector for given jetty server instance. If the admin has specified keystore/truststore settings * they will be used else a self-signed certificate is generated and used. * * @return Initialized {@link ServerConnector} for HTTPS connectios. * @throws Exception/*from w w w . ja va 2 s . co m*/ */ private ServerConnector createHttpsConnector() throws Exception { logger.info("Setting up HTTPS connector for web server"); final SslContextFactory sslContextFactory = new SslContextFactory(); if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH) && !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH))) { logger.info("Using configured SSL settings for web server"); sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH)); sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD)); // TrustStore and TrustStore password are optional if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) { sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH)); if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) { sslContextFactory .setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)); } } } else { logger.info("Using generated self-signed SSL settings for web server"); final SecureRandom random = new SecureRandom(); // Generate a private-public key pair final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024, random); final KeyPair keyPair = keyPairGenerator.generateKeyPair(); final DateTime now = DateTime.now(); // Create builder for certificate attributes final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE) .addRDN(BCStyle.OU, "Apache Drill (auth-generated)") .addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)") .addRDN(BCStyle.CN, workManager.getContext().getEndpoint().getAddress()); final Date notBefore = now.minusMinutes(1).toDate(); final Date notAfter = now.plusYears(5).toDate(); final BigInteger serialNumber = new BigInteger(128, random); // Create a certificate valid for 5years from now. final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), // attributes serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic()); // Sign the certificate using the private key final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption") .build(keyPair.getPrivate()); final X509Certificate certificate = new JcaX509CertificateConverter() .getCertificate(certificateBuilder.build(contentSigner)); // Check the validity certificate.checkValidity(now.toDate()); // Make sure the certificate is self-signed. certificate.verify(certificate.getPublicKey()); // Generate a random password for keystore protection final String keyStorePasswd = RandomStringUtils.random(20); final KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null); keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(), new java.security.cert.Certificate[] { certificate }); sslContextFactory.setKeyStore(keyStore); sslContextFactory.setKeyStorePassword(keyStorePasswd); } final HttpConfiguration httpsConfig = new HttpConfiguration(); httpsConfig.addCustomizer(new SecureRequestCustomizer()); // SSL Connector final ServerConnector sslConnector = new ServerConnector(embeddedJetty, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig)); sslConnector.setPort(config.getInt(ExecConstants.HTTP_PORT)); return sslConnector; }
From source file:org.red5.server.net.rtmp.RTMPHandshake.java
/** * Creates a Diffie-Hellman key pair.//from w w w .ja v a2 s. c o m * * @return dh keypair */ protected KeyPair generateKeyPair() { KeyPair keyPair = null; DHParameterSpec keySpec = new DHParameterSpec(DH_MODULUS, DH_BASE); try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH"); keyGen.initialize(keySpec); keyPair = keyGen.generateKeyPair(); keyAgreement = KeyAgreement.getInstance("DH"); keyAgreement.init(keyPair.getPrivate()); } catch (Exception e) { log.error("Error generating keypair", e); } return keyPair; }
From source file:com.example.android.basicandroidkeystore.BasicAndroidKeyStoreFragment.java
/** * Creates a public and private key and stores it using the Android Key Store, so that only * this application will be able to access the keys. *//* ww w . j av a 2 s .c o m*/ public void createKeys(Context context) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { // BEGIN_INCLUDE(create_valid_dates) // Create a start and end time, for the validity range of the key pair that's about to be // generated. Calendar start = new GregorianCalendar(); Calendar end = new GregorianCalendar(); end.add(Calendar.YEAR, 1); //END_INCLUDE(create_valid_dates) // BEGIN_INCLUDE(create_spec) // The KeyPairGeneratorSpec object is how parameters for your key pair are passed // to the KeyPairGenerator. For a fun home game, count how many classes in this sample // start with the phrase "KeyPair". KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context) // You'll use the alias later to retrieve the key. It's a key for the key! .setAlias(mAlias) // The subject used for the self-signed certificate of the generated pair .setSubject(new X500Principal("CN=" + mAlias)) // The serial number used for the self-signed certificate of the // generated pair. .setSerialNumber(BigInteger.valueOf(1337)) // Date range of validity for the generated pair. .setStartDate(start.getTime()).setEndDate(end.getTime()).build(); // END_INCLUDE(create_spec) // BEGIN_INCLUDE(create_keypair) // Initialize a KeyPair generator using the the intended algorithm (in this example, RSA // and the KeyStore. This example uses the AndroidKeyStore. KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance(SecurityConstants.TYPE_RSA, SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE); kpGenerator.initialize(spec); KeyPair kp = kpGenerator.generateKeyPair(); Log.d(TAG, "Public Key is: " + kp.getPublic().toString()); // END_INCLUDE(create_keypair) }
From source file:org.pgptool.gui.encryption.implpgp.KeyGeneratorServicePgpImpl.java
@Override public Key createNewKey(CreateKeyParams params) throws FieldValidationException { try {/*from www.j av a 2 s . c om*/ Preconditions.checkArgument(params != null, "params must not be null"); assertParamsValid(params); // Create KeyPairs KeyPair dsaKp = getOrGenerateDsaKeyPair(DEFAULT_DSA_KEY_PARAMETERS); KeyPairGenerator elgKpg = KeyPairGenerator.getInstance("ELGAMAL", "BC"); DHParameterSpec elParams = new DHParameterSpec(p, g); elgKpg.initialize(elParams); KeyPair elgKp = elgKpg.generateKeyPair(); // Now let do some crazy stuff (I HAVE NO IDEA WHAT I AM DOING // HERE). BouncyCastle guys are not helping by changing API from // one version to another so often!!!!!!! PGPKeyPair dsaKeyPair = new JcaPGPKeyPair(PGPPublicKey.DSA, dsaKp, new Date()); PGPKeyPair elgKeyPair = new JcaPGPKeyPair(PGPPublicKey.ELGAMAL_ENCRYPT, elgKp, new Date()); // PGPContentSignerBuilde // JCA // JcaPGPContentSignerBuilder keySignerBuilder = new // JcaPGPContentSignerBuilder( // dsaKeyPair.getPublicKey().getAlgorithm(), // HashAlgorithmTags.SHA256); // BC BcPGPContentSignerBuilder keySignerBuilderBC = new BcPGPContentSignerBuilder( dsaKeyPair.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA256); // PGPDigestCalculator // JCA // PGPDigestCalculator sha1Calc = new // JcaPGPDigestCalculatorProviderBuilder().build() // .get(HashAlgorithmTags.SHA256); // BC PGPDigestCalculator sha1CalcBC = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1); // keyEncryptor // BC BcPBESecretKeyEncryptorBuilder encryptorBuilderBC = new BcPBESecretKeyEncryptorBuilder( PGPEncryptedData.AES_256, sha1CalcBC); PBESecretKeyEncryptor keyEncryptorBC = encryptorBuilderBC.build(params.getPassphrase().toCharArray()); // JCA // JcePBESecretKeyEncryptorBuilder encryptorBuilder = new // JcePBESecretKeyEncryptorBuilder( // PGPEncryptedData.AES_256, sha1Calc).setProvider("BC"); // PBESecretKeyEncryptor keyEncryptor = // encryptorBuilder.build(params.getPassphrase().toCharArray()); // keyRingGen String userName = params.getFullName() + " <" + params.getEmail() + ">"; // JCA // PGPKeyRingGenerator keyRingGen = new // PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, // dsaKeyPair, // userName, sha1Calc, null, null, keySignerBuilder, // keyEncryptor); // BC PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, dsaKeyPair, userName, sha1CalcBC, null, null, keySignerBuilderBC, keyEncryptorBC); keyRingGen.addSubKey(elgKeyPair); // building ret Key ret = buildKey(keyRingGen); return ret; } catch (Throwable t) { Throwables.propagateIfInstanceOf(t, FieldValidationException.class); throw new RuntimeException("Failed to generate key", t); } }
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();/*from w w w .ja v a 2s. c om*/ serverPrivKey = pair.getPrivate(); frontend.initialize(serverPubKey); }
From source file:netinf.common.security.impl.CryptographyTest.java
@Test public void testBadReaderKeyAlgorithm() { InformationObject informationObject = createTestInformationObject(); Hashtable<String, PublicKey> readers = new Hashtable<String, PublicKey>(); readers = new Hashtable<String, PublicKey>(); try {/* www . j a va 2s .c om*/ KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA"); keyPairGenerator.initialize(1024); KeyPair pair = keyPairGenerator.generateKeyPair(); PublicKey publicKey = pair.getPublic(); readers.put("any name", publicKey); } catch (Exception e) { throw new NetInfUncheckedException("error creating keys"); } try { crypto.encrypt(informationObject, readers); Assert.fail("Exception expected. Wrong reader name given."); } catch (NetInfCheckedSecurityException securityException) { System.out.println(securityException.getMessage()); } }
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;// ww w . j a va 2 s.c om } 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:org.guanxi.idp.Bootstrap.java
public boolean createSelfSignedKeystore(String cn, String keystoreFile, String keystorePassword, String privateKeyPassword, String privateKeyAlias) { KeyStore ks = null;/*w w w.ja va 2s . 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:org.apache.drill.cv.exec.server.rest.CvDrillWebServer.java
/** * Create an HTTPS connector for given jetty server instance. If the admin has specified * keystore/truststore settings they will be used else a self-signed certificate is generated and * used./*from w w w . j a v a2s .co m*/ * * @return Initialized {@link ServerConnector} for HTTPS connectios. * @throws Exception */ private ServerConnector createHttpsConnector() throws Exception { CvDrillWebServer.logger.info("Setting up HTTPS connector for web server"); final SslContextFactory sslContextFactory = new SslContextFactory(); if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH) && !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH))) { CvDrillWebServer.logger.info("Using configured SSL settings for web server"); sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH)); sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD)); // TrustStore and TrustStore password are optional if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) { sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH)); if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) { sslContextFactory .setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)); } } } else { CvDrillWebServer.logger.info("Using generated self-signed SSL settings for web server"); final SecureRandom random = new SecureRandom(); // Generate a private-public key pair final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024, random); final KeyPair keyPair = keyPairGenerator.generateKeyPair(); final DateTime now = DateTime.now(); // Create builder for certificate attributes final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE) .addRDN(BCStyle.OU, "Apache Drill (auth-generated)") .addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)") .addRDN(BCStyle.CN, workManager.getContext().getEndpoint().getAddress()); final Date notBefore = now.minusMinutes(1).toDate(); final Date notAfter = now.plusYears(5).toDate(); final BigInteger serialNumber = new BigInteger(128, random); // Create a certificate valid for 5years from now. final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), // attributes serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic()); // Sign the certificate using the private key final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption") .build(keyPair.getPrivate()); final X509Certificate certificate = new JcaX509CertificateConverter() .getCertificate(certificateBuilder.build(contentSigner)); // Check the validity certificate.checkValidity(now.toDate()); // Make sure the certificate is self-signed. certificate.verify(certificate.getPublicKey()); // Generate a random password for keystore protection final String keyStorePasswd = RandomStringUtils.random(20); final KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null); keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(), new java.security.cert.Certificate[] { certificate }); sslContextFactory.setKeyStore(keyStore); sslContextFactory.setKeyStorePassword(keyStorePasswd); } final HttpConfiguration httpsConfig = new HttpConfiguration(); httpsConfig.addCustomizer(new SecureRequestCustomizer()); // SSL Connector final ServerConnector sslConnector = new ServerConnector(embeddedJetty, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig)); sslConnector.setPort(getWebserverPort()); return sslConnector; }