List of usage examples for java.security KeyPairGenerator initialize
public void initialize(AlgorithmParameterSpec params) throws InvalidAlgorithmParameterException
From source file:com.microsoft.azure.keyvault.extensions.RsaKey.java
public RsaKey(String kid, int keySize) throws NoSuchAlgorithmException { if (Strings.isNullOrWhiteSpace(kid)) { throw new IllegalArgumentException("kid"); }/*w w w .j av a 2 s . c om*/ final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(keySize); _keyPair = generator.generateKeyPair(); _kid = kid; }
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 . j av a2 s .c o m 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.ejbca.core.protocol.ws.client.NestedCrmfRequestTestCommand.java
/** * Creates a new instance of RaAddUserCommand * * @param args command line arguments/*from ww w . ja va2 s . com*/ */ public NestedCrmfRequestTestCommand(String[] args) { super(); if (args.length < NR_OF_MANDATORY_ARGS || args.length > MAX_NR_OF_ARGS) { usage(); System.exit(-1); // NOPMD, this is not a JEE app } hostname = args[ARG_HOSTNAME]; String certFile = args[ARG_CAFILE]; createsCertsPath = args.length > ARG_CREATEDCERTSPATH ? args[ARG_CREATEDCERTSPATH] : null; port = args.length > ARG_PORT ? Integer.parseInt(args[ARG_PORT].trim()) : 8080; urlPath = args.length > ARG_URLPATH && args[ARG_URLPATH].toLowerCase().indexOf("null") < 0 ? args[ARG_URLPATH].trim() : null; try { cacert = (X509Certificate) this.certificateFactory.generateCertificate(new FileInputStream(certFile)); final KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA"); keygen.initialize(2048); popokeys = keygen.generateKeyPair(); } catch (CertificateException e3) { e3.printStackTrace(getPrintStream()); System.exit(-1); } catch (FileNotFoundException e3) { e3.printStackTrace(getPrintStream()); System.exit(-1); } catch (NoSuchAlgorithmException e) { e.printStackTrace(getPrintStream()); System.exit(-1); } init(args); }
From source file:org.demosoft.medieval.life.loginserver.LoginController.java
private LoginController() throws GeneralSecurityException { _log.info("Loading LoginContoller..."); _keyPairs = new ScrambledKeyPair[10]; KeyPairGenerator keygen = null; keygen = KeyPairGenerator.getInstance("RSA"); RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4); keygen.initialize(spec); // generate the initial set of keys for (int i = 0; i < 10; i++) { _keyPairs[i] = new ScrambledKeyPair(keygen.generateKeyPair()); }/*from w ww . j a v a 2s . c om*/ _log.info("Cached 10 KeyPairs for RSA communication"); testCipher((RSAPrivateKey) _keyPairs[0]._pair.getPrivate()); // Store keys for blowfish communication generateBlowFishKeys(); }
From source file:org.wso2.carbon.keystore.mgt.KeyStoreGenerator.java
/** * This method generates the keypair and stores it in the keystore * * @param keyStore A keystore instance//from www . j a va 2s . co m * @return Generated public key for the tenant * @throws KeyStoreMgtException Error when generating key pair */ private X509Certificate generateKeyPair(KeyStore keyStore) throws KeyStoreMgtException { try { CryptoUtil.getDefaultCryptoUtil(); //generate key pair KeyPairGenerator keyPairGenerator = null; keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // Common Name and alias for the generated certificate String commonName = "CN=" + tenantDomain + ", OU=None, O=None L=None, C=None"; //generate certificates AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder() .find("MD5WithRSAEncryption"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory .createKey(keyPair.getPrivate().getEncoded()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam); Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30); Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)); X509v3CertificateBuilder v3CertBuilder = new X509v3CertificateBuilder(new X500Name(commonName), BigInteger.valueOf(new SecureRandom().nextInt()), notBefore, notAfter, new X500Name(commonName), subPubKeyInfo); X509CertificateHolder certificateHolder = v3CertBuilder.build(sigGen); X509Certificate PKCertificate = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(certificateHolder); //add private key to KS keyStore.setKeyEntry(tenantDomain, keyPair.getPrivate(), password.toCharArray(), new java.security.cert.Certificate[] { PKCertificate }); return PKCertificate; } catch (Exception ex) { String msg = "Error while generating the certificate for tenant :" + tenantDomain + "."; log.error(msg, ex); throw new KeyStoreMgtException(msg, ex); } }
From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java
@Override public KeyStore initializeUser(UserInfo userInfo, String suppliedPassword) throws CertException { char[] password = suppliedPassword.toCharArray(); KeyStore ks = null;//from w w w . ja v a 2s . c om String userName = userInfo.getUserFields().get(CNField.UserID); AliasWrapper keystoreAlias = new AliasWrapper(userName); try { ks = java.security.KeyStore.getInstance(KEYSTORE_TYPE); ks.load(null, password); KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyGen.initialize(KEY_SIZE); KeyPair keyPair = keyGen.genKeyPair(); java.security.cert.Certificate[] chain = { getRootCertificate() }; ks.setKeyEntry(keystoreAlias.getId(AliasType.KEY), keyPair.getPrivate(), password, chain); X509Certificate cert = getCertificate(keyPair, userInfo); ks.setCertificateEntry(keystoreAlias.getId(AliasType.CERT), cert); } catch (CertificateException e) { throw new CertException(e); } catch (IOException e) { throw new CertException(e); } catch (KeyStoreException e) { throw new CertException(e); } catch (NoSuchAlgorithmException e) { throw new CertException(e); } return ks; }
From source file:com.jonbanjo.cupsprint.CertificateActivity.java
public void doimport(View view) { try {//from w w w. ja va 2 s.c o m String url = "https://" + host.getText().toString() + ":" + port.getText().toString(); importButton.setEnabled(false); new importer().execute(url).get(3000, TimeUnit.MILLISECONDS); } catch (Exception e) { } finally { importButton.setEnabled(true); } if (certChain == null) { return; } for (X509Certificate cert : certChain) { try { cert.checkValidity(); } catch (Exception e) { showToast(e.toString()); return; } } String certString = certChain[0].toString(); final String alias = certChain[0].getSubjectX500Principal().getName(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Add Certificate?").setMessage(certString) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); trustStore.setKeyEntry(alias, privateKey, JfSSLScheme.password.toCharArray(), certChain); FileOutputStream outputStream = openFileOutput(JfSSLScheme.trustfile, MODE_PRIVATE); trustStore.store(outputStream, JfSSLScheme.password.toCharArray()); outputStream.flush(); outputStream.close(); certListAdaptor.add(alias); } catch (Exception e) { System.out.println(e.toString()); return; } } }).setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog dialog = builder.create(); dialog.show(); }
From source file:org.keycloak.testsuite.client.OIDCJwksClientRegistrationTest.java
@Test public void testTwoClientsWithSameKid() throws Exception { // Create client with manually set "kid" OIDCClientRepresentation response = createClientWithManuallySetKid("a1"); // Create client2 OIDCClientRepresentation clientRep2 = createRep(); clientRep2.setGrantTypes(Collections.singletonList(OAuth2Constants.CLIENT_CREDENTIALS)); clientRep2.setTokenEndpointAuthMethod(OIDCLoginProtocol.PRIVATE_KEY_JWT); // Generate some random keys for client2 KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048); PublicKey client2PublicKey = generator.generateKeyPair().getPublic(); // Set client2 with manually set "kid" to be same like kid of client1 (but keys for both clients are different) JSONWebKeySet keySet = new JSONWebKeySet(); keySet.setKeys(new JWK[] { JWKBuilder.create().kid("a1").rs256(client2PublicKey) }); clientRep2.setJwks(keySet);/* w ww.j ava2 s.c o m*/ clientRep2 = reg.oidc().create(clientRep2); // Authenticate client1 Map<String, String> generatedKeys = testingClient.testApp().oidcClientEndpoints().getKeysAsPem(); assertAuthenticateClientSuccess(generatedKeys, response, "a1"); // Assert item in publicKey cache for client1 String expectedCacheKey = PublicKeyStorageUtils.getClientModelCacheKey(REALM_NAME, response.getClientId()); Assert.assertTrue(testingClient.testing().cache(InfinispanConnectionProvider.KEYS_CACHE_NAME) .contains(expectedCacheKey)); // Assert it's not possible to authenticate as client2 with the same "kid" like client1 assertAuthenticateClientError(generatedKeys, clientRep2, "a1"); }
From source file:org.kaaproject.kaa.server.transports.http.transport.HttpTestClient.java
/** * Initialization of request keys and encoder/decoder * * @param serverPublicKey - server public key * @throws Exception - if key generation failed. *///from w w w .jav a 2 s.c om private void init(PublicKey serverPublicKey) throws Exception { KeyPairGenerator clientKeyGen; try { clientKeyGen = KeyPairGenerator.getInstance("RSA"); clientKeyGen.initialize(2048); KeyPair clientKeyPair = clientKeyGen.genKeyPair(); clientPrivateKey = clientKeyPair.getPrivate(); clientPublicKey = clientKeyPair.getPublic(); } catch (NoSuchAlgorithmException e) { throw new Exception(e.toString()); } crypt = new MessageEncoderDecoder(clientPrivateKey, clientPublicKey, serverPublicKey); try { key = crypt.getEncodedSessionKey(); } catch (GeneralSecurityException e) { throw new Exception(e.toString()); } ByteBuffer publicKeyBuffer = ByteBuffer .wrap(EndpointObjectHash.fromSha1(clientPublicKey.getEncoded()).getData()); clientPublicKeyHash = EndpointObjectHash.fromBytes(publicKeyBuffer.array()); }
From source file:org.red5.server.net.rtmp.RTMPHandshake.java
/** * Creates a Diffie-Hellman key pair./* w w w .j a v a2 s . c om*/ * * @return dh keypair */ protected KeyPair generateKeyPair() { KeyPair keyPair = null; DHParameterSpec keySpec = new DHParameterSpec(DH_MODULUS, DH_BASE); try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH"); keyGen.initialize(keySpec); keyPair = keyGen.generateKeyPair(); keyAgreement = KeyAgreement.getInstance("DH"); keyAgreement.init(keyPair.getPrivate()); } catch (Exception e) { log.error("Error generating keypair", e); } return keyPair; }