List of usage examples for java.security KeyPairGenerator getInstance
public static KeyPairGenerator getInstance(String algorithm, Provider provider) throws NoSuchAlgorithmException
From source file:org.nimbustools.ctxbroker.security.CertificateAuthority.java
/** * CertificateAuthority constructor/*from w w w. jav a 2 s . co m*/ * * @param caCert CA's public cert, X509Certificate * @param caPrivateKey (unencrypted) private key object * @param globusCADN only used for logging * @throws NoSuchProviderException problem initializing keypair generator * @throws NoSuchAlgorithmException problem initializing keypair generator * @throws CertificateException problem initializing certificate factory * @throws IOException file/stream problem * @throws ContextBrokerException other problem with CA input */ protected CertificateAuthority(X509Certificate caCert, PrivateKey caPrivateKey, String globusCADN) throws NoSuchProviderException, NoSuchAlgorithmException, CertificateException, IOException, ContextBrokerException { if (caCert == null) { throw new IllegalArgumentException("caCert is null"); } if (caPrivateKey == null) { throw new IllegalArgumentException("caPrivateKey is null"); } this.kpGen = KeyPairGenerator.getInstance("RSA", "BC"); this.kpGen.initialize(1024, new SecureRandom()); this.certGen = new X509V3CertificateGenerator(); this.factory = CertificateFactory.getInstance("X.509", "BC"); this.caX509 = caCert; this.caPrivate = caPrivateKey; this.caX509Name = new X509Principal(caX509.getIssuerX500Principal().getEncoded()); this.initializeGenerator(); X500Principal subjectDN = caCert.getSubjectX500Principal(); String targetBase = subjectDN.getName(X500Principal.RFC2253); String[] parts = targetBase.split(","); String target = ""; int cnCount = 0; for (int i = 0; i < parts.length; i++) { String newpiece; if (parts[i].startsWith("CN") || parts[i].startsWith("cn")) { newpiece = replaceToken; cnCount += 1; } else { newpiece = parts[i]; } if (i == 0) { target = newpiece; } else { target = newpiece + "," + target; } } if (cnCount == 0) { throw new ContextBrokerException("Unsupported: CA has no " + "CN (?)"); } if (cnCount != 1) { throw new ContextBrokerException("Unsupported: CA has more " + "than one CN"); } this.targetString = target; final String msg = "Initialized certificate authority with subject " + "DN (RFC2253) = '" + targetBase + "' " + "and Globus style DN = '" + globusCADN + "'. " + "New DNs will look like this (RFC2253): '" + this.targetString + "'"; logger.info(msg); }
From source file:Main.java
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) private static void generateNewKeyOld(Context context) { try {/* www. j a v a 2s . c o m*/ KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, KEY_PROVIDER); Calendar instance = Calendar.getInstance(); Date start = instance.getTime(); instance.add(Calendar.YEAR, 1); Date end = instance.getTime(); keyPairGenerator.initialize(new KeyPairGeneratorSpec.Builder(context).setAlias(KEY_ALIAS) .setSubject(new X500Principal("CN=" + KEY_ALIAS)).setSerialNumber(BigInteger.valueOf(20151021)) .setStartDate(start).setEndDate(end).build()); keyPairGenerator.generateKeyPair(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } }
From source file:org.pgptool.gui.encryption.implpgp.KeyGeneratorServicePgpImpl.java
@Override public Key createNewKey(CreateKeyParams params) throws FieldValidationException { try {//w w w .j a va2s.c o m 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:org.wso2.carbon.identity.test.common.testng.utils.ReadCertStoreSampleUtil.java
public static KeyPair getSampleKeyPair() throws CertificateException, NoSuchAlgorithmException, IOException, InvalidKeyException, KeyStoreException, NoSuchProviderException, SignatureException { KeyStore keyStore = KeyStore.getInstance("JKS"); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "SHA1WithRSA"); SecureRandom random = SecureRandom.getInstance("RSA", "SHA1WithRSA"); keyGen.initialize(1024, random);//from ww w .jav a 2 s . com KeyPair keypair = keyGen.generateKeyPair(); return keypair; }
From source file:org.xdi.oxauth.model.crypto.OxAuthCryptoProvider.java
@Override public JSONObject generateKey(SignatureAlgorithm signatureAlgorithm, Long expirationTime) throws Exception { KeyPairGenerator keyGen = null; if (signatureAlgorithm == null) { throw new RuntimeException("The signature algorithm parameter cannot be null"); } else if (SignatureAlgorithmFamily.RSA.equals(signatureAlgorithm.getFamily())) { keyGen = KeyPairGenerator.getInstance(signatureAlgorithm.getFamily(), "BC"); keyGen.initialize(2048, new SecureRandom()); } else if (SignatureAlgorithmFamily.EC.equals(signatureAlgorithm.getFamily())) { ECGenParameterSpec eccgen = new ECGenParameterSpec(signatureAlgorithm.getCurve().getAlias()); keyGen = KeyPairGenerator.getInstance(signatureAlgorithm.getFamily(), "BC"); keyGen.initialize(eccgen, new SecureRandom()); } else {/*from www .ja v a2s .c om*/ throw new RuntimeException("The provided signature algorithm parameter is not supported"); } // Generate the key KeyPair keyPair = keyGen.generateKeyPair(); java.security.PrivateKey pk = keyPair.getPrivate(); // Java API requires a certificate chain X509Certificate cert = generateV3Certificate(keyPair, dnName, signatureAlgorithm.getAlgorithm(), expirationTime); X509Certificate[] chain = new X509Certificate[1]; chain[0] = cert; String alias = UUID.randomUUID().toString(); keyStore.setKeyEntry(alias, pk, keyStoreSecret.toCharArray(), chain); FileOutputStream stream = new FileOutputStream(keyStoreFile); keyStore.store(stream, keyStoreSecret.toCharArray()); PublicKey publicKey = keyPair.getPublic(); JSONObject jsonObject = new JSONObject(); jsonObject.put(KEY_TYPE, signatureAlgorithm.getFamily()); jsonObject.put(KEY_ID, alias); jsonObject.put(KEY_USE, Use.SIGNATURE); jsonObject.put(ALGORITHM, signatureAlgorithm.getName()); jsonObject.put(EXPIRATION_TIME, expirationTime); if (publicKey instanceof RSAPublicKey) { RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; jsonObject.put(MODULUS, Base64Util.base64urlencodeUnsignedBigInt(rsaPublicKey.getModulus())); jsonObject.put(EXPONENT, Base64Util.base64urlencodeUnsignedBigInt(rsaPublicKey.getPublicExponent())); } else if (publicKey instanceof ECPublicKey) { ECPublicKey ecPublicKey = (ECPublicKey) publicKey; jsonObject.put(CURVE, signatureAlgorithm.getCurve()); jsonObject.put(X, Base64Util.base64urlencodeUnsignedBigInt(ecPublicKey.getW().getAffineX())); jsonObject.put(Y, Base64Util.base64urlencodeUnsignedBigInt(ecPublicKey.getW().getAffineY())); } JSONArray x5c = new JSONArray(); x5c.put(Base64.encodeBase64String(cert.getEncoded())); jsonObject.put(CERTIFICATE_CHAIN, x5c); return jsonObject; }
From source file:com.aaasec.sigserv.cssigapp.KeyStoreFactory.java
private static KeyPair generateECDSAKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException { ECGenParameterSpec ecSpec = new ECGenParameterSpec("P-256"); KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC"); g.initialize(ecSpec, new SecureRandom()); KeyPair pair = g.generateKeyPair(); return pair;//from ww w. ja v a 2s. c o m }
From source file:org.codice.ddf.security.certificate.generator.PkiTools.java
/** * Generate new RSA public/private key pair with 2048 bit key * * @return new generated key pair// w w w.jav a 2 s .c o m * @throws CertificateGeneratorException */ public static KeyPair generateRsaKeyPair() { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM, BouncyCastleProvider.PROVIDER_NAME); keyGen.initialize(RSA_KEY_LENGTH); return keyGen.generateKeyPair(); } catch (Exception e) { throw new CertificateGeneratorException("Failed to generate new public/private key pair.", e); } }
From source file:io.vertx.config.vault.utils.Certificates.java
/** * See https://www.cryptoworkshop.com/guide/, chapter 3 * * @return A 4096-bit RSA keypair//from w w w . j a v a 2s. c o m * @throws NoSuchAlgorithmException */ private static KeyPair generateKeyPair() throws NoSuchAlgorithmException { final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", new BouncyCastleProvider()); keyPairGenerator.initialize(4096); return keyPairGenerator.genKeyPair(); }
From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java
void install(String[] redirectEndpointUrls, String[] postLogoutRedirectUrls, String logoutUrl) throws Exception { String domainControllerFQDN = this.relyingPartyConfig.getOpFQDN(); int domainControllerPort = Integer.parseInt(this.relyingPartyConfig.getOpListeningPort()); String tenant = this.relyingPartyConfig.getTenant(); // retrieve OIDC meta data MetadataHelper metadataHelper = new MetadataHelper.Builder(domainControllerFQDN) .domainControllerPort(domainControllerPort).tenant(tenant).keyStore(this.keyStore).build(); ProviderMetadata providerMetadata = metadataHelper.getProviderMetadata(); RSAPublicKey providerPublicKey = metadataHelper.getProviderRSAPublicKey(providerMetadata); // create a non-registered OIDC client and get bearer tokens by admin user name/password ConnectionConfig connectionConfig = new ConnectionConfig(providerMetadata, providerPublicKey, this.keyStore); ClientConfig clientConfig = new ClientConfig(connectionConfig, null, null); OIDCClient nonRegisteredClient = new OIDCClient(clientConfig); TokenSpec tokenSpec = new TokenSpec.Builder(TokenType.BEARER) .resourceServers(Arrays.asList("rs_admin_server")).build(); OIDCTokens oidcTokens = nonRegisteredClient.acquireTokensByPassword( this.relyingPartyConfig.getAdminUsername(), this.relyingPartyConfig.getAdminPassword(), tokenSpec); // create a private/public key pair, generate a certificate and assign it to a solution user name. Security.addProvider(new BouncyCastleProvider()); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC"); keyGen.initialize(1024, new SecureRandom()); KeyPair keypair = keyGen.generateKeyPair(); String solutionUserName = this.relyingPartyConfig.getClientPrefix() + UUID.randomUUID().toString(); X509Certificate clientCertificate = generateCertificate(keypair, solutionUserName); // create REST idm client IdmClient idmClient = createIdmClient(oidcTokens.getAccessToken(), domainControllerFQDN, domainControllerPort);/*from w w w . j a v a 2 s . c om*/ VmdirClient vmdirClient = createVMdirClient(oidcTokens.getAccessToken(), domainControllerFQDN, domainControllerPort); // create a solution user CertificateDTO certificateDTO = new CertificateDTO.Builder() .withEncoded(convertToBase64PEMString(clientCertificate)).build(); SolutionUserDTO solutionUserDTO = new SolutionUserDTO.Builder().withName(solutionUserName) .withDomain(tenant).withCertificate(certificateDTO).build(); vmdirClient.solutionUser().create(tenant, solutionUserDTO); // add the solution user to ActAs group List<String> members = Arrays.asList(solutionUserName + "@" + tenant); vmdirClient.group().addMembers(tenant, "ActAsUsers", tenant, members, com.vmware.directory.rest.common.data.MemberType.USER); // register a OIDC client OIDCClientMetadataDTO oidcClientMetadataDTO = new OIDCClientMetadataDTO.Builder() .withRedirectUris(Arrays.asList(redirectEndpointUrls)) .withPostLogoutRedirectUris(Arrays.asList(postLogoutRedirectUrls)).withLogoutUri(logoutUrl) .withTokenEndpointAuthMethod("private_key_jwt") .withCertSubjectDN(clientCertificate.getSubjectDN().getName()) .withAuthnRequestClientAssertionLifetimeMS(2 * 60 * 1000L).build(); OIDCClientDTO oidcClientDTO = idmClient.oidcClient().register(tenant, oidcClientMetadataDTO); // persist data involved installation in files so they can be picked up in case server reboots savePublicKey(this.relyingPartyConfig.getOpPublickeyFile(), providerPublicKey); savePrivateKey(this.relyingPartyConfig.getRpPrivatekeyFile(), keypair.getPrivate()); writeObject(this.relyingPartyConfig.getRpCertificateFile(), clientCertificate); writeObject(this.relyingPartyConfig.getRpInfoFile(), oidcClientDTO.getClientId()); writeObject(this.relyingPartyConfig.getRpListeningPortFile(), this.relyingPartyConfig.getRpListeningPort()); }
From source file:com.peterphi.std.crypto.keygen.CaHelper.java
public static KeyPair generateKeyPair(int bits) throws Exception { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC"); keyGen.initialize(bits, new SecureRandom()); return keyGen.generateKeyPair(); }