List of usage examples for java.security KeyPairGenerator getInstance
public static KeyPairGenerator getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:org.guanxi.idp.Bootstrap.java
public boolean createSelfSignedKeystore(String cn, String keystoreFile, String keystorePassword, String privateKeyPassword, String privateKeyAlias) { KeyStore ks = null;/*from w w w . j av a 2 s. co m*/ try { ks = KeyStore.getInstance("JKS"); ks.load(null, null); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); keyGen.initialize(1024, new SecureRandom()); KeyPair keypair = keyGen.generateKeyPair(); PrivateKey privkey = keypair.getPrivate(); PublicKey pubkey = keypair.getPublic(); Hashtable<DERObjectIdentifier, String> attrs = new Hashtable<DERObjectIdentifier, String>(); Vector<DERObjectIdentifier> ordering = new Vector<DERObjectIdentifier>(); ordering.add(X509Name.CN); attrs.put(X509Name.CN, cn); X509Name issuerDN = new X509Name(ordering, attrs); X509Name subjectDN = new X509Name(ordering, attrs); Date validFrom = new Date(); validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000)); Date validTo = new Date(); validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000))); X509V3CertificateGenerator x509 = new X509V3CertificateGenerator(); x509.setSignatureAlgorithm("SHA1withDSA"); x509.setIssuerDN(issuerDN); x509.setSubjectDN(subjectDN); x509.setPublicKey(pubkey); x509.setNotBefore(validFrom); x509.setNotAfter(validTo); x509.setSerialNumber(new BigInteger(128, new Random())); X509Certificate[] cert = new X509Certificate[1]; cert[0] = x509.generate(privkey, "BC"); java.security.cert.Certificate[] chain = new java.security.cert.Certificate[1]; chain[0] = cert[0]; ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), cert); ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), chain); ks.store(new FileOutputStream(keystoreFile), keystorePassword.toCharArray()); String IDP_RFC_CERT = "WEB-INF/guanxi_idp/keystore/guanxi_idp_cert.txt"; PEMWriter pemWriter = new PEMWriter(new FileWriter(servletContext.getRealPath(IDP_RFC_CERT))); pemWriter.writeObject(cert[0]); pemWriter.close(); return true; } catch (Exception se) { return false; } }
From source file:org.apache.drill.exec.server.rest.WebServer.java
/** * Create an HTTPS connector for given jetty server instance. If the admin has specified keystore/truststore settings * they will be used else a self-signed certificate is generated and used. * * @return Initialized {@link ServerConnector} for HTTPS connectios. * @throws Exception/*from w ww . ja v a2s . c om*/ */ private ServerConnector createHttpsConnector() throws Exception { logger.info("Setting up HTTPS connector for web server"); final SslContextFactory sslContextFactory = new SslContextFactory(); if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH) && !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH))) { logger.info("Using configured SSL settings for web server"); sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH)); sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD)); // TrustStore and TrustStore password are optional if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) { sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH)); if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) { sslContextFactory .setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)); } } } else { logger.info("Using generated self-signed SSL settings for web server"); final SecureRandom random = new SecureRandom(); // Generate a private-public key pair final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024, random); final KeyPair keyPair = keyPairGenerator.generateKeyPair(); final DateTime now = DateTime.now(); // Create builder for certificate attributes final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE) .addRDN(BCStyle.OU, "Apache Drill (auth-generated)") .addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)") .addRDN(BCStyle.CN, workManager.getContext().getEndpoint().getAddress()); final Date notBefore = now.minusMinutes(1).toDate(); final Date notAfter = now.plusYears(5).toDate(); final BigInteger serialNumber = new BigInteger(128, random); // Create a certificate valid for 5years from now. final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), // attributes serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic()); // Sign the certificate using the private key final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption") .build(keyPair.getPrivate()); final X509Certificate certificate = new JcaX509CertificateConverter() .getCertificate(certificateBuilder.build(contentSigner)); // Check the validity certificate.checkValidity(now.toDate()); // Make sure the certificate is self-signed. certificate.verify(certificate.getPublicKey()); // Generate a random password for keystore protection final String keyStorePasswd = RandomStringUtils.random(20); final KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null); keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(), new java.security.cert.Certificate[] { certificate }); sslContextFactory.setKeyStore(keyStore); sslContextFactory.setKeyStorePassword(keyStorePasswd); } final HttpConfiguration httpsConfig = new HttpConfiguration(); httpsConfig.addCustomizer(new SecureRequestCustomizer()); // SSL Connector final ServerConnector sslConnector = new ServerConnector(embeddedJetty, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig)); sslConnector.setPort(config.getInt(ExecConstants.HTTP_PORT)); return sslConnector; }
From source file:org.mitre.openid.connect.client.AbstractOIDCAuthenticationFilter.java
@Override public void afterPropertiesSet() { super.afterPropertiesSet(); Assert.notNull(errorRedirectURI, "An Error Redirect URI must be supplied"); KeyPairGenerator keyPairGenerator; try {//from w w w . jav a2 s .c o m keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(KEY_SIZE); KeyPair keyPair = keyPairGenerator.generateKeyPair(); publicKey = keyPair.getPublic(); privateKey = keyPair.getPrivate(); signer = Signature.getInstance(SIGNING_ALGORITHM); } catch (GeneralSecurityException generalSecurityException) { // generalSecurityException.printStackTrace(); throw new IllegalStateException(generalSecurityException); } // prepend the spec necessary SCOPE setScope((scope != null && !scope.isEmpty()) ? SCOPE + " " + scope : SCOPE); }
From source file:test.integ.be.fedict.commons.eid.client.SSLTest.java
private static KeyPair generateKeyPair() throws Exception { final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); final SecureRandom random = new SecureRandom(); keyPairGenerator.initialize(new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4), random); final KeyPair keyPair = keyPairGenerator.generateKeyPair(); return keyPair; }
From source file:org.forgerock.openidm.selfservice.impl.SelfService.java
private SnapshotTokenHandlerFactory newTokenHandlerFactory() { return new SnapshotTokenHandlerFactory() { @Override//ww w. j a v a 2 s . c o m public SnapshotTokenHandler get(SnapshotTokenConfig snapshotTokenConfig) { switch (snapshotTokenConfig.getType()) { case JwtTokenHandlerConfig.TYPE: return createJwtTokenHandler((JwtTokenHandlerConfig) snapshotTokenConfig); default: throw new IllegalArgumentException("Unknown type " + snapshotTokenConfig.getType()); } } private SnapshotTokenHandler createJwtTokenHandler(JwtTokenHandlerConfig config) { try { SigningManager signingManager = new SigningManager(); SigningHandler signingHandler = signingManager.newHmacSigningHandler(config.getSharedKey()); KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(config.getKeyPairAlgorithm()); keyPairGen.initialize(config.getKeyPairSize()); return new JwtTokenHandler(config.getJweAlgorithm(), config.getEncryptionMethod(), keyPairGen.generateKeyPair(), config.getJwsAlgorithm(), signingHandler, config.getTokenLifeTimeInSeconds()); } catch (NoSuchAlgorithmException nsaE) { throw new RuntimeException("Unable to create key pair for encryption", nsaE); } } }; }
From source file:netinf.common.security.impl.CryptographyTest.java
@Test public void testBadReaderKeyAlgorithm() { InformationObject informationObject = createTestInformationObject(); Hashtable<String, PublicKey> readers = new Hashtable<String, PublicKey>(); readers = new Hashtable<String, PublicKey>(); try {/*from w w w . j av a 2 s.co m*/ KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA"); keyPairGenerator.initialize(1024); KeyPair pair = keyPairGenerator.generateKeyPair(); PublicKey publicKey = pair.getPublic(); readers.put("any name", publicKey); } catch (Exception e) { throw new NetInfUncheckedException("error creating keys"); } try { crypto.encrypt(informationObject, readers); Assert.fail("Exception expected. Wrong reader name given."); } catch (NetInfCheckedSecurityException securityException) { System.out.println(securityException.getMessage()); } }
From source file:com.mytalentfolio.h_daforum.CconnectToServer.java
/** * Creates a new instance of (@code KeyPairGenerator}. * /*www. java 2 s.com*/ * @return the new {@code KeyPairGenerator} instance. * @throws NoSuchAlgorithmException * if the specified algorithm is not available */ private KeyPairGenerator getKeyPairGenerator() throws NoSuchAlgorithmException { // Generate Key Pair KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); return keyGen; }
From source file:org.asimba.wa.integrationtest.saml2.model.AuthnRequest.java
public String getSignedRequest(int format, InputStream keystoreStream, String keystorePassword, String keyAlias, String keyPassword) {//from w ww .jav a 2s .com DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder builder; Document doc; try { builder = dbf.newDocumentBuilder(); doc = builder.parse(new InputSource(new ByteArrayInputStream(getRequest(plain).getBytes("utf-8")))); // Prepare doc by marking attributes as referenceable: tagIdAttributes(doc); // Prepare cryptographic environemnt KeyStore keystore = getKeystore("JKS", keystoreStream, keystorePassword); if (keystore == null) return null; KeyPair kp; kp = getKeyPairFromKeystore(keystore, keyAlias, keyPassword); if (kp == null) { // Generate key, to prove that it works... KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA"); kpg.initialize(512); kp = kpg.generateKeyPair(); } // Set signing context with PrivateKey and root of the Document DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement()); // Get SignatureFactory for creating signatures in DOM: XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); // Create reference for "" -> root of the document // SAML requires enveloped transform Reference ref = fac.newReference("#" + this._id, fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); // Create SignedInfo (SAML2: Exclusive with or without comments is specified) SignedInfo si = fac.newSignedInfo( fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref)); // Add KeyInfo to the document: KeyInfoFactory kif = fac.getKeyInfoFactory(); // .. get key from the generated keypair: KeyValue kv = kif.newKeyValue(kp.getPublic()); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); XMLSignature signature = fac.newXMLSignature(si, ki); String before = docToString(doc); // Sign! signature.sign(dsc); _authnRequestDocument = doc; // persist, as we've worked hard for it String after = docToString(doc); if (_logger.isDebugEnabled()) { _logger.debug("Before: {}", before); _logger.debug("After : {}", after); } return after; } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XMLStreamException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // key generation exception e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { // digest algorithm selection exception e.printStackTrace(); } catch (KeyException e) { // when key-value was not available (when adding to KeyInfo) e.printStackTrace(); } catch (MarshalException e) { // sign didn't work: e.printStackTrace(); } catch (XMLSignatureException e) { // sign didn't work: e.printStackTrace(); } return null; }
From source file:com.intuit.s3encrypt.S3Encrypt.java
private static KeyPair createKeyFile(String filename) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA"); keyGenerator.initialize(2048, new SecureRandom()); KeyPair myKeyPair = keyGenerator.generateKeyPair(); PublicKey publicKey = myKeyPair.getPublic(); PrivateKey privateKey = myKeyPair.getPrivate(); System.out.println("keys created... " + filename); saveKeyPair(filename, myKeyPair);/*from w w w . jav a 2 s. c om*/ return myKeyPair; }
From source file:org.apache.accumulo.test.util.CertUtils.java
private KeyPair generateKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException { KeyPairGenerator gen = KeyPairGenerator.getInstance(encryptionAlgorithm); gen.initialize(keysize);/* w ww.j av a 2 s. co m*/ return gen.generateKeyPair(); }