List of usage examples for java.security KeyPairGenerator generateKeyPair
public KeyPair generateKeyPair()
From source file:com.microsoft.azure.keyvault.cryptography.RsaKey.java
public RsaKey(String kid, int keySize, Provider provider) throws NoSuchAlgorithmException { if (Strings.isNullOrWhiteSpace(kid)) { throw new IllegalArgumentException("kid"); }/*from w w w .ja v a 2 s . co m*/ final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", provider); generator.initialize(keySize); _kid = kid; _keyPair = generator.generateKeyPair(); _provider = provider; }
From source file:mitm.common.security.certificate.impl.StandardX509CertificateBuilderTest.java
@Test public void testGenerateSelfSignedV3Certificate() throws Exception { X509CertificateBuilder certificateBuilder = new StandardX509CertificateBuilder("BC", "BC"); KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA"); keyPairGenerator.initialize(2048, randomSource); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X500PrincipalBuilder issuerBuilder = new X500PrincipalBuilder(); issuerBuilder.setCommonName("Martijn Brinkers"); issuerBuilder.setCountryCode("NL"); issuerBuilder.setEmail("test@example.com", "test2@example.com"); issuerBuilder.setGivenName("Martijn"); issuerBuilder.setSurname("Brinkers"); issuerBuilder.setLocality("Amsterdam"); issuerBuilder.setOrganisation("None"); issuerBuilder.setState("NH"); AltNamesBuilder altNamesBuider = new AltNamesBuilder(); altNamesBuider.setRFC822Names("m.brinkers@pobox.com"); altNamesBuider.setDNSNames("example.com"); X500Principal issuer = issuerBuilder.buildPrincipal(); GeneralNames altNames = altNamesBuider.buildAltNames(); Set<KeyUsageType> keyUsage = new HashSet<KeyUsageType>(); keyUsage.add(KeyUsageType.DIGITALSIGNATURE); keyUsage.add(KeyUsageType.KEYENCIPHERMENT); keyUsage.add(KeyUsageType.NONREPUDIATION); Set<ExtendedKeyUsageType> extendedKeyUsage = new HashSet<ExtendedKeyUsageType>(); extendedKeyUsage.add(ExtendedKeyUsageType.CLIENTAUTH); extendedKeyUsage.add(ExtendedKeyUsageType.EMAILPROTECTION); Date notBefore = DateUtils.addHours(new Date(), -1); Date notAfter = DateUtils.addYears(new Date(), 10); certificateBuilder.setSubject(issuer); certificateBuilder.setIssuer(issuer); certificateBuilder.setAltNames(altNames, true); certificateBuilder.setKeyUsage(keyUsage, true); certificateBuilder.setExtendedKeyUsage(extendedKeyUsage, true); certificateBuilder.setNotBefore(notBefore); certificateBuilder.setNotAfter(notAfter); certificateBuilder.setPublicKey(keyPair.getPublic()); certificateBuilder.setSerialNumber(new BigInteger("1")); certificateBuilder.setSignatureAlgorithm("SHA256WithRSA"); certificateBuilder.setIsCA(true, true /* critical */); certificateBuilder.setPathLengthConstraint(5); Set<String> crlDistPoints = new HashSet<String>(); crlDistPoints.add("http://example.com"); crlDistPoints.add("123"); certificateBuilder.setCRLDistributionPoints(crlDistPoints); X509Certificate certificate = certificateBuilder.generateCertificate(keyPair.getPrivate(), null); assertNotNull(certificate);/* ww w . j a v a 2 s . co m*/ File file = new File(tempDir, "testGenerateSelfSignedV3Certificate.cer"); CertificateUtils.writeCertificate(certificate, file); X509CertificateInspector certInspector = new X509CertificateInspector(certificate); assertEquals( "EMAILADDRESS=test2@example.com, EMAILADDRESS=test@example.com, GIVENNAME=Martijn, " + "SURNAME=Brinkers, CN=Martijn Brinkers, O=None, L=Amsterdam, ST=NH, C=NL", certInspector.getSubjectFriendly()); assertEquals(certInspector.getIssuerFriendly(), certInspector.getSubjectFriendly()); AltNamesInspector altNamesInspector = new AltNamesInspector(certificate.getSubjectAlternativeNames()); List<String> rFC822Names = altNamesInspector.getRFC822Names(); assertEquals(1, rFC822Names.size()); assertEquals("m.brinkers@pobox.com", rFC822Names.get(0)); List<String> dNSNames = altNamesInspector.getDNSNames(); assertEquals(1, dNSNames.size()); assertEquals("example.com", dNSNames.get(0)); assertEquals(3, certInspector.getKeyUsage().size()); assertTrue(certInspector.getKeyUsage().contains(KeyUsageType.DIGITALSIGNATURE)); assertTrue(certInspector.getKeyUsage().contains(KeyUsageType.KEYENCIPHERMENT)); assertTrue(certInspector.getKeyUsage().contains(KeyUsageType.NONREPUDIATION)); assertEquals(2, certInspector.getExtendedKeyUsage().size()); assertTrue(certInspector.getExtendedKeyUsage().contains(ExtendedKeyUsageType.CLIENTAUTH)); assertTrue(certInspector.getExtendedKeyUsage().contains(ExtendedKeyUsageType.EMAILPROTECTION)); // we cannot compare the dates because of encoding we loose some detail so check if within 1 sec assertTrue(Math.abs(notAfter.getTime() - certificate.getNotAfter().getTime()) < 1000); assertTrue(Math.abs(notBefore.getTime() - certificate.getNotBefore().getTime()) < 1000); assertEquals("1", certInspector.getSerialNumberHex()); assertEquals("SHA256WITHRSA", certificate.getSigAlgName()); assertTrue(certInspector.isCA()); assertEquals(5, certInspector.getBasicConstraints().getPathLenConstraint().intValue()); Set<String> crlDistPointsCert = CRLDistributionPointsInspector .getURIDistributionPointNames(certInspector.getCRLDistibutionPoints()); assertTrue(crlDistPointsCert.contains("http://example.com")); assertTrue(crlDistPointsCert.contains("123")); }
From source file:com.kuzumeji.platform.standard.SecurityService.java
/** * RSA?(?/?)??/*from w w w . j a va 2 s.c om*/ * <dl> * <dt>? * <dd>RSA?(?/?)??(?=2048) * </dl> * @return ? */ public KeyPair generateKeyPair() { try { final KeyPairGenerator keygen = KeyPairGenerator.getInstance(RSA_ALGO_NAME); keygen.initialize(KEYSIZE, SECURE_RANDOM); return keygen.generateKeyPair(); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
From source file:sernet.verinice.encryption.test.CryptoTest.java
KeyPair generateKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException { KeyPairGenerator keyGen; keyGen = org.bouncycastle.jce.provider.asymmetric.ec.KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); keyGen.initialize(1024, new SecureRandom()); return keyGen.generateKeyPair(); }
From source file:org.iavante.sling.commons.services.impl.EncryptionServiceImpl.java
/** * Make a keypair (public for encryption and private for decrypt) with * RSA_KeySize bits size/*from ww w . j a v a2 s . c o m*/ * * @throws NoSuchAlgorithmException * @throws NoSuchProviderException */ private void makeKey() throws NoSuchAlgorithmException, NoSuchProviderException { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); // Initialize the Key-Pair Generator SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); kpg.initialize(defaultRsaKeySize, random); keyPair = kpg.generateKeyPair(); }
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 ww . j a v a 2 s . c o m*/ 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.microsoft.azure.keyvault.extensions.RsaKey.java
public RsaKey(String kid, int keySize) throws NoSuchAlgorithmException { if (Strings.isNullOrWhiteSpace(kid)) { throw new IllegalArgumentException("kid"); }/*from w ww. j a va 2s . com*/ final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(keySize); _keyPair = generator.generateKeyPair(); _kid = kid; }
From source file:org.ejbca.core.protocol.ws.client.NestedCrmfRequestTestCommand.java
/** * Creates a new instance of RaAddUserCommand * * @param args command line arguments// w w w. jav a 2 s .c o m */ 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:com.turo.pushy.apns.ApnsClientBenchmark.java
@Setup public void setUp() throws Exception { this.eventLoopGroup = new NioEventLoopGroup(2); final ApnsSigningKey signingKey; {/* w w w . j av a 2 s . c o m*/ final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC"); final SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); keyPairGenerator.initialize(256, random); signingKey = new ApnsSigningKey(KEY_ID, TEAM_ID, (ECPrivateKey) keyPairGenerator.generateKeyPair().getPrivate()); } final ApnsClientBuilder clientBuilder = new ApnsClientBuilder().setApnsServer(HOST, PORT) .setConcurrentConnections(this.concurrentConnections).setSigningKey(signingKey) .setTrustedServerCertificateChain( ApnsClientBenchmark.class.getResourceAsStream(CA_CERTIFICATE_FILENAME)) .setEventLoopGroup(this.eventLoopGroup); this.client = clientBuilder.build(); this.server = new BenchmarkApnsServer( ApnsClientBenchmark.class.getResourceAsStream(SERVER_CERTIFICATES_FILENAME), ApnsClientBenchmark.class.getResourceAsStream(SERVER_KEY_FILENAME), this.eventLoopGroup); final String token = generateRandomToken(); this.pushNotifications = new ArrayList<>(this.notificationCount); final ApnsPayloadBuilder payloadBuilder = new ApnsPayloadBuilder(); for (int i = 0; i < this.notificationCount; i++) { final String payload = payloadBuilder .setAlertBody(RandomStringUtils.randomAlphanumeric(MESSAGE_BODY_LENGTH)) .buildWithDefaultMaximumLength(); this.pushNotifications.add(new SimpleApnsPushNotification(token, TOPIC, payload)); } this.server.start(PORT).await(); }
From source file:test.unit.be.fedict.eid.idp.protocol.saml2.SAML2ArtifactProtocolServiceTest.java
private KeyPair generateKeyPair() throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); keyPairGenerator.initialize(new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4), random); return keyPairGenerator.generateKeyPair(); }