List of usage examples for java.security KeyPairGenerator initialize
public void initialize(AlgorithmParameterSpec params) throws InvalidAlgorithmParameterException
From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java
/** * Initialize the Diffie-Hellman keys. This method is not thread safe *///w w w .jav a2 s . co m public static void initDHKeys(DistributionConfig config) throws Exception { dhSKAlgo = config.getSecurityClientDHAlgo(); dhPrivateKey = null; dhPublicKey = null; // Initialize the keys when either the host is a client that has // non-blank setting for DH symmetric algo, or this is a server // that has authenticator defined. if ((dhSKAlgo != null && dhSKAlgo.length() > 0) /* || securityService.isClientSecurityRequired() */) { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH"); DHParameterSpec dhSpec = new DHParameterSpec(dhP, dhG, dhL); keyGen.initialize(dhSpec); KeyPair keypair = keyGen.generateKeyPair(); // Get the generated public and private keys dhPrivateKey = keypair.getPrivate(); dhPublicKey = keypair.getPublic(); random = new SecureRandom(); // Force the random generator to seed itself. byte[] someBytes = new byte[48]; random.nextBytes(someBytes); } }
From source file:org.cesecore.keys.util.KeyStoreTools.java
private void generateRSA(final int keySize, final String keyEntryName) { if (log.isTraceEnabled()) { log.trace(">generate: keySize " + keySize + ", keyEntryName " + keyEntryName); }//from w ww .jav a 2 s . c o m // Generate the RSA Keypair KeyPairGenerator kpg; try { kpg = KeyPairGenerator.getInstance("RSA", this.providerName); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Algorithm " + "RSA" + "was not recognized.", e); } catch (NoSuchProviderException e) { throw new IllegalStateException("BouncyCastle was not found as a provider.", e); } kpg.initialize(keySize); generateKeyPair(kpg, keyEntryName, "SHA1withRSA"); if (log.isTraceEnabled()) { log.trace("<generate: keySize " + keySize + ", keyEntryName " + keyEntryName); } }
From source file:org.cesecore.keys.util.KeyStoreTools.java
private void generateDSA(final int keySize, final String keyEntryName) { if (log.isTraceEnabled()) { log.trace(">generate: keySize " + keySize + ", keyEntryName " + keyEntryName); }/*from www.j a v a 2s. c om*/ // Generate the RSA Keypair KeyPairGenerator kpg; try { kpg = KeyPairGenerator.getInstance("DSA", this.providerName); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Algorithm " + "DSA" + "was not recognized.", e); } catch (NoSuchProviderException e) { throw new IllegalStateException("BouncyCastle was not found as a provider.", e); } kpg.initialize(keySize); generateKeyPair(kpg, keyEntryName, "SHA1withDSA"); if (log.isTraceEnabled()) { log.trace("<generate: keySize " + keySize + ", keyEntryName " + keyEntryName); } }
From source file:org.jenkinsci.remoting.engine.HandlerLoopbackLoadStress.java
public HandlerLoopbackLoadStress(Config config) throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException, UnrecoverableKeyException, KeyManagementException, OperatorCreationException { this.config = config; KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA"); gen.initialize(2048); // maximum supported by JVM with export restrictions keyPair = gen.generateKeyPair();/*from w w w . j a va 2 s. co m*/ Date now = new Date(); Date firstDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(10)); Date lastDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(-10)); SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo .getInstance(keyPair.getPublic().getEncoded()); X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); X500Name subject = nameBuilder.addRDN(BCStyle.CN, getClass().getSimpleName()).addRDN(BCStyle.C, "US") .build(); X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(subject, BigInteger.ONE, firstDate, lastDate, subject, subjectPublicKeyInfo); JcaX509ExtensionUtils instance = new JcaX509ExtensionUtils(); certGen.addExtension(X509Extension.subjectKeyIdentifier, false, instance.createSubjectKeyIdentifier(subjectPublicKeyInfo)); ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BOUNCY_CASTLE_PROVIDER) .build(keyPair.getPrivate()); certificate = new JcaX509CertificateConverter().setProvider(BOUNCY_CASTLE_PROVIDER) .getCertificate(certGen.build(signer)); char[] password = "password".toCharArray(); KeyStore store = KeyStore.getInstance("jks"); store.load(null, password); store.setKeyEntry("alias", keyPair.getPrivate(), password, new Certificate[] { certificate }); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(store, password); context = SSLContext.getInstance("TLS"); context.init(kmf.getKeyManagers(), new TrustManager[] { new BlindTrustX509ExtendedTrustManager() }, null); mainHub = IOHub.create(executorService); // on windows there is a bug whereby you cannot mix ServerSockets and Sockets on the same selector acceptorHub = File.pathSeparatorChar == 59 ? IOHub.create(executorService) : mainHub; legacyHub = new NioChannelHub(executorService); executorService.submit(legacyHub); serverSocketChannel = ServerSocketChannel.open(); JnlpProtocolHandler handler = null; for (JnlpProtocolHandler h : new JnlpProtocolHandlerFactory(executorService).withNioChannelHub(legacyHub) .withIOHub(mainHub).withSSLContext(context).withPreferNonBlockingIO(!config.bio) .withClientDatabase(new JnlpClientDatabase() { @Override public boolean exists(String clientName) { return true; } @Override public String getSecretOf(@Nonnull String clientName) { return secretFor(clientName); } }).withSSLClientAuthRequired(false).handlers()) { if (config.name.equals(h.getName())) { handler = h; break; } } if (handler == null) { throw new RuntimeException("Unknown handler: " + config.name); } this.handler = handler; acceptor = new Acceptor(serverSocketChannel); runtimeMXBean = ManagementFactory.getRuntimeMXBean(); operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); _getProcessCpuTime = _getProcessCpuTime(operatingSystemMXBean); garbageCollectorMXBeans = new ArrayList<GarbageCollectorMXBean>( ManagementFactory.getGarbageCollectorMXBeans()); Collections.sort(garbageCollectorMXBeans, new Comparator<GarbageCollectorMXBean>() { @Override public int compare(GarbageCollectorMXBean o1, GarbageCollectorMXBean o2) { return o1.getName().compareTo(o2.getName()); } }); stats = new Stats(); }
From source file:edu.uiuc.ncsa.myproxy.MyProxyLogon.java
/** * Retrieves credentials from the MyProxy server. *///from w ww . j a v a 2s.c o m public void getCredentials() throws IOException, GeneralSecurityException { KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(keyAlg); keyGenerator.initialize(getKeySize()); this.keypair = keyGenerator.genKeyPair(); MyPKCS10CertRequest pkcs10 = CertUtil.createCertRequest(this.keypair, pkcs10SigAlgName, DN, pkcs10Provider); getCredentials(pkcs10.getEncoded()); }
From source file:org.cesecore.keys.util.KeyStoreTools.java
/** Generates keys in the Keystore token. * @param spec AlgorithmParameterSpec for the KeyPairGenerator. Can be anything like RSAKeyGenParameterSpec, DSAParameterSpec, ECParameterSpec or ECGenParameterSpec. * @param keyEntryName// w w w . j a va 2 s . c om */ public void generateKeyPair(final AlgorithmParameterSpec spec, final String keyEntryName) throws InvalidAlgorithmParameterException, CertificateException, IOException { if (log.isTraceEnabled()) { log.trace(">generate from AlgorithmParameterSpec: " + spec.getClass().getName()); } // Generate the Keypair String algorithm = "EC"; String sigAlg = "SHA1withECDSA"; String specName = spec.getClass().getName(); if (specName.contains("DSA")) { algorithm = "DSA"; sigAlg = "SHA1withDSA"; } else if (specName.contains("RSA")) { algorithm = "RSA"; sigAlg = "SHA1withRSA"; } KeyPairGenerator kpg; try { kpg = KeyPairGenerator.getInstance(algorithm, this.providerName); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Algorithm " + algorithm + " was not recognized.", e); } catch (NoSuchProviderException e) { throw new IllegalStateException("BouncyCastle was not found as a provider.", e); } try { kpg.initialize(spec); } catch (InvalidAlgorithmParameterException e) { log.debug("Algorithm parameters not supported: " + e.getMessage()); throw e; } generateKeyPair(kpg, keyEntryName, sigAlg); if (log.isTraceEnabled()) { log.trace("<generate from AlgorithmParameterSpec: " + spec.getClass().getName()); } }
From source file:org.cesecore.keys.util.KeyStoreTools.java
private void generateExtraEC(final String name, final String keyEntryName, final String algInstanceName, final String sigAlgName) throws InvalidAlgorithmParameterException { if (log.isTraceEnabled()) { log.trace(">generate " + algInstanceName + ": curve name " + name + ", keyEntryName " + keyEntryName); }//from w w w . ja v a 2 s . c o m // Generate the EC Keypair KeyPairGenerator kpg; try { kpg = KeyPairGenerator.getInstance(algInstanceName, this.providerName); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Algorithm " + name + "was not recognized.", e); } catch (NoSuchProviderException e) { throw new IllegalStateException("BouncyCastle was not found as a provider.", e); } try { ECGenParameterSpec ecSpec = new ECGenParameterSpec(name); kpg.initialize(ecSpec); } catch (InvalidAlgorithmParameterException e) { log.debug("EC " + algInstanceName + " name " + name + " not supported."); throw e; } generateKeyPair(kpg, keyEntryName, sigAlgName); if (log.isTraceEnabled()) { log.trace("<generate: curve name " + name + ", keyEntryName " + keyEntryName); } }
From source file:com.poscoict.license.service.BoardService.java
public Map<String, Object> passwordPop(HttpSession session) throws Exception { logger.info("get passwordPopForm"); Map<String, Object> map = new HashMap<String, Object>(); KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048); KeyPair keyPair = generator.genKeyPair(); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); // ? ? ?? ? . session.setAttribute("__rsaPrivateKey__", privateKey); // ? JavaScript RSA ?? . RSAPublicKeySpec publicSpec = (RSAPublicKeySpec) keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class); map.put("publicKeyModulus", publicSpec.getModulus().toString(16)); map.put("publicKeyExponent", publicSpec.getPublicExponent().toString(16)); logger.info("return passwordPopForm"); return map;/*w w w .j a va 2 s .c om*/ }
From source file:com.otterca.common.crypto.acceptance.X509CertificateBuilderAcceptanceTest.java
/** * Default constructor.//from w ww .j a v a2 s . co m * * @throws Exception */ protected X509CertificateBuilderAcceptanceTest() throws GeneralSecurityException, InvalidNameException, URISyntaxException, UnknownHostException, IOException { certUtil = new X509CertificateUtilImpl(); TimeZone.setDefault(TimeZone.getTimeZone("UTC")); // create key pairs. this is for testing so we use 512-bit keys for // speed. KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); keyPairGen.initialize(512); keyPair = keyPairGen.generateKeyPair(); issuerKeyPair = keyPairGen.generateKeyPair(); grandfatherKeyPair = keyPairGen.generateKeyPair(); notBefore = Calendar.getInstance(); notBefore.set(Calendar.MINUTE, 0); notBefore.set(Calendar.SECOND, 0); notBefore.set(Calendar.MILLISECOND, 0); notAfter = Calendar.getInstance(); notAfter.setTime(notBefore.getTime()); notAfter.add(Calendar.YEAR, 1); expectedGeneralNameUri1 = new com.otterca.common.crypto.GeneralName.URI("http://example.com"); expectedGeneralNameUri2 = new com.otterca.common.crypto.GeneralName.URI("ldap://example.net"); expectedGeneralNameDir = new com.otterca.common.crypto.GeneralName.Directory("C=US,ST=AK,C=Anchorage"); expectedGeneralNameEmail = new com.otterca.common.crypto.GeneralName.Email("bob@example.com"); expectedGeneralNameDns = new com.otterca.common.crypto.GeneralName.DNS("example.com"); expectedGeneralNameIpAddress = new com.otterca.common.crypto.GeneralName.IpAddress("127.0.0.1"); }
From source file:org.signserver.server.cryptotokens.KeystoreCryptoToken.java
@Override public void generateKey(String keyAlgorithm, String keySpec, String alias, char[] authCode, Map<String, Object> params, IServices services) throws CryptoTokenOfflineException, IllegalArgumentException { if (keySpec == null) { throw new IllegalArgumentException("Missing keyspec parameter"); }/*from ww w . ja v a 2 s. c om*/ if (alias == null) { throw new IllegalArgumentException("Missing alias parameter"); } if (LOG.isDebugEnabled()) { LOG.debug("keyAlgorithm: " + keyAlgorithm + ", keySpec: " + keySpec + ", alias: " + alias); } try { final KeyStore keystore = getKeyStore(); // Check key generation limit, if configured if (keygenerationLimit != null && keygenerationLimit > -1) { final int current; try { current = keystore.size(); if (current >= keygenerationLimit) { throw new TokenOutOfSpaceException("Key generation limit exceeded: " + current); } } catch (KeyStoreException ex) { LOG.error("Checking key generation limit failed", ex); throw new TokenOutOfSpaceException( "Current number of key entries could not be obtained: " + ex.getMessage(), ex); } } final KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgorithm, "BC"); if ("ECDSA".equals(keyAlgorithm)) { kpg.initialize(ECNamedCurveTable.getParameterSpec(keySpec)); } else { kpg.initialize(Integer.valueOf(keySpec)); } final String sigAlgName = "SHA1With" + keyAlgorithm; LOG.debug("generating..."); final KeyPair keyPair = kpg.generateKeyPair(); Certificate[] chain = new Certificate[1]; chain[0] = CryptoTokenHelper.createDummyCertificate(alias, sigAlgName, keyPair, getProvider(PROVIDERUSAGE_SIGN)); LOG.debug("Creating certificate with entry " + alias + '.'); keystore.setKeyEntry(alias, keyPair.getPrivate(), authCode, chain); final OutputStream os; if (TYPE_INTERNAL.equalsIgnoreCase(keystoretype)) { os = new ByteArrayOutputStream(); } else { os = new FileOutputStream(new File(keystorepath)); } keystore.store(os, authenticationCode); if (TYPE_INTERNAL.equalsIgnoreCase(keystoretype)) { final ByteArrayOutputStream baos = (ByteArrayOutputStream) os; final IWorkerSession.ILocal workerSessionLocal = services.get(IWorkerSession.ILocal.class); if (workerSessionLocal == null) { throw new IllegalStateException("No WorkerSession available"); } workerSessionLocal.setKeystoreData(new AdminInfo("Internal", null, null), workerId, baos.toByteArray()); } final KeyEntry entry = new KeyEntry((PrivateKey) keyPair.getPrivate(), chain[0], Arrays.asList(chain)); // If this is the first entry entries.put(alias, entry); if (properties.getProperty(DEFAULTKEY) == null) { properties.setProperty(DEFAULTKEY, alias); entries.put(ICryptoToken.PURPOSE_SIGN, entry); entries.put(ICryptoToken.PURPOSE_DECRYPT, entry); } } catch (UnsupportedOperationException ex) { LOG.error(ex, ex); throw new CryptoTokenOfflineException(ex); } catch (KeyStoreException ex) { LOG.error(ex, ex); throw new CryptoTokenOfflineException(ex); } catch (NoSuchAlgorithmException ex) { LOG.error(ex, ex); throw new CryptoTokenOfflineException(ex); } catch (NoSuchProviderException ex) { LOG.error(ex, ex); throw new CryptoTokenOfflineException(ex); } catch (InvalidAlgorithmParameterException ex) { LOG.error(ex, ex); throw new CryptoTokenOfflineException(ex); } catch (NumberFormatException ex) { LOG.error(ex, ex); throw new CryptoTokenOfflineException(ex); } catch (OperatorCreationException ex) { LOG.error(ex, ex); throw new CryptoTokenOfflineException(ex); } catch (CertificateException ex) { LOG.error(ex, ex); throw new CryptoTokenOfflineException(ex); } catch (IOException ex) { LOG.error(ex, ex); throw new CryptoTokenOfflineException(ex); } catch (IllegalStateException ex) { LOG.error(ex, ex); throw new CryptoTokenOfflineException(ex); } }