List of usage examples for org.bouncycastle.crypto.generators RSAKeyPairGenerator generateKeyPair
public AsymmetricCipherKeyPair generateKeyPair()
From source file:com.foilen.smalltools.crypt.asymmetric.RSACrypt.java
License:Open Source License
@Override public AsymmetricKeys generateKeyPair(int keysize) { // Generate// www . j a v a2s .c om RSAKeyPairGenerator rsaKeyPairGenerator = new RSAKeyPairGenerator(); KeyGenerationParameters param = new RSAKeyGenerationParameters(new BigInteger("65537"), random, keysize, 80); rsaKeyPairGenerator.init(param); AsymmetricCipherKeyPair asymmetricCipherKeyPair = rsaKeyPairGenerator.generateKeyPair(); // Store AsymmetricKeys asymmetricKeys = new AsymmetricKeys(asymmetricCipherKeyPair.getPublic(), asymmetricCipherKeyPair.getPrivate()); return asymmetricKeys; }
From source file:com.geoxp.oss.client.OSSClient.java
License:Apache License
public static byte[] getSecret(String ossURL, String secretName, String sshKeyFingerprint) throws OSSException { SSHAgentClient agent = null;/*from ww w.j a va 2 s. c om*/ HttpClient httpclient = null; try { agent = new SSHAgentClient(); List<SSHKey> sshkeys = agent.requestIdentities(); // // If no SSH Key fingerprint was provided, try all SSH keys available in the agent // List<String> fingerprints = new ArrayList<String>(); if (null == sshKeyFingerprint) { for (SSHKey key : sshkeys) { fingerprints.add(key.fingerprint); } } else { fingerprints.add(sshKeyFingerprint.toLowerCase().replaceAll("[^0-9a-f]", "")); } int idx = 0; for (String fingerprint : fingerprints) { idx++; // // Check if the signing key is available in the agent // byte[] keyblob = null; for (SSHKey key : sshkeys) { if (key.fingerprint.equals(fingerprint)) { keyblob = key.blob; break; } } // // Throw an exception if this condition is encountered as it can only happen if // there was a provided fingerprint which is not in the agent. // if (null == keyblob) { throw new OSSException("SSH Key " + sshKeyFingerprint + " was not found by your SSH agent."); } // // Generate temporary RSA key pair // RSAKeyPairGenerator rsagen = new RSAKeyPairGenerator(); RSAKeyGenerationParameters params = new RSAKeyGenerationParameters(new BigInteger("65537"), CryptoHelper.getSecureRandom(), 2048, 64); rsagen.init(params); final AsymmetricCipherKeyPair keypair = rsagen.generateKeyPair(); RSAPrivateKey rsapriv = new RSAPrivateKey() { public BigInteger getModulus() { return ((RSAKeyParameters) keypair.getPrivate()).getModulus(); } public String getFormat() { return "PKCS#8"; } public byte[] getEncoded() { return null; } public String getAlgorithm() { return "RSA"; } public BigInteger getPrivateExponent() { return ((RSAKeyParameters) keypair.getPrivate()).getExponent(); } }; RSAPublicKey rsapub = new RSAPublicKey() { public BigInteger getModulus() { return ((RSAKeyParameters) keypair.getPublic()).getModulus(); } public String getFormat() { return "PKCS#8"; } public byte[] getEncoded() { return null; } public String getAlgorithm() { return "RSA"; } public BigInteger getPublicExponent() { return ((RSAKeyParameters) keypair.getPublic()).getExponent(); } }; // // Build OSS Token // // <TS> <<SECRET_NAME> <RSA_ENC_KEY>> <SSH Signing Key Blob> <SSH Signature Blob> // ByteArrayOutputStream token = new ByteArrayOutputStream(); byte[] tsdata = nowBytes(); token.write(CryptoHelper.encodeNetworkString(tsdata)); ByteArrayOutputStream subtoken = new ByteArrayOutputStream(); subtoken.write(CryptoHelper.encodeNetworkString(secretName.getBytes("UTF-8"))); subtoken.write(CryptoHelper.encodeNetworkString(CryptoHelper.sshKeyBlobFromPublicKey(rsapub))); token.write(CryptoHelper.encodeNetworkString(subtoken.toByteArray())); token.write(CryptoHelper.encodeNetworkString(keyblob)); // // Generate signature // byte[] sigblob = agent.sign(keyblob, token.toByteArray()); token.write(CryptoHelper.encodeNetworkString(sigblob)); String b64token = new String(Base64.encode(token.toByteArray()), "UTF-8"); // // Send request // httpclient = new DefaultHttpClient(); URIBuilder builder = new URIBuilder(ossURL + GuiceServletModule.SERVLET_PATH_GET_SECRET); builder.addParameter("token", b64token); URI uri = builder.build(); String qs = uri.getRawQuery(); HttpPost post = new HttpPost( uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + uri.getPath()); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(new StringEntity(qs)); HttpResponse response = httpclient.execute(post); HttpEntity resEntity = response.getEntity(); String content = EntityUtils.toString(resEntity, "UTF-8"); post.reset(); if (HttpServletResponse.SC_OK != response.getStatusLine().getStatusCode()) { // Only throw an exception if this is the last SSH key we could try if (idx == fingerprints.size()) { throw new OSSException("None of the provided keys (" + idx + ") could be used to retrieve secret. Latest error message was: " + response.getStatusLine().getReasonPhrase()); } else { continue; } } // // Extract encrypted secret and sealed key // byte[] secretandsealedkey = Base64.decode(content); byte[] encryptedsecret = CryptoHelper.decodeNetworkString(secretandsealedkey, 0); byte[] sealedkey = CryptoHelper.decodeNetworkString(secretandsealedkey, 4 + encryptedsecret.length); // // Unseal key // byte[] wrappingkey = CryptoHelper.decryptRSA(rsapriv, sealedkey); // // Unwrap secret // return CryptoHelper.unwrapAES(wrappingkey, encryptedsecret); } } catch (OSSException osse) { throw osse; } catch (Exception e) { throw new OSSException(e); } finally { if (null != httpclient) { httpclient.getConnectionManager().shutdown(); } if (null != agent) { agent.close(); } } return null; }
From source file:com.geoxp.oss.client.OSSClient.java
License:Apache License
public static List<String> getACL(String ossURL, String sshKeyFingerprint, String secretName) throws OSSException { SSHAgentClient agent = null;/* w ww .ja v a2 s .c o m*/ HttpClient httpclient = null; try { agent = new SSHAgentClient(); List<SSHKey> sshkeys = agent.requestIdentities(); // // If no SSH Key fingerprint was provided, try all SSH keys available in the agent // List<String> fingerprints = new ArrayList<String>(); if (null == sshKeyFingerprint) { for (SSHKey key : sshkeys) { fingerprints.add(key.fingerprint); } } else { fingerprints.add(sshKeyFingerprint.toLowerCase().replaceAll("[^0-9a-f]", "")); } int idx = 0; for (String fingerprint : fingerprints) { idx++; // // Check if the signing key is available in the agent // byte[] keyblob = null; for (SSHKey key : sshkeys) { if (key.fingerprint.equals(fingerprint)) { keyblob = key.blob; break; } } // // Throw an exception if this condition is encountered as it can only happen if // there was a provided fingerprint which is not in the agent. // if (null == keyblob) { throw new OSSException("SSH Key " + sshKeyFingerprint + " was not found by your SSH agent."); } // // Generate temporary RSA key pair // RSAKeyPairGenerator rsagen = new RSAKeyPairGenerator(); RSAKeyGenerationParameters params = new RSAKeyGenerationParameters(new BigInteger("65537"), CryptoHelper.getSecureRandom(), 2048, 64); rsagen.init(params); final AsymmetricCipherKeyPair keypair = rsagen.generateKeyPair(); RSAPrivateKey rsapriv = new RSAPrivateKey() { public BigInteger getModulus() { return ((RSAKeyParameters) keypair.getPrivate()).getModulus(); } public String getFormat() { return "PKCS#8"; } public byte[] getEncoded() { return null; } public String getAlgorithm() { return "RSA"; } public BigInteger getPrivateExponent() { return ((RSAKeyParameters) keypair.getPrivate()).getExponent(); } }; RSAPublicKey rsapub = new RSAPublicKey() { public BigInteger getModulus() { return ((RSAKeyParameters) keypair.getPublic()).getModulus(); } public String getFormat() { return "PKCS#8"; } public byte[] getEncoded() { return null; } public String getAlgorithm() { return "RSA"; } public BigInteger getPublicExponent() { return ((RSAKeyParameters) keypair.getPublic()).getExponent(); } }; // // Build OSS Token // // <TS> <<SECRET_NAME> <RSA_ENC_KEY>> <SSH Signing Key Blob> <SSH Signature Blob> // ByteArrayOutputStream token = new ByteArrayOutputStream(); byte[] tsdata = nowBytes(); token.write(CryptoHelper.encodeNetworkString(tsdata)); ByteArrayOutputStream subtoken = new ByteArrayOutputStream(); subtoken.write(CryptoHelper.encodeNetworkString(secretName.getBytes("UTF-8"))); subtoken.write(CryptoHelper.encodeNetworkString(CryptoHelper.sshKeyBlobFromPublicKey(rsapub))); token.write(CryptoHelper.encodeNetworkString(subtoken.toByteArray())); token.write(CryptoHelper.encodeNetworkString(keyblob)); // // Generate signature // byte[] sigblob = agent.sign(keyblob, token.toByteArray()); token.write(CryptoHelper.encodeNetworkString(sigblob)); String b64token = new String(Base64.encode(token.toByteArray()), "UTF-8"); // // Send request // httpclient = new DefaultHttpClient(); URIBuilder builder = new URIBuilder(ossURL + GuiceServletModule.SERVLET_PATH_GET_ACL); builder.addParameter("token", b64token); URI uri = builder.build(); String qs = uri.getRawQuery(); HttpPost post = new HttpPost( uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + uri.getPath()); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(new StringEntity(qs)); HttpResponse response = httpclient.execute(post); HttpEntity resEntity = response.getEntity(); String content = EntityUtils.toString(resEntity, "UTF-8"); post.reset(); if (HttpServletResponse.SC_OK != response.getStatusLine().getStatusCode()) { // Only throw an exception if this is the last SSH key we could try if (idx == fingerprints.size()) { throw new OSSException("None of the provided keys (" + idx + ") could be used to retrieve ACLs. Latest error message was: " + response.getStatusLine().getReasonPhrase()); } else { continue; } } // // Extract encrypted list of fingerprints and sealed key // byte[] fprandsealedkey = Base64.decode(content); byte[] encryptedfpr = CryptoHelper.decodeNetworkString(fprandsealedkey, 0); byte[] sealedkey = CryptoHelper.decodeNetworkString(fprandsealedkey, 4 + encryptedfpr.length); // // Unseal key // byte[] wrappingkey = CryptoHelper.decryptRSA(rsapriv, sealedkey); // // Unwrap fingerprints // byte[] fpr = CryptoHelper.unwrapAES(wrappingkey, encryptedfpr); int offset = 0; List<String> res = new ArrayList<String>(); while (offset < fpr.length) { byte[] f = CryptoHelper.decodeNetworkString(fpr, offset); if (null == f) { break; } offset += 4 + f.length; if (0 < f.length) { res.add(new String(Hex.encode(f), "UTF-8").replaceAll("([0-9a-f]{2})", "$1:")); } } return res; } } catch (OSSException osse) { throw osse; } catch (Exception e) { throw new OSSException(e); } finally { if (null != httpclient) { httpclient.getConnectionManager().shutdown(); } if (null != agent) { agent.close(); } } return null; }
From source file:com.geoxp.oss.CryptoHelperTest.java
License:Apache License
@Test public void testSSHSignatureBlobSign_RSA() throws Exception { RSAKeyPairGenerator rsakpg = new RSAKeyPairGenerator(); RSAKeyGenerationParameters params = new RSAKeyGenerationParameters(new BigInteger("35"), new SecureRandom(), 2048, 8);/*from www. j a v a 2 s .com*/ rsakpg.init(params); AsymmetricCipherKeyPair kp = rsakpg.generateKeyPair(); RSAPrivateCrtKeyParameters privParams = (RSAPrivateCrtKeyParameters) kp.getPrivate(); RSAKeyParameters pubParams = (RSAKeyParameters) kp.getPublic(); KeySpec ks = new RSAPrivateKeySpec(privParams.getModulus(), privParams.getExponent()); PrivateKey priv = KeyFactory.getInstance("RSA").generatePrivate(ks); ks = new RSAPublicKeySpec(pubParams.getModulus(), pubParams.getExponent()); PublicKey pub = KeyFactory.getInstance("RSA").generatePublic(ks); byte[] data = PLAINTEXT.getBytes(); byte[] sig = CryptoHelper.sshSignatureBlobSign(data, priv); Assert.assertTrue(CryptoHelper.sshSignatureBlobVerify(data, sig, pub)); }
From source file:com.github.jinahya.rfc5849.OAuthSignatureRsaSah1BcTest.java
License:Apache License
static <R> R applyKeyPair(final Function<AsymmetricCipherKeyPair, R> function) { final RSAKeyPairGenerator generator = new RSAKeyPairGenerator(); generator.init(new RSAKeyGenerationParameters(exponent(), // publicExponent new SecureRandom(), // random modulus().intValue(), // strength 80 // centainty ));//from w ww. j a v a2s .c o m final AsymmetricCipherKeyPair pair = generator.generateKeyPair(); return function.apply(pair); }
From source file:com.goodvikings.cryptim.api.KeyRing.java
License:BEER-WARE LICENSE
private void genOwnKeys() throws PGPException { RSAKeyPairGenerator kpg = new RSAKeyPairGenerator(); kpg.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), new SecureRandom(), ASYMM_KEY_SIZE, 90));//from ww w.ja v a2 s. com kp = new BcPGPKeyPair(PGPPublicKey.RSA_GENERAL, kpg.generateKeyPair(), new Date()); }
From source file:com.raphfrk.craftproxyclient.net.protocol.p16x.P16xProtocol.java
License:Open Source License
private AsymmetricCipherKeyPair getRSAKeyPair() { RSAKeyPairGenerator keyGen = new RSAKeyPairGenerator(); SecureRandom random = Crypt.getSeededRandom(); RSAKeyGenerationParameters params = new RSAKeyGenerationParameters(new BigInteger("10001", 16), random, 1024, 80);//w ww . j a va 2s .c om keyGen.init(params); return keyGen.generateKeyPair(); }
From source file:de.r2soft.empires.framework.security.CertificateUtil.java
License:Open Source License
/** * Generate a secure key pair.//from www . j a v a 2s . c o m * * @return */ private AsymmetricCipherKeyPair generateKeypair() { RSAKeyPairGenerator gen = new RSAKeyPairGenerator(); gen.init(new RSAKeyGenerationParameters(BigInteger.valueOf(3), new SecureRandom(), 1024, 80)); return gen.generateKeyPair(); }
From source file:dorkbox.util.crypto.CryptoRSA.java
License:Apache License
public static AsymmetricCipherKeyPair generateKeyPair(SecureRandom secureRandom, int keyLength) { RSAKeyPairGenerator keyGen = new RSAKeyPairGenerator(); RSAKeyGenerationParameters params = new RSAKeyGenerationParameters(new BigInteger("65537"), // public exponent secureRandom, //pnrg keyLength, // key length 8); //the number of iterations of the Miller-Rabin primality test. keyGen.init(params);//from w w w. j a v a 2 s.co m return keyGen.generateKeyPair(); }
From source file:dorkbox.util.crypto.RsaTest.java
License:Apache License
@SuppressWarnings("deprecation") @Test//w w w .ja va2 s.c o m public void RsaSerialization() throws IOException { RSAKeyPairGenerator keyGen = new RSAKeyPairGenerator(); RSAKeyGenerationParameters params = new RSAKeyGenerationParameters(new BigInteger("65537"), // public exponent new SecureRandom(entropySeed.getBytes()), //pnrg 1024, // key length 8); //the number of iterations of the Miller-Rabin primality test. keyGen.init(params); AsymmetricCipherKeyPair key = keyGen.generateKeyPair(); RSAKeyParameters public1 = (RSAKeyParameters) key.getPublic(); RSAPrivateCrtKeyParameters private1 = (RSAPrivateCrtKeyParameters) key.getPrivate(); Kryo kryo = new Kryo(); kryo.register(RSAKeyParameters.class, new RsaPublicKeySerializer()); kryo.register(RSAPrivateCrtKeyParameters.class, new RsaPrivateKeySerializer()); // Test output to stream, large buffer. ByteArrayOutputStream outStream = new ByteArrayOutputStream(); Output output = new Output(outStream, 4096); kryo.writeClassAndObject(output, public1); output.flush(); // Test input from stream, large buffer. Input input = new Input(new ByteArrayInputStream(outStream.toByteArray()), 4096); RSAKeyParameters public2 = (RSAKeyParameters) kryo.readClassAndObject(input); if (!CryptoRSA.compare(public1, public2)) { fail("public keys not equal"); } // Test output to stream, large buffer. outStream = new ByteArrayOutputStream(); output = new Output(outStream, 4096); kryo.writeClassAndObject(output, private1); output.flush(); // Test input from stream, large buffer. input = new Input(new ByteArrayInputStream(outStream.toByteArray()), 4096); RSAPrivateCrtKeyParameters private2 = (RSAPrivateCrtKeyParameters) kryo.readClassAndObject(input); if (!CryptoRSA.compare(private1, private2)) { fail("private keys not equal"); } }