List of usage examples for java.security KeyPairGenerator initialize
public void initialize(AlgorithmParameterSpec params) throws InvalidAlgorithmParameterException
From source file:com.mytalentfolio.h_daforum.CconnectToServer.java
/** * Creates a new instance of (@code KeyPairGenerator}. * /*from w w w .ja v a 2 s. c o m*/ * @return the new {@code KeyPairGenerator} instance. * @throws NoSuchAlgorithmException * if the specified algorithm is not available */ private KeyPairGenerator getKeyPairGenerator() throws NoSuchAlgorithmException { // Generate Key Pair KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); return keyGen; }
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. */// w ww.j a va2 s . c om 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.openengsb.core.services.internal.security.FileKeySource.java
private void generateKeysIfRequired(File keyDirectoryFile) { File privateKeyFile = new File(keyDirectoryFile, DEFAULT_PRIVATE_KEY_FILENAME); File publicKeyFile = new File(keyDirectoryFile, DEFAULT_PUBLIC_KEY_FILENAME); if (privateKeyFile.exists() && publicKeyFile.exists()) { LOGGER.info("skipping key-generation, because there already are some"); return;// w w w . jav a2s .c o m } KeyPairGenerator generator; try { LOGGER.info("generating new keypair"); generator = KeyPairGenerator.getInstance(DEFAULT_ALGORITHM); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("failed to generate keypair", e); } generator.initialize(DEFAULT_KEY_SIZE); KeyPair generatedKeyPair = generator.generateKeyPair(); try { LOGGER.trace("saving new keypair to files"); FileUtils.writeByteArrayToFile(privateKeyFile, generatedKeyPair.getPrivate().getEncoded()); FileUtils.writeByteArrayToFile(publicKeyFile, generatedKeyPair.getPublic().getEncoded()); } catch (IOException e) { throw new IllegalStateException("failed to write keys to key-directory", e); } }
From source file:org.pgptool.gui.encryption.implpgp.KeyGeneratorServicePgpImpl.java
@Override public Key createNewKey(CreateKeyParams params) throws FieldValidationException { try {/* ww w .j a va2s . c om*/ Preconditions.checkArgument(params != null, "params must not be null"); assertParamsValid(params); // Create KeyPairs KeyPair dsaKp = getOrGenerateDsaKeyPair(DEFAULT_DSA_KEY_PARAMETERS); KeyPairGenerator elgKpg = KeyPairGenerator.getInstance("ELGAMAL", "BC"); DHParameterSpec elParams = new DHParameterSpec(p, g); elgKpg.initialize(elParams); KeyPair elgKp = elgKpg.generateKeyPair(); // Now let do some crazy stuff (I HAVE NO IDEA WHAT I AM DOING // HERE). BouncyCastle guys are not helping by changing API from // one version to another so often!!!!!!! PGPKeyPair dsaKeyPair = new JcaPGPKeyPair(PGPPublicKey.DSA, dsaKp, new Date()); PGPKeyPair elgKeyPair = new JcaPGPKeyPair(PGPPublicKey.ELGAMAL_ENCRYPT, elgKp, new Date()); // PGPContentSignerBuilde // JCA // JcaPGPContentSignerBuilder keySignerBuilder = new // JcaPGPContentSignerBuilder( // dsaKeyPair.getPublicKey().getAlgorithm(), // HashAlgorithmTags.SHA256); // BC BcPGPContentSignerBuilder keySignerBuilderBC = new BcPGPContentSignerBuilder( dsaKeyPair.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA256); // PGPDigestCalculator // JCA // PGPDigestCalculator sha1Calc = new // JcaPGPDigestCalculatorProviderBuilder().build() // .get(HashAlgorithmTags.SHA256); // BC PGPDigestCalculator sha1CalcBC = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1); // keyEncryptor // BC BcPBESecretKeyEncryptorBuilder encryptorBuilderBC = new BcPBESecretKeyEncryptorBuilder( PGPEncryptedData.AES_256, sha1CalcBC); PBESecretKeyEncryptor keyEncryptorBC = encryptorBuilderBC.build(params.getPassphrase().toCharArray()); // JCA // JcePBESecretKeyEncryptorBuilder encryptorBuilder = new // JcePBESecretKeyEncryptorBuilder( // PGPEncryptedData.AES_256, sha1Calc).setProvider("BC"); // PBESecretKeyEncryptor keyEncryptor = // encryptorBuilder.build(params.getPassphrase().toCharArray()); // keyRingGen String userName = params.getFullName() + " <" + params.getEmail() + ">"; // JCA // PGPKeyRingGenerator keyRingGen = new // PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, // dsaKeyPair, // userName, sha1Calc, null, null, keySignerBuilder, // keyEncryptor); // BC PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, dsaKeyPair, userName, sha1CalcBC, null, null, keySignerBuilderBC, keyEncryptorBC); keyRingGen.addSubKey(elgKeyPair); // building ret Key ret = buildKey(keyRingGen); return ret; } catch (Throwable t) { Throwables.propagateIfInstanceOf(t, FieldValidationException.class); throw new RuntimeException("Failed to generate key", t); } }
From source file:netinf.common.security.impl.CryptographyTest.java
@Test public void testBadReaderKeyAlgorithm() { InformationObject informationObject = createTestInformationObject(); Hashtable<String, PublicKey> readers = new Hashtable<String, PublicKey>(); readers = new Hashtable<String, PublicKey>(); try {/*from w w w . j ava 2 s . c o m*/ KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA"); keyPairGenerator.initialize(1024); KeyPair pair = keyPairGenerator.generateKeyPair(); PublicKey publicKey = pair.getPublic(); readers.put("any name", publicKey); } catch (Exception e) { throw new NetInfUncheckedException("error creating keys"); } try { crypto.encrypt(informationObject, readers); Assert.fail("Exception expected. Wrong reader name given."); } catch (NetInfCheckedSecurityException securityException) { System.out.println(securityException.getMessage()); } }
From source file:org.ejbca.util.keystore.KeyStoreContainerBase.java
/** * @see org.ejbca.util.keystore.KeyStoreContainer#generate(int, java.lang.String) *//*from w w w .j a v a 2s . com*/ private byte[] generateRSA(final int keySize, final String keyEntryName) throws Exception { if (log.isTraceEnabled()) { log.trace(">generate: keySize " + keySize + ", keyEntryName " + keyEntryName); } // Generate the RSA Keypair final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", this.providerName); kpg.initialize(keySize); final byte result[] = generate(kpg, keyEntryName, "SHA1withRSA"); if (log.isTraceEnabled()) { log.trace("<generate: keySize " + keySize + ", keyEntryName " + keyEntryName); } return result; }
From source file:org.ejbca.util.keystore.KeyStoreContainerBase.java
/** * @see org.ejbca.util.keystore.KeyStoreContainer#generate(int, java.lang.String) *//* w w w .j av a2 s. co m*/ private byte[] generateDSA(final int keySize, final String keyEntryName) throws Exception { if (log.isTraceEnabled()) { log.trace(">generate: keySize " + keySize + ", keyEntryName " + keyEntryName); } // Generate the RSA Keypair final KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA", this.providerName); kpg.initialize(keySize); final byte result[] = generate(kpg, keyEntryName, "SHA1withDSA"); if (log.isTraceEnabled()) { log.trace("<generate: keySize " + keySize + ", keyEntryName " + keyEntryName); } return result; }
From source file:netinf.common.security.impl.CryptographyTest.java
@Test public void testBadPrivateKeyAlgorithm() throws NetInfCheckedSecurityException { Attribute attribute = createTestAttribute(); Attribute encryptedAttribute = crypto.encrypt(attribute, publicKeys); IdentityManager wrongIdentityManager = EasyMock.createMock(IdentityManager.class); EasyMock.expect(wrongIdentityManager.hasPrivateKey((String) EasyMock.anyObject())).andReturn(true) .anyTimes();/*from ww w .j a v a2s . c o m*/ EasyMock.expect(wrongIdentityManager.hasPrivateKey((String) EasyMock.anyObject(), (String) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(true).anyTimes(); try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA"); keyPairGenerator.initialize(1024); KeyPair pair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = pair.getPrivate(); try { EasyMock.expect(wrongIdentityManager.getPrivateKey((String) EasyMock.anyObject())) .andReturn(privateKey).anyTimes(); EasyMock.expect(wrongIdentityManager.getPrivateKey((String) EasyMock.anyObject(), (String) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(privateKey) .anyTimes(); } catch (NetInfCheckedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } catch (Exception e) { throw new NetInfUncheckedException("error creating keys"); } EasyMock.replay(wrongIdentityManager); try { // FIXME added dummy-port! needs adjustment! CryptographyImpl crypto = new CryptographyImpl(wrongIdentityManager, algorithm, factory, convenienceCommunicator); crypto.decrypt(encryptedAttribute); Assert.fail("Exception expected. Wrong private key given."); } catch (NetInfCheckedSecurityException securityException) { System.out.println(securityException.getMessage()); } }
From source file:netinf.common.security.impl.CryptographyTest.java
@Test public void testBadPrivateKey() throws NetInfCheckedSecurityException { Attribute attribute = createTestAttribute(); Attribute encryptedAttribute = crypto.encrypt(attribute, publicKeys); // String keyName = identityObject.getIdentifier().toString() + "?" + DefinedAttributeIdentification.PUBLIC_KEY.getURI(); IdentityManager wrongIdentityManager = EasyMock.createMock(IdentityManager.class); EasyMock.expect(wrongIdentityManager.hasPrivateKey((String) EasyMock.anyObject())).andReturn(true) .anyTimes();//from w w w . ja v a 2 s. c o m EasyMock.expect(wrongIdentityManager.hasPrivateKey((String) EasyMock.anyObject(), (String) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(true).anyTimes(); try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair pair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = pair.getPrivate(); try { EasyMock.expect(wrongIdentityManager.getPrivateKey((String) EasyMock.anyObject())) .andReturn(privateKey).anyTimes(); EasyMock.expect(wrongIdentityManager.getPrivateKey((String) EasyMock.anyObject(), (String) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(privateKey) .anyTimes(); } catch (NetInfCheckedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } catch (Exception e) { throw new NetInfUncheckedException("error creating keys"); } EasyMock.replay(wrongIdentityManager); try { // FIXME added dummy-port! needs adjustment! CryptographyImpl crypto = new CryptographyImpl(wrongIdentityManager, algorithm, factory, convenienceCommunicator); crypto.decrypt(encryptedAttribute); Assert.fail("Exception expected. Wrong private key given."); } catch (NetInfCheckedSecurityException securityException) { System.out.println(securityException.getMessage()); } }
From source file:org.ejbca.util.keystore.KeyStoreContainerBase.java
@Override public byte[] generate(final AlgorithmParameterSpec spec, final String keyEntryName) throws Exception { if (log.isTraceEnabled()) { log.trace(">generate from AlgorithmParameterSpec: " + spec.getClass().getName()); }//from w ww . j av a 2 s . c om // 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"; } final KeyPairGenerator kpg = KeyPairGenerator.getInstance(algorithm, this.providerName); try { kpg.initialize(spec); } catch (InvalidAlgorithmParameterException e) { log.debug("Algorithm parameters not supported: " + e.getMessage()); throw e; } final byte result[] = generate(kpg, keyEntryName, sigAlg); if (log.isTraceEnabled()) { log.trace("<generate from AlgorithmParameterSpec: " + spec.getClass().getName()); } return result; }