List of usage examples for java.security KeyPairGenerator getInstance
public static KeyPairGenerator getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:net.nicholaswilliams.java.licensing.licensor.TestLicenseCreator.java
@BeforeClass public static void setUpClass() throws Exception { TestLicenseCreator.control = EasyMock.createStrictControl(); TestLicenseCreator.passwordProvider = TestLicenseCreator.control.createMock(PasswordProvider.class); TestLicenseCreator.keyDataProvider = TestLicenseCreator.control.createMock(PrivateKeyDataProvider.class); try {//from w w w. j ava 2 s.com LicenseCreator.getInstance(); fail("Expected java.lang.IllegalArgumentException, got no exception."); } catch (IllegalArgumentException ignore) { } LicenseCreatorProperties.setPrivateKeyDataProvider(TestLicenseCreator.keyDataProvider); try { LicenseCreator.getInstance(); fail("Expected java.lang.IllegalArgumentException, got no exception."); } catch (IllegalArgumentException ignore) { } LicenseCreatorProperties.setPrivateKeyPasswordProvider(TestLicenseCreator.passwordProvider); LicenseCreator.getInstance(); KeyPair keyPair = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair(); TestLicenseCreator.publicKey = keyPair.getPublic(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyPair.getPrivate().getEncoded()); IOUtils.write(Encryptor.encryptRaw(pkcs8EncodedKeySpec.getEncoded(), keyPassword), outputStream); TestLicenseCreator.encryptedPrivateKey = outputStream.toByteArray(); }
From source file:ru.jts_dev.authserver.config.KeyGenerationConfig.java
@Bean public KeyPairGenerator RSAKeyPairGenerator() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { KeyPairGenerator keygen;// ww w . j av a 2 s . c o m keygen = KeyPairGenerator.getInstance("RSA"); RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4); keygen.initialize(spec); return keygen; }
From source file:com.zxy.commons.codec.rsa.AbstractRSAUtils.java
/** * ??/*from w w w . j a va 2 s . com*/ * * @param pubFile public file * @param priFile private file * @throws IOException IOException */ @SuppressWarnings("PMD.PrematureDeclaration") protected void generater(File pubFile, File priFile) throws IOException { try { KeyPairGenerator keygen = KeyPairGenerator.getInstance(ALGORITHM); SecureRandom secrand = new SecureRandom(); keygen.initialize(KEY_SIZE, secrand); KeyPair keys = keygen.genKeyPair(); PublicKey pubkey = keys.getPublic(); PrivateKey prikey = keys.getPrivate(); byte[] priKey = Base64.encodeBase64(prikey.getEncoded()); byte[] pubKey = Base64.encodeBase64(pubkey.getEncoded()); if (pubFile.exists()) { throw new IOException(pubFile.getPath() + " is exist!"); } if (priFile.exists()) { throw new IOException(priFile.getPath() + " is exist!"); } OutputStream pubOutput = new FileOutputStream(pubFile); try { IOUtils.write(pubKey, pubOutput); } finally { IOUtils.closeQuietly(pubOutput); } OutputStream priOutput = new FileOutputStream(priFile); try { IOUtils.write(priKey, priOutput); } finally { IOUtils.closeQuietly(priOutput); } } catch (NoSuchAlgorithmException e) { log.error("?", e); } }
From source file:org.apache.abdera.security.util.KeyHelper.java
public static KeyPair generateKeyPair(String type, int size) throws NoSuchAlgorithmException, NoSuchProviderException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance(type); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); keyGen.initialize(size, random);/*from ww w. j a v a2 s . c om*/ random.setSeed(System.currentTimeMillis()); return keyGen.generateKeyPair(); }
From source file:com.vmware.identity.sts.auth.impl.UserCertAuthenticatorTest.java
@BeforeClass public static void setUp() throws Exception { // create key pair and client private key, certificate KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024, new SecureRandom()); KeyPair userKeyPair = keyGen.generateKeyPair(); userPrivateKey = (RSAPrivateKey) userKeyPair.getPrivate(); x509Certificate = generateCertificate(userKeyPair, "User"); }
From source file:org.zaproxy.zap.extension.dynssl.SslCertificateUtils.java
/** * Creates a new Root CA certificate and returns private and public key as * {@link KeyStore}. The {@link KeyStore#getDefaultType()} is used. * * @return// w w w.j a v a 2 s . c o m * @throws NoSuchAlgorithmException If no providers are found * for 'RSA' key pair generator * or 'SHA1PRNG' Secure random number generator * @throws IllegalStateException in case of errors during assembling {@link KeyStore} */ public static final KeyStore createRootCA() throws NoSuchAlgorithmException { final Date startDate = Calendar.getInstance().getTime(); final Date expireDate = new Date(startDate.getTime() + (DEFAULT_VALID_DAYS * 24L * 60L * 60L * 1000L)); final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA"); g.initialize(2048, SecureRandom.getInstance("SHA1PRNG")); final KeyPair keypair = g.genKeyPair(); final PrivateKey privKey = keypair.getPrivate(); final PublicKey pubKey = keypair.getPublic(); Security.addProvider(new BouncyCastleProvider()); Random rnd = new Random(); // using the hash code of the user's name and home path, keeps anonymity // but also gives user a chance to distinguish between each other X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE); namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA"); namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode()) + Integer.toHexString(System.getProperty("user.home").hashCode())); namebld.addRDN(BCStyle.O, "OWASP Root CA"); namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA"); namebld.addRDN(BCStyle.C, "xx"); X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(), BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey); KeyStore ks = null; try { certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded())); certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign)); KeyPurposeId[] eku = { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth, KeyPurposeId.anyExtendedKeyUsage }; certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku)); final ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC") .build(privKey); final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(certGen.build(sigGen)); ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); ks.setKeyEntry(SslCertificateService.ZAPROXY_JKS_ALIAS, privKey, SslCertificateService.PASSPHRASE, new Certificate[] { cert }); } catch (final Exception e) { throw new IllegalStateException("Errors during assembling root CA.", e); } return ks; }
From source file:de.rub.nds.burp.utilities.attacks.signatureFaking.helper.CertificateHandler.java
public void createFakedCertificate() throws CertificateHandlerException { try {/*from ww w . j a va2s . c o m*/ Logging.getInstance().log(getClass(), "Faking the found certificate", Logging.DEBUG); KeyPairGenerator kpg = KeyPairGenerator.getInstance(originalPublicKey.getAlgorithm()); kpg.initialize(((RSAPublicKey) certificate.getPublicKey()).getModulus().bitLength()); fakedKeyPair = kpg.generateKeyPair(); X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.setSubjectDN(certificate.getSubjectX500Principal()); v3CertGen.setIssuerDN(certificate.getIssuerX500Principal()); v3CertGen.setNotAfter(certificate.getNotAfter()); v3CertGen.setNotBefore(certificate.getNotBefore()); v3CertGen.setSerialNumber(new BigInteger(64, new Random())); v3CertGen.setSignatureAlgorithm(certificate.getSigAlgName()); v3CertGen.setPublicKey(fakedKeyPair.getPublic()); fakedCertificate = v3CertGen.generate(fakedKeyPair.getPrivate()); } catch (CertificateEncodingException | SecurityException | SignatureException | InvalidKeyException | NoSuchAlgorithmException e) { throw new CertificateHandlerException(e); } }
From source file:com.cellngine.crypto.RSACipher.java
@Override public void generateKeypair(final int keyLength) { if (keyLength <= 0) { throw new IllegalArgumentException("Key length must be positive and nonzero"); }//from ww w. jav a2 s . co m final KeyPairGenerator generator; try { generator = KeyPairGenerator.getInstance(ALGORITHM); } catch (final NoSuchAlgorithmException e) { LOG.error("Unable to get key generator instance (" + ALGORITHM + ")", e); return; } try { generator.initialize(keyLength, this.random); } catch (final InvalidParameterException e) { throw new IllegalArgumentException("Unsupported key length"); } final KeyPair pair = generator.generateKeyPair(); this.publicKey = pair.getPublic(); this.privateKey = pair.getPrivate(); }
From source file:org.sonatype.sisu.encryptor.RsaAesEncryptor.java
public void generateKeys(OutputStream publicKeyOut, OutputStream privateKeyOut) throws GeneralSecurityException, IOException { KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); generator.initialize(KEY_SIZE * 8, random); KeyPair keyPair = generator.generateKeyPair(); OutputStream privateOut = new Base64OutputStream(privateKeyOut); PrivateKey privateKey = keyPair.getPrivate(); privateOut.write(privateKey.getEncoded()); IOUtil.close(privateOut);//from ww w .j a v a2 s . c o m OutputStream publicOut = new Base64OutputStream(publicKeyOut); PublicKey publicKey = keyPair.getPublic(); publicOut.write(publicKey.getEncoded()); IOUtil.close(publicOut); }
From source file:net.sf.zekr.common.util.CryptoUtils.java
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException { // Generate a 1024-bit Digital Signature Algorithm (DSA) key pair KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); keyGen.initialize(1024);// ww w . j av a2 s .co m KeyPair keypair = keyGen.genKeyPair(); return keypair; }