List of usage examples for java.security KeyPairGenerator getInstance
public static KeyPairGenerator getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:org.jenkinsci.remoting.engine.HandlerLoopbackLoadStress.java
public HandlerLoopbackLoadStress(Config config) throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException, UnrecoverableKeyException, KeyManagementException, OperatorCreationException { this.config = config; KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA"); gen.initialize(2048); // maximum supported by JVM with export restrictions keyPair = gen.generateKeyPair();/*from ww w . j a v a2 s . c o m*/ Date now = new Date(); Date firstDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(10)); Date lastDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(-10)); SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo .getInstance(keyPair.getPublic().getEncoded()); X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); X500Name subject = nameBuilder.addRDN(BCStyle.CN, getClass().getSimpleName()).addRDN(BCStyle.C, "US") .build(); X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(subject, BigInteger.ONE, firstDate, lastDate, subject, subjectPublicKeyInfo); JcaX509ExtensionUtils instance = new JcaX509ExtensionUtils(); certGen.addExtension(X509Extension.subjectKeyIdentifier, false, instance.createSubjectKeyIdentifier(subjectPublicKeyInfo)); ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BOUNCY_CASTLE_PROVIDER) .build(keyPair.getPrivate()); certificate = new JcaX509CertificateConverter().setProvider(BOUNCY_CASTLE_PROVIDER) .getCertificate(certGen.build(signer)); char[] password = "password".toCharArray(); KeyStore store = KeyStore.getInstance("jks"); store.load(null, password); store.setKeyEntry("alias", keyPair.getPrivate(), password, new Certificate[] { certificate }); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(store, password); context = SSLContext.getInstance("TLS"); context.init(kmf.getKeyManagers(), new TrustManager[] { new BlindTrustX509ExtendedTrustManager() }, null); mainHub = IOHub.create(executorService); // on windows there is a bug whereby you cannot mix ServerSockets and Sockets on the same selector acceptorHub = File.pathSeparatorChar == 59 ? IOHub.create(executorService) : mainHub; legacyHub = new NioChannelHub(executorService); executorService.submit(legacyHub); serverSocketChannel = ServerSocketChannel.open(); JnlpProtocolHandler handler = null; for (JnlpProtocolHandler h : new JnlpProtocolHandlerFactory(executorService).withNioChannelHub(legacyHub) .withIOHub(mainHub).withSSLContext(context).withPreferNonBlockingIO(!config.bio) .withClientDatabase(new JnlpClientDatabase() { @Override public boolean exists(String clientName) { return true; } @Override public String getSecretOf(@Nonnull String clientName) { return secretFor(clientName); } }).withSSLClientAuthRequired(false).handlers()) { if (config.name.equals(h.getName())) { handler = h; break; } } if (handler == null) { throw new RuntimeException("Unknown handler: " + config.name); } this.handler = handler; acceptor = new Acceptor(serverSocketChannel); runtimeMXBean = ManagementFactory.getRuntimeMXBean(); operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); _getProcessCpuTime = _getProcessCpuTime(operatingSystemMXBean); garbageCollectorMXBeans = new ArrayList<GarbageCollectorMXBean>( ManagementFactory.getGarbageCollectorMXBeans()); Collections.sort(garbageCollectorMXBeans, new Comparator<GarbageCollectorMXBean>() { @Override public int compare(GarbageCollectorMXBean o1, GarbageCollectorMXBean o2) { return o1.getName().compareTo(o2.getName()); } }); stats = new Stats(); }
From source file:net.nicholaswilliams.java.licensing.encryption.TestKeyFileUtilities.java
@Test public void testPublicKeyEncryption01() throws Throwable { File file = new File("testPublicKeyEncryption01.key"); if (file.exists()) FileUtils.forceDelete(file);/*from w ww .ja v a2s . com*/ PublicKey publicKey = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair() .getPublic(); KeyFileUtilities.writeEncryptedPublicKey(publicKey, file, "myTestPassword01".toCharArray()); PublicKey publicKey2 = KeyFileUtilities.readEncryptedPublicKey(file, "myTestPassword01".toCharArray()); assertNotNull("The key should not be null.", publicKey2); assertFalse("The objects should not be the same.", publicKey == publicKey2); assertEquals("The keys should be the same.", publicKey, publicKey2); FileUtils.forceDelete(file); }
From source file:ie.peternagy.jcrypto.algo.EllipticCurveWrapper.java
/** * Generate a set of Elliptic Curve keys *//*from w w w. ja v a2 s .c o m*/ public void generateKeys() { tryLoadKeys(); if (isInitialized(true) && isInitialized(false)) { return; } try { ECGenParameterSpec ecGenSpec = new ECGenParameterSpec(EC_CURVE); KeyPairGenerator g = KeyPairGenerator.getInstance(ALGORITHM_NAME); g.initialize(ecGenSpec, CryptoSecurityUtil.getSecureRandom()); KeyPair pair = g.generateKeyPair(); privateKey = pair.getPrivate(); publicKey = pair.getPublic(); writeKeys(); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException ex) { Logger.getLogger(EllipticCurveWrapper.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:SecureConnection.java
private byte[] getPublicKeyStep2(DHParameterSpec dhParamSpec) throws Exception { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DH"); keyPairGen.initialize(dhParamSpec);/* w w w . ja v a 2 s . c om*/ KeyPair keyPair = keyPairGen.generateKeyPair(); this.keyAgree = KeyAgreement.getInstance("DH"); this.keyAgree.init(keyPair.getPrivate()); return keyPair.getPublic().getEncoded(); }
From source file:com.owncloud.android.util.EncryptionTestIT.java
@Test public void encryptPrivateKey() throws Exception { String keyPhrase = "moreovertelevisionfactorytendencyindependenceinternationalintellectualimpress" + "interestvolunteer"; KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(4096, new SecureRandom()); KeyPair keyPair = keyGen.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); byte[] privateKeyBytes = privateKey.getEncoded(); String privateKeyString = EncryptionUtils.encodeBytesToBase64String(privateKeyBytes); String encryptedString = EncryptionUtils.encryptPrivateKey(privateKeyString, keyPhrase); String decryptedString = EncryptionUtils.decryptPrivateKey(encryptedString, keyPhrase); assertEquals(privateKeyString, decryptedString); }
From source file:test.be.fedict.eid.applet.RSATest.java
@Test public void testPSS() throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); keyPairGenerator.initialize(new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4), random); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); Signature signature = Signature.getInstance("SHA256withRSA/PSS", "BC"); byte[] data = "hello world".getBytes(); signature.initSign(privateKey);//from ww w .j a v a2 s . c o m signature.update(data); byte[] signatureValue = signature.sign(); LOG.debug("signature size: " + signatureValue.length); LOG.debug("signature value: " + new String(Hex.encodeHex(signatureValue))); signature.initVerify(publicKey); signature.update(data); boolean result = signature.verify(signatureValue); assertTrue(result); signature.initSign(privateKey); signature.update(data); byte[] signatureValue2 = signature.sign(); LOG.debug("signature size: " + signatureValue2.length); LOG.debug("signature value: " + new String(Hex.encodeHex(signatureValue2))); assertFalse(Arrays.equals(signatureValue, signatureValue2)); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256", "BC"); byte[] digest = messageDigest.digest(data); signature = Signature.getInstance("RAWRSASSA-PSS", "BC"); signature.setParameter(new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1)); signature.initVerify(publicKey); signature.update(digest); result = signature.verify(signatureValue); assertTrue(result); }
From source file:org.springframework.security.ldap.server.ApacheDsSSLContainer.java
public File getKeystore(File directory) throws Exception { KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null);//from w ww . ja v a2 s .c om KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(keysize); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X509Certificate[] chain = { getSelfCertificate(new X500Name(commonName, organizationalUnit, organization, city, state, country), new Date(), (long) validity * 24 * 60 * 60, keyPair, "SHA256withRSA") }; keyStore.setKeyEntry(alias, keyPair.getPrivate(), keyPass, chain); String keystoreName = "ldap.keystore"; File keystore = new File(directory, keystoreName); if (!keystore.createNewFile()) { throw new FileNotFoundException("Unable to create file:" + keystore); } keyStore.store(new FileOutputStream(keystore, false), keyPass); return keystore; }
From source file:org.globus.gsi.util.CertificateUtil.java
/** * Generates a key pair of given algorithm and strength. * * @param algorithm the algorithm of the key pair. * @param bits the strength//from w ww . j a v a 2 s .c o m * @return <code>KeyPair</code> the generated key pair. * @exception GeneralSecurityException if something goes wrong. */ public static KeyPair generateKeyPair(String algorithm, int bits) throws GeneralSecurityException { KeyPairGenerator generator = null; if (provider == null) { generator = KeyPairGenerator.getInstance(algorithm); } else { generator = KeyPairGenerator.getInstance(algorithm, provider); } generator.initialize(bits); return generator.generateKeyPair(); }
From source file:it.geosolutions.sfs.web.Start.java
private static void assureSelfSignedServerCertificate(String hostname, File keyStoreFile, String password) throws Exception { KeyStore privateKS = KeyStore.getInstance("JKS"); if (keyStoreFile.exists()) { FileInputStream fis = new FileInputStream(keyStoreFile); privateKS.load(fis, password.toCharArray()); if (keyStoreContainsCertificate(privateKS, hostname)) return; } else {//w w w.j a v a 2s . c o m privateKS.load(null); } // create a RSA key pair generator using 1024 bits KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair KPair = keyPairGenerator.generateKeyPair(); // cerate a X509 certifacte generator // X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); // set validity to 10 years, issuer and subject are equal --> self singed certificate int random = new SecureRandom().nextInt(); if (random < 0) random *= -1; // v3CertGen.setSerialNumber(BigInteger.valueOf(random)); // v3CertGen.setIssuerDN(new X509Principal("CN=" + hostname + ", OU=None, O=None L=None, C=None")); // v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30)); // v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365*10))); // v3CertGen.setSubjectDN(new X509Principal("CN=" + hostname + ", OU=None, O=None L=None, C=None")); // // v3CertGen.setPublicKey(KPair.getPublic()); // v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption"); // // X509Certificate PKCertificate = v3CertGen.generateX509Certificate(KPair.getPrivate()); // // store the certificate containing the public key,this file is needed // to import the public key in other key store. File certFile = new File(keyStoreFile.getParentFile(), hostname + ".cert"); FileOutputStream fos = new FileOutputStream(certFile.getAbsoluteFile()); // fos.write(PKCertificate.getEncoded()); fos.close(); // privateKS.setKeyEntry(hostname+".key", KPair.getPrivate(), // password.toCharArray(), // new java.security.cert.Certificate[]{PKCertificate}); // // privateKS.setCertificateEntry(hostname+".cert",PKCertificate); privateKS.store(new FileOutputStream(keyStoreFile), password.toCharArray()); }
From source file:org.tolven.gatekeeper.CertificateHelper.java
private X509CertificatePrivateKeyPair createX509CertificatePrivateKeyPair(String email, String commonName, String organizationUnitName, String organizationName, String stateOrProvince) { String privateKeyAlgorithm = USER_PRIVATE_KEY_ALGORITHM_PROP; KeyPairGenerator keyPairGenerator; try {/* ww w .j av a2 s. c o m*/ keyPairGenerator = KeyPairGenerator.getInstance(privateKeyAlgorithm); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException("Could not get KeyPairGenerator for algorithm: " + privateKeyAlgorithm, ex); } int keySize = Integer.parseInt(USER_PRIVATE_KEY_LENGTH_PROP); keyPairGenerator.initialize(keySize); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X500Principal x500Principal = getX500Principal(email, commonName, organizationUnitName, organizationName, stateOrProvince); return createSelfSignedCertificate(x500Principal, keyPair.getPublic(), keyPair.getPrivate()); }