List of usage examples for java.security KeyPairGenerator getInstance
public static KeyPairGenerator getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:com.cws.esolutions.security.dao.keymgmt.impl.FileKeyManager.java
/** * @see com.cws.esolutions.security.dao.keymgmt.interfaces.KeyManager#createKeys(java.lang.String) *//*from w w w.j a va 2 s .c o m*/ public synchronized boolean createKeys(final String guid) throws KeyManagementException { final String methodName = FileKeyManager.CNAME + "#createKeys(final String guid) throws KeyManagementException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", guid); } boolean isComplete = false; OutputStream publicStream = null; OutputStream privateStream = null; final File keyDirectory = FileUtils.getFile(keyConfig.getKeyDirectory() + "/" + guid); try { if (!(keyDirectory.exists())) { if (!(keyDirectory.mkdirs())) { throw new KeyManagementException( "Configured key directory does not exist and unable to create it"); } } keyDirectory.setExecutable(true, true); SecureRandom random = new SecureRandom(); KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(keyConfig.getKeyAlgorithm()); keyGenerator.initialize(keyConfig.getKeySize(), random); KeyPair keyPair = keyGenerator.generateKeyPair(); if (keyPair != null) { File privateFile = FileUtils .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PRIVATEKEY_FILE_EXT); File publicFile = FileUtils .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PUBLICKEY_FILE_EXT); if (!(privateFile.createNewFile())) { throw new IOException("Failed to store private key file"); } if (!(publicFile.createNewFile())) { throw new IOException("Failed to store public key file"); } privateFile.setWritable(true, true); publicFile.setWritable(true, true); privateStream = new FileOutputStream(privateFile); publicStream = new FileOutputStream(publicFile); IOUtils.write(keyPair.getPrivate().getEncoded(), privateStream); IOUtils.write(keyPair.getPublic().getEncoded(), publicStream); // assume success, as we'll get an IOException if the write failed isComplete = true; } else { throw new KeyManagementException("Failed to generate keypair. Cannot continue."); } } catch (FileNotFoundException fnfx) { throw new KeyManagementException(fnfx.getMessage(), fnfx); } catch (IOException iox) { throw new KeyManagementException(iox.getMessage(), iox); } catch (NoSuchAlgorithmException nsax) { throw new KeyManagementException(nsax.getMessage(), nsax); } finally { if (publicStream != null) { IOUtils.closeQuietly(publicStream); } if (privateStream != null) { IOUtils.closeQuietly(privateStream); } } return isComplete; }
From source file:org.wso2.carbon.keystore.mgt.KeyStoreGenerator.java
/** * This method generates the keypair and stores it in the keystore * * @param keyStore A keystore instance/* w w w. j a v a2s . c om*/ * @return Generated public key for the tenant * @throws KeyStoreMgtException Error when generating key pair */ private X509Certificate generateKeyPair(KeyStore keyStore) throws KeyStoreMgtException { try { CryptoUtil.getDefaultCryptoUtil(); //generate key pair KeyPairGenerator keyPairGenerator = null; keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // Common Name and alias for the generated certificate String commonName = "CN=" + tenantDomain + ", OU=None, O=None L=None, C=None"; //generate certificates AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder() .find("MD5WithRSAEncryption"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory .createKey(keyPair.getPrivate().getEncoded()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam); Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30); Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)); X509v3CertificateBuilder v3CertBuilder = new X509v3CertificateBuilder(new X500Name(commonName), BigInteger.valueOf(new SecureRandom().nextInt()), notBefore, notAfter, new X500Name(commonName), subPubKeyInfo); X509CertificateHolder certificateHolder = v3CertBuilder.build(sigGen); X509Certificate PKCertificate = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(certificateHolder); //add private key to KS keyStore.setKeyEntry(tenantDomain, keyPair.getPrivate(), password.toCharArray(), new java.security.cert.Certificate[] { PKCertificate }); return PKCertificate; } catch (Exception ex) { String msg = "Error while generating the certificate for tenant :" + tenantDomain + "."; log.error(msg, ex); throw new KeyStoreMgtException(msg, ex); } }
From source file:com.jonbanjo.cupsprint.CertificateActivity.java
public void doimport(View view) { try {/*from www . j a va 2 s .c o m*/ String url = "https://" + host.getText().toString() + ":" + port.getText().toString(); importButton.setEnabled(false); new importer().execute(url).get(3000, TimeUnit.MILLISECONDS); } catch (Exception e) { } finally { importButton.setEnabled(true); } if (certChain == null) { return; } for (X509Certificate cert : certChain) { try { cert.checkValidity(); } catch (Exception e) { showToast(e.toString()); return; } } String certString = certChain[0].toString(); final String alias = certChain[0].getSubjectX500Principal().getName(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Add Certificate?").setMessage(certString) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); trustStore.setKeyEntry(alias, privateKey, JfSSLScheme.password.toCharArray(), certChain); FileOutputStream outputStream = openFileOutput(JfSSLScheme.trustfile, MODE_PRIVATE); trustStore.store(outputStream, JfSSLScheme.password.toCharArray()); outputStream.flush(); outputStream.close(); certListAdaptor.add(alias); } catch (Exception e) { System.out.println(e.toString()); return; } } }).setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog dialog = builder.create(); dialog.show(); }
From source file:com.vmware.demo.SamlUtils.java
/** * Generate a RSA key pair (default size SamlUtils.keySize specified as 2048 bits) * * @return the new KeyPair/* ww w . j a va 2s . co m*/ * @throws SamlException */ public static KeyPair generateKey(int keySize) throws SamlException { KeyPair pair = null; try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(keySize); pair = keyGen.genKeyPair(); } catch (Exception e) { throw new SamlException("Failed to generate RSA signing key.", e); } return pair; }
From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java
/** * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#createCertificateRequest(List, String, int, int) *//*w w w.j ava 2s . c om*/ public synchronized File createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException { final String methodName = ICertificateManager.CNAME + "#createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", subjectData); DEBUGGER.debug("Value: {}", validityPeriod); DEBUGGER.debug("Value: {}", keySize); } final File rootDirectory = certConfig.getRootDirectory(); final String signatureAlgorithm = certConfig.getSignatureAlgorithm(); final String certificateAlgorithm = certConfig.getCertificateAlgorithm(); final File privateKeyDirectory = FileUtils .getFile(certConfig.getPrivateKeyDirectory() + "/" + subjectData.get(0)); final File publicKeyDirectory = FileUtils .getFile(certConfig.getPublicKeyDirectory() + "/" + subjectData.get(0)); final File csrDirectory = FileUtils.getFile(certConfig.getCsrDirectory() + "/" + subjectData.get(0)); final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + subjectData.get(0)); final X500Name x500Name = new X500Name("CN=" + subjectData.get(0) + ",OU=" + subjectData.get(1) + ",O=" + subjectData.get(2) + ",L=" + subjectData.get(3) + ",ST=" + subjectData.get(4) + ",C=" + subjectData.get(5) + ",E=" + subjectData.get(6)); if (DEBUG) { DEBUGGER.debug("rootDirectory: {}", rootDirectory); DEBUGGER.debug("signatureAlgorithm: {}", signatureAlgorithm); DEBUGGER.debug("certificateAlgorithm: {}", certificateAlgorithm); DEBUGGER.debug("privateKeyDirectory: {}", privateKeyDirectory); DEBUGGER.debug("publicKeyDirectory: {}", publicKeyDirectory); DEBUGGER.debug("csrDirectory: {}", csrDirectory); DEBUGGER.debug("storeDirectory: {}", storeDirectory); DEBUGGER.debug("x500Name: {}", x500Name); } File csrFile = null; JcaPEMWriter csrPemWriter = null; JcaPEMWriter publicKeyWriter = null; JcaPEMWriter privateKeyWriter = null; FileOutputStream csrFileStream = null; FileOutputStream keyStoreStream = null; FileOutputStream publicKeyFileStream = null; FileOutputStream privateKeyFileStream = null; OutputStreamWriter csrFileStreamWriter = null; OutputStreamWriter privateKeyStreamWriter = null; OutputStreamWriter publicKeyStreamWriter = null; try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, storePassword.toCharArray()); if (DEBUG) { DEBUGGER.debug("KeyStore: {}", keyStore); } SecureRandom random = new SecureRandom(); KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(certificateAlgorithm); keyGenerator.initialize(keySize, random); if (DEBUG) { DEBUGGER.debug("KeyGenerator: {}", keyGenerator); } KeyPair keyPair = keyGenerator.generateKeyPair(); if (DEBUG) { DEBUGGER.debug("KeyPair: {}", keyPair); } if (keyPair != null) { final Signature sig = Signature.getInstance(signatureAlgorithm); final PrivateKey privateKey = keyPair.getPrivate(); final PublicKey publicKey = keyPair.getPublic(); if (DEBUG) { DEBUGGER.debug("Signature: {}", sig); DEBUGGER.debug("PrivateKey: {}", privateKey); DEBUGGER.debug("PublicKey: {}", publicKey); } sig.initSign(privateKey, random); ContentSigner signGen = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey); if (DEBUG) { DEBUGGER.debug("ContentSigner: {}", signGen); } Calendar expiry = Calendar.getInstance(); expiry.add(Calendar.DAY_OF_YEAR, validityPeriod); if (DEBUG) { DEBUGGER.debug("Calendar: {}", expiry); } CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType()); if (DEBUG) { DEBUGGER.debug("CertificateFactory: {}", certFactory); } X509Certificate[] issuerCert = new X509Certificate[] { (X509Certificate) certFactory .generateCertificate(new FileInputStream(certConfig.getIntermediateCertificateFile())) }; if (DEBUG) { DEBUGGER.debug("X509Certificate[]: {}", (Object) issuerCert); } keyStore.setCertificateEntry(certConfig.getRootCertificateName(), certFactory.generateCertificate( new FileInputStream(FileUtils.getFile(certConfig.getRootCertificateFile())))); keyStore.setCertificateEntry(certConfig.getIntermediateCertificateName(), certFactory.generateCertificate(new FileInputStream( FileUtils.getFile(certConfig.getIntermediateCertificateFile())))); PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name, publicKey); if (DEBUG) { DEBUGGER.debug("PKCS10CertificationRequestBuilder: {}", builder); } PKCS10CertificationRequest csr = builder.build(signGen); if (DEBUG) { DEBUGGER.debug("PKCS10CertificationRequest: {}", csr); } // write private key File privateKeyFile = FileUtils.getFile(privateKeyDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.PRIVATEKEY_FILE_EXT); if (DEBUG) { DEBUGGER.debug("privateKeyFile: {}", privateKeyFile); } if (!(privateKeyFile.createNewFile())) { throw new IOException("Failed to store private file"); } privateKeyFileStream = new FileOutputStream(privateKeyFile); privateKeyStreamWriter = new OutputStreamWriter(privateKeyFileStream); if (DEBUG) { DEBUGGER.debug("privateKeyFileStream: {}", privateKeyFileStream); DEBUGGER.debug("privateKeyStreamWriter: {}", privateKeyStreamWriter); } privateKeyWriter = new JcaPEMWriter(privateKeyStreamWriter); privateKeyWriter.writeObject(privateKey); privateKeyWriter.flush(); privateKeyStreamWriter.flush(); privateKeyFileStream.flush(); // write public key File publicKeyFile = FileUtils.getFile(publicKeyDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.PUBLICKEY_FILE_EXT); if (DEBUG) { DEBUGGER.debug("publicKeyFile: {}", publicKeyFile); } if (!(publicKeyFile.createNewFile())) { throw new IOException("Failed to store public key file"); } publicKeyFileStream = new FileOutputStream(publicKeyFile); publicKeyStreamWriter = new OutputStreamWriter(publicKeyFileStream); if (DEBUG) { DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream); DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter); } publicKeyWriter = new JcaPEMWriter(publicKeyStreamWriter); publicKeyWriter.writeObject(publicKey); publicKeyWriter.flush(); publicKeyStreamWriter.flush(); publicKeyFileStream.flush(); // write csr csrFile = FileUtils .getFile(csrDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.CSR_FILE_EXT); if (DEBUG) { DEBUGGER.debug("csrFile: {}", csrFile); } if (!(csrFile.createNewFile())) { throw new IOException("Failed to store CSR file"); } csrFileStream = new FileOutputStream(csrFile); csrFileStreamWriter = new OutputStreamWriter(csrFileStream); if (DEBUG) { DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream); DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter); } csrPemWriter = new JcaPEMWriter(csrFileStreamWriter); csrPemWriter.writeObject(csr); csrPemWriter.flush(); csrFileStreamWriter.flush(); csrFileStream.flush(); File keyStoreFile = FileUtils .getFile(storeDirectory + "/" + subjectData.get(0) + "." + KeyStore.getDefaultType()); if (DEBUG) { DEBUGGER.debug("keyStoreFile: {}", keyStoreFile); } keyStoreStream = FileUtils.openOutputStream(keyStoreFile); if (DEBUG) { DEBUGGER.debug("keyStoreStream: {}", keyStoreStream); } keyStore.setKeyEntry(subjectData.get(0), (Key) keyPair.getPrivate(), storePassword.toCharArray(), issuerCert); keyStore.store(keyStoreStream, storePassword.toCharArray()); keyStoreStream.flush(); if (DEBUG) { DEBUGGER.debug("KeyStore: {}", keyStore); } } else { throw new CertificateManagementException("Failed to generate keypair. Cannot continue."); } } catch (FileNotFoundException fnfx) { throw new CertificateManagementException(fnfx.getMessage(), fnfx); } catch (IOException iox) { throw new CertificateManagementException(iox.getMessage(), iox); } catch (NoSuchAlgorithmException nsax) { throw new CertificateManagementException(nsax.getMessage(), nsax); } catch (IllegalStateException isx) { throw new CertificateManagementException(isx.getMessage(), isx); } catch (InvalidKeyException ikx) { throw new CertificateManagementException(ikx.getMessage(), ikx); } catch (OperatorCreationException ocx) { throw new CertificateManagementException(ocx.getMessage(), ocx); } catch (KeyStoreException ksx) { throw new CertificateManagementException(ksx.getMessage(), ksx); } catch (CertificateException cx) { throw new CertificateManagementException(cx.getMessage(), cx); } finally { if (csrFileStreamWriter != null) { IOUtils.closeQuietly(csrFileStreamWriter); } if (csrFileStream != null) { IOUtils.closeQuietly(csrFileStream); } if (csrPemWriter != null) { IOUtils.closeQuietly(csrPemWriter); } if (publicKeyFileStream != null) { IOUtils.closeQuietly(publicKeyFileStream); } if (publicKeyStreamWriter != null) { IOUtils.closeQuietly(publicKeyStreamWriter); } if (publicKeyWriter != null) { IOUtils.closeQuietly(publicKeyWriter); } if (privateKeyFileStream != null) { IOUtils.closeQuietly(privateKeyFileStream); } if (privateKeyStreamWriter != null) { IOUtils.closeQuietly(privateKeyStreamWriter); } if (privateKeyWriter != null) { IOUtils.closeQuietly(privateKeyWriter); } if (keyStoreStream != null) { IOUtils.closeQuietly(keyStoreStream); } } return csrFile; }
From source file:com.tcs.ebw.security.EBWSecurity.java
/** /* ww w . j av a2 s. co m*/ * This method is used to generate keypairs for using with Asymmetric cryptography. * This method generates and stores private and public keys in their respective * objects. Later these keys can be used in appropriate places in Encyption * and Decryption using PublicKeyCryptography or Asymmetric Cryptography methods. * * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws NoSuchProviderException */ private void generateKeyPairsForAsymmetric() throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException { /** KeyPair Generation required for Asymmetric Crypto **/ if (kpg == null) { // //EBWLogger.logDebug(this,"Provider added successully"); kpg = KeyPairGenerator.getInstance(EBWConstants.ENCRYPTION_ASYMMETRIC_ALGORITHM); ////EBWLogger.logDebug(this,"Keypair generated successfully.."); kpg.initialize(1024); kp = kpg.generateKeyPair(); priKey = kp.getPrivate(); pubKey = kp.getPublic(); //if(priKey!=null && pubKey!=null) ////EBWLogger.logDebug(this,"Private / Public keys generated successfully.."); } /** Initialize cipher used for Asymmetric Crypto **/ ////EBWLogger.logDebug(this,"Getting Cipher instance."); cipherAsymmetric = Cipher.getInstance(EBWConstants.ENCRYPTION_ASYMMETRIC_ALGORITHM); }
From source file:test.unit.org.owasp.webscarab.util.SunCertificateUtilsTest.java
private KeyPair generateKeyPair(int size) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); keyPairGenerator.initialize(new RSAKeyGenParameterSpec(size, RSAKeyGenParameterSpec.F4), random); KeyPair keyPair = keyPairGenerator.generateKeyPair(); return keyPair; }
From source file:de.pawlidi.openaletheia.utils.CipherUtils.java
/** * //from ww w. j a va 2 s . c o m * @return */ public static KeyPair generateKeyPair() { KeyPairGenerator generator = null; SecureRandom secureRandom = null; try { generator = KeyPairGenerator.getInstance(CIPHER_ALGORITHM); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Could not generate key", e); } try { secureRandom = SecureRandom.getInstance(RANDOM_NUMBER_GENERATOR_ALGORITHM, "SUN"); } catch (NoSuchAlgorithmException | NoSuchProviderException e) { // ignore exception } if (secureRandom == null) { generator.initialize(2048); } else { generator.initialize(2048, secureRandom); } return generator.generateKeyPair(); }
From source file:com.streamsets.pipeline.lib.remote.SSHDUnitTest.java
protected KeyPair generateKeyPair() throws Exception { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048);//from w ww . j a va2 s. c o m return keyGen.generateKeyPair(); }
From source file:org.candlepin.CRLWriteBenchmark.java
@Setup(Level.Trial) public void createKey() throws Exception { KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048);/*from www . j a v a2s. co m*/ keyPair = generator.generateKeyPair(); }