List of usage examples for java.security KeyPairGenerator getInstance
public static KeyPairGenerator getInstance(String algorithm, Provider provider) throws NoSuchAlgorithmException
From source file:fr.xebia.demo.amazon.aws.AmazonAwsIamAccountCreatorV2.java
public AmazonAwsIamAccountCreatorV2() { try {/*from w w w .j a v a 2s. co m*/ InputStream credentialsAsStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream("AwsCredentials.properties"); Preconditions.checkNotNull(credentialsAsStream, "File 'AwsCredentials.properties' NOT found in the classpath"); AWSCredentials awsCredentials = new PropertiesCredentials(credentialsAsStream); iam = new AmazonIdentityManagementClient(awsCredentials); ses = new AmazonSimpleEmailServiceClient(awsCredentials); ec2 = new AmazonEC2Client(awsCredentials); ec2.setEndpoint("ec2.eu-west-1.amazonaws.com"); keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC"); keyPairGenerator.initialize(1024, new SecureRandom()); } catch (Exception e) { throw Throwables.propagate(e); } }
From source file:org.ejbca.util.keystore.KeyTools.java
/** * Generates a keypair//from w w w .ja v a 2s.co m * * @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:net.jmhertlein.core.crypto.Keys.java
/** * Generates a new Elliptic Curve Digital Signature Algorithm (ECDSA) public/private key pair. * * System's default SecureRandom is used * @param curveName the name of a pre-defined elliptic curve (e.g. secp521r1) * @param provider the JCE provider to use * @return a new ECDSA key pair/*from w w w .j av a2 s.co m*/ */ public static KeyPair newECDSAKeyPair(String curveName, String provider) { KeyPair ret; try { ECGenParameterSpec ecGenSpec = new ECGenParameterSpec(curveName); KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", provider); g.initialize(ecGenSpec, new SecureRandom()); ret = g.generateKeyPair(); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | NoSuchProviderException ex) { Logger.getLogger(Keys.class.getName()).log(Level.SEVERE, null, ex); ret = null; } return ret; }
From source file:org.ejbca.util.keystore.KeyStoreContainerBase.java
/** * @see org.ejbca.util.keystore.KeyStoreContainer#generate(java.lang.String, java.lang.String) *//*from ww w . j a va 2 s . c o m*/ private byte[] generateEC(final String name, final String keyEntryName) throws Exception { if (log.isTraceEnabled()) { log.trace(">generate EC: curve name " + name + ", keyEntryName " + keyEntryName); } // Generate the EC Keypair final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", this.providerName); try { Provider prov = Security.getProvider(this.providerName); if (StringUtils.contains(prov.getClass().getName(), "iaik")) { throw new InvalidAlgorithmParameterException("IAIK ECC key generation not implemented."); /* ECDSAPrivateKey privateKeyTemplate = new ECDSAPrivateKey(); privateKeyTemplate.getSign().setBooleanValue(Boolean.TRUE); privateKeyTemplate.getToken().setBooleanValue(Boolean.FALSE); ECDSAPublicKey publicKeyTemplate = new ECDSAPublicKey(); publicKeyTemplate.getVerify().setBooleanValue(Boolean.TRUE); publicKeyTemplate.getToken().setBooleanValue(Boolean.FALSE); ObjectID eccCurveObjectID = new ObjectID(objectID); publicKeyTemplate.getEcdsaParams().setByteArrayValue(DerCoder.encode(eccCurveObjectID)); PKCS11KeyPairGenerationSpec keyPairGenerationSpec = new PKCS11KeyPairGenerationSpec(tokenManager, publicKeyTemplate, privateKeyTemplate, PKCS11Spec.USE_READ_WRITE_SESSION, PKCS11Spec.USE_USER_SESSION); keyPairGenerator.initialize(keyPairGenerationSpec); */ } else { kpg.initialize(new ECGenParameterSpec(name)); } } catch (InvalidAlgorithmParameterException e) { log.debug("EC name " + name + " not supported."); throw e; } final byte result[] = generate(kpg, keyEntryName, "SHA1withECDSA"); if (log.isTraceEnabled()) { log.trace("<generate: curve name " + name + ", keyEntryName " + keyEntryName); } return result; }
From source file:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java
public AmazonAwsIamAccountCreator(Environment environment) { this.environment = Preconditions.checkNotNull(environment); try {/*from w w w . ja v a2 s .c o m*/ keyPairGenerator = KeyPairGenerator.getInstance("RSA", BOUNCY_CASTLE_PROVIDER_NAME); keyPairGenerator.initialize(1024, new SecureRandom()); String credentialsFileName = "AwsCredentials-" + environment.getIdentifier() + ".properties"; InputStream credentialsAsStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(credentialsFileName); Preconditions.checkNotNull(credentialsAsStream, "File '/" + credentialsFileName + "' NOT found in the classpath"); AWSCredentials awsCredentials = new PropertiesCredentials(credentialsAsStream); iam = new AmazonIdentityManagementClient(awsCredentials); ses = new AmazonSimpleEmailServiceClient(awsCredentials); ec2 = new AmazonEC2Client(awsCredentials); ec2.setEndpoint("ec2.eu-west-1.amazonaws.com"); InputStream smtpPropertiesAsStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream("smtp.properties"); Preconditions.checkNotNull(smtpPropertiesAsStream, "File '/smtp.properties' NOT found in the classpath"); final Properties smtpProperties = new Properties(); smtpProperties.load(smtpPropertiesAsStream); mailSession = Session.getInstance(smtpProperties, null); mailTransport = mailSession.getTransport(); if (smtpProperties.containsKey("mail.username")) { mailTransport.connect(smtpProperties.getProperty("mail.username"), smtpProperties.getProperty("mail.password")); } else { mailTransport.connect(); } try { mailFrom = new InternetAddress(smtpProperties.getProperty("mail.from")); } catch (Exception e) { throw new MessagingException("Exception parsing 'mail.from' from 'smtp.properties'", e); } } catch (Exception e) { throw Throwables.propagate(e); } }
From source file:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java
/** * Generates a new Elliptic Curve Digital Signature Algorithm (ECDSA) public/private key pair. * * System's default SecureRandom is used * * @param curveName the name of a pre-defined elliptic curve (e.g. secp521r1) * @param provider the JCE provider to use * @return a new ECDSA key pair/*from w ww. j av a 2 s . co m*/ */ public static KeyPair newECDSAKeyPair(String curveName, String provider) { KeyPair ret; try { ECGenParameterSpec ecGenSpec = new ECGenParameterSpec(curveName); KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", provider); g.initialize(ecGenSpec, new SecureRandom()); ret = g.generateKeyPair(); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | NoSuchProviderException ex) { Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(System.err); ret = null; } return ret; }
From source file:org.cesecore.keys.util.KeyTools.java
/** * Generates a keypair/*from w w w.j a va2 s.com*/ * * @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; }
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. *///from w w w . j a v 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.cesecore.keys.util.KeyStoreTools.java
private void generateEC(final String name, final String keyEntryName) throws InvalidAlgorithmParameterException { if (log.isTraceEnabled()) { log.trace(">generate EC: curve name " + name + ", keyEntryName " + keyEntryName); }//from w w w .ja va 2 s . c om // Generate the EC Keypair KeyPairGenerator kpg; try { kpg = KeyPairGenerator.getInstance("EC", this.providerName); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Algorithm " + "EC" + "was not recognized.", e); } catch (NoSuchProviderException e) { throw new IllegalStateException("BouncyCastle was not found as a provider.", e); } try { Provider prov = Security.getProvider(this.providerName); if (StringUtils.contains(prov.getClass().getName(), "iaik")) { throw new InvalidAlgorithmParameterException("IAIK ECC key generation not implemented."); /* ECDSAPrivateKey privateKeyTemplate = new ECDSAPrivateKey(); privateKeyTemplate.getSign().setBooleanValue(Boolean.TRUE); privateKeyTemplate.getToken().setBooleanValue(Boolean.FALSE); ECDSAPublicKey publicKeyTemplate = new ECDSAPublicKey(); publicKeyTemplate.getVerify().setBooleanValue(Boolean.TRUE); publicKeyTemplate.getToken().setBooleanValue(Boolean.FALSE); ObjectID eccCurveObjectID = new ObjectID(objectID); publicKeyTemplate.getEcdsaParams().setByteArrayValue(DerCoder.encode(eccCurveObjectID)); PKCS11KeyPairGenerationSpec keyPairGenerationSpec = new PKCS11KeyPairGenerationSpec(tokenManager, publicKeyTemplate, privateKeyTemplate, PKCS11Spec.USE_READ_WRITE_SESSION, PKCS11Spec.USE_USER_SESSION); keyPairGenerator.initialize(keyPairGenerationSpec); */ } else { ECGenParameterSpec ecSpec = new ECGenParameterSpec(name); if (StringUtils.equals(name, "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 ecSpec = null; } kpg.initialize(ecSpec); } } catch (InvalidAlgorithmParameterException e) { log.debug("EC name " + name + " not supported."); throw e; } generateKeyPair(kpg, keyEntryName, "SHA1withECDSA"); if (log.isTraceEnabled()) { log.trace("<generate: curve name " + name + ", keyEntryName " + keyEntryName); } }
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 va2s .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); } }