List of usage examples for java.security KeyPairGenerator generateKeyPair
public KeyPair generateKeyPair()
From source file:netinf.common.security.impl.CryptographyTest.java
@Test public void testBadPrivateKeyAlgorithm() throws NetInfCheckedSecurityException { Attribute attribute = createTestAttribute(); Attribute encryptedAttribute = crypto.encrypt(attribute, publicKeys); IdentityManager wrongIdentityManager = EasyMock.createMock(IdentityManager.class); EasyMock.expect(wrongIdentityManager.hasPrivateKey((String) EasyMock.anyObject())).andReturn(true) .anyTimes();/*from w w w .j a v a 2 s .c o m*/ EasyMock.expect(wrongIdentityManager.hasPrivateKey((String) EasyMock.anyObject(), (String) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(true).anyTimes(); try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA"); keyPairGenerator.initialize(1024); KeyPair pair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = pair.getPrivate(); try { EasyMock.expect(wrongIdentityManager.getPrivateKey((String) EasyMock.anyObject())) .andReturn(privateKey).anyTimes(); EasyMock.expect(wrongIdentityManager.getPrivateKey((String) EasyMock.anyObject(), (String) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(privateKey) .anyTimes(); } catch (NetInfCheckedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } catch (Exception e) { throw new NetInfUncheckedException("error creating keys"); } EasyMock.replay(wrongIdentityManager); try { // FIXME added dummy-port! needs adjustment! CryptographyImpl crypto = new CryptographyImpl(wrongIdentityManager, algorithm, factory, convenienceCommunicator); crypto.decrypt(encryptedAttribute); Assert.fail("Exception expected. Wrong private key given."); } catch (NetInfCheckedSecurityException securityException) { System.out.println(securityException.getMessage()); } }
From source file:netinf.common.security.impl.CryptographyTest.java
@Test public void testBadPrivateKey() throws NetInfCheckedSecurityException { Attribute attribute = createTestAttribute(); Attribute encryptedAttribute = crypto.encrypt(attribute, publicKeys); // String keyName = identityObject.getIdentifier().toString() + "?" + DefinedAttributeIdentification.PUBLIC_KEY.getURI(); IdentityManager wrongIdentityManager = EasyMock.createMock(IdentityManager.class); EasyMock.expect(wrongIdentityManager.hasPrivateKey((String) EasyMock.anyObject())).andReturn(true) .anyTimes();// ww w. ja v a 2s . c o m EasyMock.expect(wrongIdentityManager.hasPrivateKey((String) EasyMock.anyObject(), (String) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(true).anyTimes(); try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair pair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = pair.getPrivate(); try { EasyMock.expect(wrongIdentityManager.getPrivateKey((String) EasyMock.anyObject())) .andReturn(privateKey).anyTimes(); EasyMock.expect(wrongIdentityManager.getPrivateKey((String) EasyMock.anyObject(), (String) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(privateKey) .anyTimes(); } catch (NetInfCheckedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } catch (Exception e) { throw new NetInfUncheckedException("error creating keys"); } EasyMock.replay(wrongIdentityManager); try { // FIXME added dummy-port! needs adjustment! CryptographyImpl crypto = new CryptographyImpl(wrongIdentityManager, algorithm, factory, convenienceCommunicator); crypto.decrypt(encryptedAttribute); Assert.fail("Exception expected. Wrong private key given."); } catch (NetInfCheckedSecurityException securityException) { System.out.println(securityException.getMessage()); } }
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);// ww w . jav a2 s . c o m // generate the initial set of keys for (int i = 0; i < 10; i++) { _keyPairs[i] = new ScrambledKeyPair(keygen.generateKeyPair()); } _log.info("Cached 10 KeyPairs for RSA communication"); testCipher((RSAPrivateKey) _keyPairs[0]._pair.getPrivate()); // Store keys for blowfish communication generateBlowFishKeys(); }
From source file:org.forgerock.openidm.selfservice.impl.SelfService.java
private SnapshotTokenHandlerFactory newTokenHandlerFactory() { return new SnapshotTokenHandlerFactory() { @Override//from ww w .j a va 2 s. co 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:com.mytalentfolio.h_daforum.CconnectToServer.java
/** * {@code connect} is for forming the secure connection between server and * android, sending and receiving of the data. * //from w w w. j av a 2 s . co m * @param arg0 * data which is to be sent to server. * * @return data in string format, received from the server. */ public String connect(String... arg0) { int nrOfDataToSendToServer = arg0.length; nrOfDataToSendToServer = nrOfDataToSendToServer - 1; boolean valid = false; String dataFromServer = "unverified", serverPublicKeySigStr, serverDataSig; try { //Creating the server certificate Certificate serverCertificate = getServerCertificate(); KeyStore keyStore = getKeyStore(serverCertificate); TrustManagerFactory tmf = getTrustManager(keyStore); SSLContext sslContext = getSSLContext(tmf); HostnameVerifier hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; HttpsURLConnection urlConnection = getURLConnection(sslContext, hostnameVerifier); // Converting the data into JSONObject JSONObject obj = new JSONObject(); for (int i = 0; i <= nrOfDataToSendToServer; i++) { obj.put("param" + i, arg0[i]); } // Converting the JSONObject into string String dataToSend = obj.toString(); KeyPairGenerator keyGen = getKeyPairGenerator(); KeyPair keyPair = keyGen.generateKeyPair(); //Public key for verifying the digital signature PublicKey clientPublicKeySig = keyPair.getPublic(); //Private key for signing the data PrivateKey clientPrivateKeySig = keyPair.getPrivate(); // Get signed data String sigData = getDataSig(clientPrivateKeySig, dataToSend); // Creating URL Format String urlData = URLEncoder.encode("clientPublicKeySig", "UTF-8") + "=" + URLEncoder .encode(Base64.encodeToString(clientPublicKeySig.getEncoded(), Base64.DEFAULT), "UTF-8"); urlData += "&" + URLEncoder.encode("clientData", "UTF-8") + "=" + URLEncoder.encode(dataToSend, "UTF-8"); urlData += "&" + URLEncoder.encode("clientDataSig", "UTF-8") + "=" + URLEncoder.encode(sigData, "UTF-8"); // Sending the data to the server OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream()); wr.write(urlData); wr.flush(); wr.close(); // Receiving the data from server BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; // Read Server Response while ((line = reader.readLine()) != null) { // Append server response in string sb.append(line + "\n"); // sb.append(line); } String text = sb.toString(); reader.close(); // Extracting the data, public key and signature received from // server Vector<String> storeExtractedValues = new Vector<String>(); storeExtractedValues = extractDataFromJson(text, "data"); dataFromServer = storeExtractedValues.get(0); storeExtractedValues = extractDataFromJson(text, "serverPublicKeySig"); serverPublicKeySigStr = storeExtractedValues.get(0); storeExtractedValues = extractDataFromJson(text, "serverDataSig"); serverDataSig = storeExtractedValues.get(0); // Converting the Server Public key format to Java compatible from PublicKey serverPublicKeySig = getServerPublicKey(serverPublicKeySigStr); // Verify the received data valid = getDataValidity(serverPublicKeySig, dataFromServer, serverDataSig); // Disconnect the url connection urlConnection.disconnect(); if (dataFromServer.equalsIgnoreCase("unverified")) { CExceptionHandling.ExceptionState = ExceptionSet.SENT_DATA_UNVERIFIED; return "-1"; } else if (valid == false) { CExceptionHandling.ExceptionState = ExceptionSet.RECEIVED_DATA_UNVERIFIED; return "-1"; } else { return dataFromServer; } } catch (Exception e) { CExceptionHandling.ExceptionMsg = e.getMessage(); if (e.toString().equals("java.net.SocketException: Network unreachable")) { CExceptionHandling.ExceptionState = ExceptionSet.NO_DATA_CONNECTION; } else if (e.toString().equals( "java.net.SocketTimeoutException: failed to connect to /10.0.2.2 (port 443) after 10000ms")) { CExceptionHandling.ExceptionState = ExceptionSet.CONNECTION_TIMEOUT; } else { CExceptionHandling.ExceptionState = ExceptionSet.OTHER_EXCEPTIONS; } return "-1"; } }
From source file:test.be.fedict.eid.applet.RSATest.java
@Test public void testManualEncryption() throws Exception { while (true) { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); SecureRandom random = new SecureRandom(); int keySize = 128; keyPairGenerator.initialize(new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F0), random); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey; LOG.debug("private key modulus: " + rsaPrivateKey.getModulus()); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; LOG.debug("public key modulus: " + rsaPublicKey.getModulus()); LOG.debug("public key exponent: " + rsaPublicKey.getPublicExponent()); LOG.debug("modulus size: " + rsaPublicKey.getModulus().toByteArray().length); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); int dataSize = keySize / 8 - 11; byte[] data1 = new byte[dataSize]; for (int i = 0; i < data1.length; i++) { data1[i] = 0x00;//from www. j a va 2s . co m } byte[] data2 = new byte[dataSize]; for (int i = 0; i < data2.length; i++) { data2[i] = 0x00; } data2[data2.length - 1] = 0x07; byte[] signatureValue1 = cipher.doFinal(data1); LOG.debug("signature size: " + signatureValue1.length); cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); byte[] signatureValue2 = cipher.doFinal(data2); BigInteger sigBigInt1 = new BigInteger(signatureValue1); BigInteger sigBigInt2 = new BigInteger(signatureValue2); BigInteger msgBigInt1 = sigBigInt1.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus()); BigInteger msgBigInt2 = sigBigInt2.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus()); LOG.debug("msg big int: " + msgBigInt1); byte[] msgBytes1 = msgBigInt1.toByteArray(); LOG.debug("original message size: " + msgBytes1.length); LOG.debug("original message1: " + new String(Hex.encodeHex(msgBytes1))); LOG.debug("original message2: " + new String(Hex.encodeHex(msgBigInt2.toByteArray()))); LOG.debug("msg1 prime: " + msgBigInt1.isProbablePrime(100)); LOG.debug("msg2 prime: " + msgBigInt2.isProbablePrime(100)); // BigInteger.pow offers a very naive implementation LOG.debug("calculating s1^e..."); BigInteger s1_e = sigBigInt1.pow(rsaPublicKey.getPublicExponent().intValue()); LOG.debug("s1^e: " + s1_e); LOG.debug("calculating s2^e..."); BigInteger s2_e = sigBigInt2.pow(rsaPublicKey.getPublicExponent().intValue()); LOG.debug("s2^e: " + s2_e); LOG.debug("calculating GCD..."); LOG.debug("msg1: " + msgBigInt1); LOG.debug("msg2: " + msgBigInt2); BigInteger a = s1_e.subtract(msgBigInt1); BigInteger b = s2_e.subtract(msgBigInt2); LOG.debug("a: " + a); LOG.debug("b: " + b); BigInteger candidateModulus = a.gcd(b); LOG.debug("candidate modulus: " + candidateModulus); LOG.debug("candidate modulus size: " + candidateModulus.toByteArray().length); BigInteger s_e = s1_e.multiply(s2_e); BigInteger m = msgBigInt1.multiply(msgBigInt2); while (false == rsaPublicKey.getModulus().equals(candidateModulus)) { LOG.error("incorrect candidate modulus"); LOG.debug("modulus | candidate modulus: " + candidateModulus.remainder(rsaPublicKey.getModulus()).equals(BigInteger.ZERO)); s_e = s_e.multiply(s1_e); m = m.multiply(msgBigInt1); BigInteger n1 = s_e.subtract(m).gcd(a); BigInteger n2 = s_e.subtract(m).gcd(b); candidateModulus = n1.gcd(n2); // try / 2 LOG.debug("new modulus: " + n1); LOG.debug("new modulus: " + n2); LOG.debug("candidate modulus: " + candidateModulus); LOG.debug("actual mod: " + rsaPublicKey.getModulus()); } } }
From source file:org.apache.openaz.xacml.pdp.test.custom.TestCustom.java
/** * This function generates the public/private key pair. Should never have to call this again, this was * called once to generate the keys. They were saved into the testsets/custom/datatype-function * sub-directory.//from w w w. ja v a 2s . c om */ public void generateKeyPair() { // // Generate a RSA private/public key pair // KeyPairGenerator keyGen; try { keyGen = KeyPairGenerator.getInstance(ALGORITHM); } catch (NoSuchAlgorithmException e) { logger.error("failed to generate keypair: " + e); return; } keyGen.initialize(1024); final KeyPair key = keyGen.generateKeyPair(); // // Save the keys to disk // Path file = Paths.get(this.directory, PRIVATEKEY_FILE); try (ObjectOutputStream os = new ObjectOutputStream(Files.newOutputStream(file))) { os.writeObject(key.getPrivate()); } catch (IOException e) { e.printStackTrace(); } file = Paths.get(this.directory, PUBLICKEY_FILE); try (ObjectOutputStream os = new ObjectOutputStream(Files.newOutputStream(file))) { os.writeObject(key.getPublic()); } catch (IOException e) { e.printStackTrace(); } }
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
@Test public void testSoftwareRSAKeyWrapping() throws Exception { final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); final KeyPair keyPair = keyPairGenerator.generateKeyPair(); final KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); final SecretKey secretKey = keyGenerator.generateKey(); LOG.debug("secret key algo: " + secretKey.getAlgorithm()); final Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.WRAP_MODE, keyPair.getPublic()); LOG.debug("cipher security provider: " + cipher.getProvider().getName()); LOG.debug("cipher type: " + cipher.getClass().getName()); final byte[] wrappedKey = cipher.wrap(secretKey); cipher.init(Cipher.UNWRAP_MODE, keyPair.getPrivate()); final Key resultKey = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); assertArrayEquals(secretKey.getEncoded(), resultKey.getEncoded()); }
From source file:org.apache.drill.yarn.appMaster.http.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.// w ww . j a v a 2 s. com * <p> * This is a shameless copy of * {@link org.apache.drill.exec.server.rest.Webserver#createHttpsConnector( )}. * The two should be merged at some point. The primary issue is that the Drill * version is tightly coupled to Drillbit configuration. * * @return Initialized {@link ServerConnector} for HTTPS connections. * @throws Exception */ private ServerConnector createHttpsConnector(Config config) throws Exception { LOG.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))) // { // LOG.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 { LOG.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, "Drill AM"); 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(jettyServer, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig)); sslConnector.setPort(config.getInt(DrillOnYarnConfig.HTTP_PORT)); return sslConnector; }
From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java
/** * Creates a key pair./*from w ww . j av a 2 s .co m*/ * * @return the key pair * @throws NoSuchAlgorithmException * if the required algorithm for the key pair does not exist */ private final KeyPair getKeyPair() throws NoSuchAlgorithmException { final KeyPairGenerator keyPairGenerator; // Key pair generator final KeyPair keypair; // Key pair keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024, new SecureRandom()); keypair = keyPairGenerator.generateKeyPair(); LOGGER.debug("Created key pair with private key {} {} and public key {} {}", keypair.getPrivate().getAlgorithm(), Arrays.asList(keypair.getPrivate().getEncoded()), keypair.getPublic().getAlgorithm(), Arrays.asList(keypair.getPublic().getEncoded())); return keypair; }