List of usage examples for java.security KeyPairGenerator getInstance
public static KeyPairGenerator getInstance(String algorithm, Provider provider) throws NoSuchAlgorithmException
From source file:org.xdi.oxauth.model.util.JwtUtil.java
public static KeyPair generateRsaKey() throws NoSuchAlgorithmException, NoSuchProviderException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC"); keyGen.initialize(2048, new SecureRandom()); return keyGen.generateKeyPair(); }
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 w w w .ja va2 s . co m // 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.cesecore.certificates.util.AlgorithmTools.java
/** Check if the curve name is known by the first found PKCS#11 provider or default (if none was found)*/ public static boolean isNamedECKnownInDefaultProvider(String ecNamedCurveBc) { final Provider[] providers = Security.getProviders("KeyPairGenerator.EC"); String providerName = providers[0].getName(); try {// www . ja va 2 s .c om for (Provider ecProvider : providers) { //This will list something like: SunPKCS11-NSS, BC, SunPKCS11-<library>-slot<slotnumber> if (log.isDebugEnabled()) { log.debug("Found EC capable provider named: " + ecProvider.getName()); } if (ecProvider.getName().startsWith("SunPKCS11-") && !ecProvider.getName().startsWith("SunPKCS11-NSS")) { providerName = ecProvider.getName(); break; } } final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", providerName); kpg.initialize(new ECGenParameterSpec(ecNamedCurveBc)); return true; } catch (InvalidAlgorithmParameterException e) { if (log.isDebugEnabled()) { log.debug(ecNamedCurveBc + " is not available in provider " + providerName); } } catch (NoSuchAlgorithmException e) { throw new RuntimeException( "EC capable provider " + providerName + " could no longer handle elliptic curve algorithm..", e); } catch (NoSuchProviderException e) { throw new RuntimeException("EC capable provider " + providerName + " disappeard unexpectedly.", e); } return false; }
From source file:org.signserver.server.cryptotokens.KeystoreCryptoTokenTest.java
/** * Test importing a new certificate chain to an existing keystore. * @throws Exception /*from w w w.j av a 2 s . c o m*/ */ public void testImportCertificateChain() throws Exception { LOG.info("testImportCertificateChain"); final boolean autoActivate = false; final int workerId = WORKER_CMS; try { setCMSSignerPropertiesCombined(workerId, autoActivate); // Generate key and issue certificate final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC"); kpg.initialize(1024); final KeyPair keyPair = kpg.generateKeyPair(); // Create a key-pair and certificate in the keystore FileOutputStream out = null; try { KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(null, null); final X509Certificate[] chain = new X509Certificate[1]; chain[0] = getSelfCertificate("CN=Test", (long) 30 * 24 * 60 * 60 * 365, keyPair); ks.setKeyEntry("newkey11", keyPair.getPrivate(), pin.toCharArray(), chain); out = new FileOutputStream(keystoreFile); ks.store(out, pin.toCharArray()); } finally { IOUtils.closeQuietly(out); } workerSession.setWorkerProperty(workerId, "DEFAULTKEY", "newkey11"); workerSession.reloadConfiguration(workerId); // Activate first so we can generate a key workerSession.activateSigner(workerId, pin); List<String> errors = workerSession.getStatus(workerId).getFatalErrors(); assertTrue("Fatal errors: " + errors, workerSession.getStatus(workerId).getFatalErrors().isEmpty()); // generate a new certificate final X509Certificate newCert = getSelfCertificate("CN=TestNew", (long) 30 * 24 * 60 * 60 * 365, keyPair); workerSession.importCertificateChain(workerId, Arrays.asList(newCert.getEncoded()), "newkey11", null); final Certificate readCert = workerSession.getSignerCertificate(workerId); assertTrue("Matching certificates", Arrays.equals(newCert.getEncoded(), readCert.getEncoded())); } finally { FileUtils.deleteQuietly(keystoreFile); removeWorker(workerId); } }
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 ava2s. c o m */ 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:net.maritimecloud.identityregistry.utils.CertificateUtil.java
/** * Generates a keypair (public and private) based on Elliptic curves. * //from ww w. j av a2s . c o m * @return The generated keypair */ public static KeyPair generateKeyPair() { ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("secp384r1"); KeyPairGenerator g; try { g = KeyPairGenerator.getInstance("ECDSA", BC_PROVIDER_NAME); } catch (NoSuchAlgorithmException | NoSuchProviderException e) { throw new RuntimeException(e.getMessage(), e); } try { g.initialize(ecGenSpec, new SecureRandom()); } catch (InvalidAlgorithmParameterException e) { throw new RuntimeException(e.getMessage(), e); } KeyPair pair = g.generateKeyPair(); return pair; }
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 w w w . j ava 2 s . c o m 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); } }
From source file:org.texai.x509.X509Utils.java
/** Creates a random 3072 bit RSA key pair. * @return a random 3072 bit RSA key pair * @throws NoSuchAlgorithmException when an invalid algorithm is given * @throws NoSuchProviderException when an invalid provider is given * @throws InvalidAlgorithmParameterException when an invalid algorithm parameter is given *//* ww w. java2 s . co m*/ public static KeyPair generateRSAKeyPair3072() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException { final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", BOUNCY_CASTLE_PROVIDER); final AlgorithmParameterSpec algorithmParameterSpec = new RSAKeyGenParameterSpec(3072, RSAKeyGenParameterSpec.F4); keyPairGenerator.initialize(algorithmParameterSpec, getSecureRandom()); return keyPairGenerator.generateKeyPair(); }
From source file:org.xdi.oxauth.model.util.JwtUtil.java
public static KeyPair generateKeyES256() throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("P-256"); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDSA", "BC"); keyGen.initialize(ecSpec, new SecureRandom()); return keyGen.generateKeyPair(); }
From source file:org.xdi.oxauth.model.util.JwtUtil.java
public static KeyPair generateKeyES384() throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("P-384"); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDSA", "BC"); keyGen.initialize(ecSpec, new SecureRandom()); return keyGen.generateKeyPair(); }