Example usage for org.bouncycastle.crypto.params RSAKeyGenerationParameters RSAKeyGenerationParameters

List of usage examples for org.bouncycastle.crypto.params RSAKeyGenerationParameters RSAKeyGenerationParameters

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.params RSAKeyGenerationParameters RSAKeyGenerationParameters.

Prototype

public RSAKeyGenerationParameters(BigInteger publicExponent, SecureRandom random, int strength, int certainty) 

Source Link

Usage

From source file:beta01.SimpleRootCA.java

/**
 * Create a random 2048 bit RSA key pair
 *//*w w  w. j  av  a  2s  .  c  om*/
public static AsymmetricCipherKeyPair generateRSAKeyPair() throws Exception {
    AsymmetricCipherKeyPairGenerator kpGen = new RSAKeyPairGenerator();

    kpGen.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x11), new SecureRandom(), 2048, 12));

    return kpGen.generateKeyPair();
}

From source file:co.lqnt.lockbox.key.KeyFactory.java

License:Open Source License

/**
 * Generate a new private key.//w  w  w. j a v  a  2 s.  com
 *
 * @param size The size of the key in bits.
 *
 * @return The private key.
 */
public PrivateKey generatePrivateKey(final int size) {
    this.keyGenerator().init(new RSAKeyGenerationParameters(BigInteger.valueOf(65537),
            this.random().jceSecureRandom(), size, 80));

    AsymmetricKeyParameter keyParameters = this.keyGenerator().generateKeyPair().getPrivate();

    RSAPrivateCrtKeyParameters rsaKeyParameters;
    if (keyParameters instanceof RSAPrivateCrtKeyParameters) {
        rsaKeyParameters = (RSAPrivateCrtKeyParameters) keyParameters;
    } else {
        throw new RuntimeException("Invalid key pair generated by Bouncy Castle.");
    }

    return new PrivateKey(rsaKeyParameters.getModulus(), rsaKeyParameters.getPublicExponent(),
            rsaKeyParameters.getExponent(), rsaKeyParameters.getP(), rsaKeyParameters.getQ(),
            rsaKeyParameters.getDP(), rsaKeyParameters.getDQ(), rsaKeyParameters.getQInv());
}

From source file:com.foilen.smalltools.crypt.asymmetric.RSACrypt.java

License:Open Source License

@Override
public AsymmetricKeys generateKeyPair(int keysize) {
    // Generate/*from   w ww.j a  v  a  2s  .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  av a  2s  . 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_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;/*from  ww w .  j a  v a 2  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  w w  w . j ava2 s .c  o  m
    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  w  w. j a  v  a  2 s.  com*/
    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));/* www  . j  av a  2s. c  om*/

    kp = new BcPGPKeyPair(PGPPublicKey.RSA_GENERAL, kpg.generateKeyPair(), new Date());
}

From source file:com.licel.jcardsim.crypto.RSAKeyImpl.java

License:Apache License

/**
 * Get//from  w w  w . j av  a 2 s .  co m
 * <code>RSAKeyGenerationParameters</code>
 *
 * @param rnd Secure Random Generator
 * @return parameters for use with BouncyCastle API
 */
public KeyGenerationParameters getKeyGenerationParameters(SecureRandom rnd) {
    if (!isPrivate && exponent.isInitialized()) {
        return new RSAKeyGenerationParameters(exponent.getBigInteger(), rnd, size, 80);
    }
    return getDefaultKeyGenerationParameters(size, rnd);
}

From source file:com.licel.jcardsim.crypto.RSAKeyImpl.java

License:Apache License

/**
 * Get default//from w  ww .  ja v a 2 s .  c  o  m
 * <code>RSAKeyGenerationParameters</code>
 *
 * @param keySize key size in bits
 * @param rnd Secure Random Generator
 * @return parameters for use with BouncyCastle API
 */
static KeyGenerationParameters getDefaultKeyGenerationParameters(short keySize, SecureRandom rnd) {
    return new RSAKeyGenerationParameters(new BigInteger("10001", 16), rnd, keySize, 80);
}