List of usage examples for java.security KeyPairGenerator generateKeyPair
public KeyPair generateKeyPair()
From source file:org.xdi.oxauth.model.crypto.OxAuthCryptoProvider.java
@Override public JSONObject generateKey(SignatureAlgorithm signatureAlgorithm, Long expirationTime) throws Exception { KeyPairGenerator keyGen = null; if (signatureAlgorithm == null) { throw new RuntimeException("The signature algorithm parameter cannot be null"); } else if (SignatureAlgorithmFamily.RSA.equals(signatureAlgorithm.getFamily())) { keyGen = KeyPairGenerator.getInstance(signatureAlgorithm.getFamily(), "BC"); keyGen.initialize(2048, new SecureRandom()); } else if (SignatureAlgorithmFamily.EC.equals(signatureAlgorithm.getFamily())) { ECGenParameterSpec eccgen = new ECGenParameterSpec(signatureAlgorithm.getCurve().getAlias()); keyGen = KeyPairGenerator.getInstance(signatureAlgorithm.getFamily(), "BC"); keyGen.initialize(eccgen, new SecureRandom()); } else {/*from w ww . ja v a 2 s .c om*/ throw new RuntimeException("The provided signature algorithm parameter is not supported"); } // Generate the key KeyPair keyPair = keyGen.generateKeyPair(); java.security.PrivateKey pk = keyPair.getPrivate(); // Java API requires a certificate chain X509Certificate cert = generateV3Certificate(keyPair, dnName, signatureAlgorithm.getAlgorithm(), expirationTime); X509Certificate[] chain = new X509Certificate[1]; chain[0] = cert; String alias = UUID.randomUUID().toString(); keyStore.setKeyEntry(alias, pk, keyStoreSecret.toCharArray(), chain); FileOutputStream stream = new FileOutputStream(keyStoreFile); keyStore.store(stream, keyStoreSecret.toCharArray()); PublicKey publicKey = keyPair.getPublic(); JSONObject jsonObject = new JSONObject(); jsonObject.put(KEY_TYPE, signatureAlgorithm.getFamily()); jsonObject.put(KEY_ID, alias); jsonObject.put(KEY_USE, Use.SIGNATURE); jsonObject.put(ALGORITHM, signatureAlgorithm.getName()); jsonObject.put(EXPIRATION_TIME, expirationTime); if (publicKey instanceof RSAPublicKey) { RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; jsonObject.put(MODULUS, Base64Util.base64urlencodeUnsignedBigInt(rsaPublicKey.getModulus())); jsonObject.put(EXPONENT, Base64Util.base64urlencodeUnsignedBigInt(rsaPublicKey.getPublicExponent())); } else if (publicKey instanceof ECPublicKey) { ECPublicKey ecPublicKey = (ECPublicKey) publicKey; jsonObject.put(CURVE, signatureAlgorithm.getCurve()); jsonObject.put(X, Base64Util.base64urlencodeUnsignedBigInt(ecPublicKey.getW().getAffineX())); jsonObject.put(Y, Base64Util.base64urlencodeUnsignedBigInt(ecPublicKey.getW().getAffineY())); } JSONArray x5c = new JSONArray(); x5c.put(Base64.encodeBase64String(cert.getEncoded())); jsonObject.put(CERTIFICATE_CHAIN, x5c); return jsonObject; }
From source file:duthientan.mmanm.com.Main.java
private void BntGenerationKeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BntGenerationKeyActionPerformed // TODO add your handling code here: if (filePath.size() != 0) { progressBarCipher.setIndeterminate(true); new Thread(new Runnable() { @Override//from w w w. j a v a 2 s . c o m public void run() { try { Path path = Paths.get(filePath.get(0)); String srcParent = path.getParent().toString(); final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); final KeyPair key = keyGen.generateKeyPair(); File privateKeyFile = new File(srcParent + "/private.key"); File publicKeyFile = new File(srcParent + "/public.key"); publicKeyFile.createNewFile(); publicKeyFile.createNewFile(); ObjectOutputStream publicKeyOS = new ObjectOutputStream( new FileOutputStream(publicKeyFile)); publicKeyOS.writeObject(key.getPublic()); publicKeyOS.close(); ObjectOutputStream privateKeyOS = new ObjectOutputStream( new FileOutputStream(privateKeyFile)); privateKeyOS.writeObject(key.getPrivate()); privateKeyOS.close(); progressBarCipher.setIndeterminate(false); JFrame frame = new JFrame("COMPLETED"); JOptionPane.showMessageDialog(frame, "Greneration Key File Completed"); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } }).start(); } else { JFrame frame = new JFrame("ERROR"); JOptionPane.showMessageDialog(frame, "Please Choice File To Cipher Before Greneration Key"); } }
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"); }// www. java2s . 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:com.mirth.connect.server.controllers.DefaultConfigurationController.java
/** * Checks for an existing certificate to use for secure communication between the server and * client. If no certficate exists, this will generate a new one. * /*from www .ja v a2 s . c o m*/ */ private void generateDefaultCertificate(Provider provider, KeyStore keyStore, char[] keyPassword) throws Exception { final String certificateAlias = "mirthconnect"; if (!keyStore.containsAlias(certificateAlias)) { // Common CA and SSL cert attributes Date startDate = new Date(); // time from which certificate is valid Date expiryDate = DateUtils.addYears(startDate, 50); // time after which certificate is not valid KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", provider); keyPairGenerator.initialize(2048); KeyPair caKeyPair = keyPairGenerator.generateKeyPair(); logger.debug("generated new key pair for CA cert using provider: " + provider.getName()); // Generate CA cert X500Name caSubjectName = new X500Name("CN=Mirth Connect Certificate Authority"); SubjectPublicKeyInfo caSubjectKey = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(caKeyPair.getPublic().getEncoded())); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(caSubjectName, BigInteger.ONE, startDate, expiryDate, caSubjectName, caSubjectKey); certBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.basicConstraints, true, new BasicConstraints(0)); ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider(provider) .build(caKeyPair.getPrivate()); Certificate caCert = new JcaX509CertificateConverter().setProvider(provider) .getCertificate(certBuilder.build(sigGen)); // Generate SSL cert KeyPair sslKeyPair = keyPairGenerator.generateKeyPair(); logger.debug("generated new key pair for SSL cert using provider: " + provider.getName()); X500Name sslSubjectName = new X500Name("CN=mirth-connect"); SubjectPublicKeyInfo sslSubjectKey = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(sslKeyPair.getPublic().getEncoded())); X509v3CertificateBuilder sslCertBuilder = new X509v3CertificateBuilder(caSubjectName, new BigInteger(50, new SecureRandom()), startDate, expiryDate, sslSubjectName, sslSubjectKey); sslCertBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifier(caCert.getEncoded())); sslCertBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(sslKeyPair.getPublic().getEncoded())); sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider(provider) .build(caKeyPair.getPrivate()); Certificate sslCert = new JcaX509CertificateConverter().setProvider(provider) .getCertificate(sslCertBuilder.build(sigGen)); logger.debug("generated new certificate with serial number: " + ((X509Certificate) sslCert).getSerialNumber()); // add the generated SSL cert to the keystore using the key password keyStore.setKeyEntry(certificateAlias, sslKeyPair.getPrivate(), keyPassword, new Certificate[] { sslCert }); } else { logger.debug("found certificate in keystore"); } }
From source file:org.ejbca.util.keystore.KeyTools.java
/** * Generates a keypair//w ww. j a v a2s . com * * @param keySpec string specification of keys to generate, typical value is 1024 for RSA or DSA keys, or prime192v1 for ECDSA keys or null of algspec is to be used. * @param algSpec AlgorithmParameterSpec of keys to generate, typically an EXParameterSpec for EC keys, or null if keySpec is to be used. * @param keyAlg algorithm of keys to generate, typical value is RSA, DSA or ECDSA, see AlgorithmConstants.KEYALGORITHM_XX * * @see org.ejbca.core.model.AlgorithmConstants * @see org.bouncycastle.asn1.x9.X962NamedCurves * @see org.bouncycastle.asn1.nist.NISTNamedCurves * @see org.bouncycastle.asn1.sec.SECNamedCurves * * @return KeyPair the generated keypair * @throws InvalidAlgorithmParameterException * @see org.ejbca.core.model.AlgorithmConstants#KEYALGORITHM_RSA */ public static KeyPair genKeys(final String keySpec, final AlgorithmParameterSpec algSpec, final String keyAlg) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException { if (log.isTraceEnabled()) { log.trace(">genKeys(" + keySpec + ", " + keyAlg + ")"); } final KeyPairGenerator keygen = KeyPairGenerator.getInstance(keyAlg, "BC"); if (StringUtils.equals(keyAlg, AlgorithmConstants.KEYALGORITHM_ECDSA)) { AlgorithmParameterSpec ecSpec = null; if ((keySpec != null) && !StringUtils.equals(keySpec, "implicitlyCA")) { log.debug("Generating named curve ECDSA key pair: " + keySpec); // We have EC keys ecSpec = ECNamedCurveTable.getParameterSpec(keySpec); if (ecSpec == null) { throw new InvalidAlgorithmParameterException("keySpec " + keySpec + " is invalid for ECDSA."); } } else if (algSpec != null) { log.debug("Generating ECDSA key pair from AlgorithmParameterSpec: " + algSpec); ecSpec = algSpec; } else if (StringUtils.equals(keySpec, "implicitlyCA")) { log.debug("Generating implicitlyCA encoded ECDSA key pair"); // If the keySpec is null, we have "implicitlyCA" defined EC parameters // The parameters were already installed when we installed the provider // We just make sure that ecSpec == null here } else { throw new InvalidAlgorithmParameterException("No keySpec no algSpec and no implicitlyCA specified"); } keygen.initialize(ecSpec, new SecureRandom()); } else { // RSA or DSA keys final int keysize = Integer.parseInt(keySpec); keygen.initialize(keysize); } final KeyPair keys = keygen.generateKeyPair(); if (log.isDebugEnabled()) { final PublicKey pk = keys.getPublic(); final int len = getKeyLength(pk); log.debug("Generated " + keys.getPublic().getAlgorithm() + " keys with length " + len); } log.trace("<genKeys()"); return keys; }
From source file:org.cesecore.keys.util.KeyTools.java
/** * Generates a keypair//from w w w . j a v a2 s.c o m * * @param keySpec * string specification of keys to generate, typical value is 2048 for RSA keys, * 1024 for DSA keys, secp256r1 for ECDSA keys, or null if algspec is to be used. * @param algSpec * AlgorithmParameterSpec of keys to generate, typically an EXParameterSpec for EC keys, or null if keySpec is to be used. * @param keyAlg * algorithm of keys to generate, typical value is RSA, DSA or ECDSA, see AlgorithmConstants.KEYALGORITHM_XX * * @see org.cesecore.certificates.util.core.model.AlgorithmConstants * @see org.bouncycastle.asn1.x9.X962NamedCurves * @see org.bouncycastle.asn1.nist.NISTNamedCurves * @see org.bouncycastle.asn1.sec.SECNamedCurves * * @return KeyPair the generated keypair * @throws InvalidAlgorithmParameterException * @see org.cesecore.certificates.util.AlgorithmConstants#KEYALGORITHM_RSA */ public static KeyPair genKeys(final String keySpec, final AlgorithmParameterSpec algSpec, final String keyAlg) throws InvalidAlgorithmParameterException { if (log.isTraceEnabled()) { log.trace(">genKeys(" + keySpec + ", " + keyAlg + ")"); } KeyPairGenerator keygen; try { keygen = KeyPairGenerator.getInstance(keyAlg, BouncyCastleProvider.PROVIDER_NAME); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Algorithm " + keyAlg + "was not recognized.", e); } catch (NoSuchProviderException e) { throw new IllegalStateException("BouncyCastle was not found as a provider.", e); } if (StringUtils.equals(keyAlg, AlgorithmConstants.KEYALGORITHM_ECDSA)) { AlgorithmParameterSpec ecSpec = null; if ((keySpec != null) && !StringUtils.equals(keySpec, "implicitlyCA")) { log.debug("Generating named curve ECDSA key pair: " + keySpec); // We have EC keys ECGenParameterSpec bcSpec = new ECGenParameterSpec(keySpec); keygen.initialize(bcSpec, new SecureRandom()); // The old code should work in BC v1.50b6 and later, but in vesions prior to that the below produces a key with explicit parameter encoding instead of named curves. // There is a test for this in KeyToolsTest.testGenKeysECDSAx9 // ecSpec = ECNamedCurveTable.getParameterSpec(keySpec); // if (ecSpec == null) { // throw new InvalidAlgorithmParameterException("keySpec " + keySpec + " is invalid for ECDSA."); // } // keygen.initialize(ecSpec, new SecureRandom()); } else if (algSpec != null) { log.debug("Generating ECDSA key pair from AlgorithmParameterSpec: " + algSpec); ecSpec = algSpec; keygen.initialize(ecSpec, new SecureRandom()); } else if (StringUtils.equals(keySpec, "implicitlyCA")) { log.debug("Generating implicitlyCA encoded ECDSA key pair"); // If the keySpec is null, we have "implicitlyCA" defined EC parameters // The parameters were already installed when we installed the provider // We just make sure that ecSpec == null here keygen.initialize(ecSpec, new SecureRandom()); } else { throw new InvalidAlgorithmParameterException("No keySpec no algSpec and no implicitlyCA specified"); } } else if (keyAlg.equals(AlgorithmConstants.KEYALGORITHM_ECGOST3410)) { AlgorithmParameterSpec ecSpec = null; if (keySpec != null) { log.debug("Generating keys from given key specifications : " + keySpec); ecSpec = ECGOST3410NamedCurveTable.getParameterSpec(keySpec); if (ecSpec == null) throw new InvalidAlgorithmParameterException( "Key specification " + keySpec + " is invalid for ECGOST3410"); } else if (algSpec != null) { log.debug("Generating keys from given algorithm parameters : " + algSpec); ecSpec = algSpec; } else { throw new InvalidAlgorithmParameterException("No key or algorithm specifications"); } keygen.initialize(ecSpec, new SecureRandom()); } else if (keyAlg.equals(AlgorithmConstants.KEYALGORITHM_DSTU4145)) { AlgorithmParameterSpec ecSpec = null; if (keySpec != null) { log.debug("Generating keys from given key specifications : " + keySpec); ecSpec = dstuOidToAlgoParams(keySpec); if (ecSpec == null) throw new InvalidAlgorithmParameterException( "Key specification " + keySpec + " is invalid for DSTU4145"); } else if (algSpec != null) { log.debug("Generating keys from given algorithm parameters : " + algSpec); ecSpec = algSpec; } else { throw new InvalidAlgorithmParameterException("No key or algorithm specifications"); } keygen.initialize(ecSpec, new SecureRandom()); } else if (keySpec.startsWith("DSA")) { // DSA key with "DSA" in keyspec final int keysize = Integer.parseInt(keySpec.substring(3)); keygen.initialize(keysize); } else { // RSA or DSA key where keyspec is simply the key length final int keysize = Integer.parseInt(keySpec); keygen.initialize(keysize); } final KeyPair keys = keygen.generateKeyPair(); if (log.isDebugEnabled()) { final PublicKey pk = keys.getPublic(); final int len = getKeyLength(pk); log.debug("Generated " + keys.getPublic().getAlgorithm() + " keys with length " + len); } log.trace("<genKeys()"); return keys; }