Example usage for org.bouncycastle.crypto.generators RSAKeyPairGenerator RSAKeyPairGenerator

List of usage examples for org.bouncycastle.crypto.generators RSAKeyPairGenerator RSAKeyPairGenerator

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.generators RSAKeyPairGenerator RSAKeyPairGenerator.

Prototype

RSAKeyPairGenerator

Source Link

Usage

From source file:beta01.SimpleRootCA.java

/**
 * Create a random 2048 bit RSA key pair
 *//*from  w  w  w  .  j  a v a2 s.  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

/**
 * Construct a new key factory./*from   w ww  . j ava  2s.  co m*/
 */
public KeyFactory() {
    BouncyCastleProvider provider = new BouncyCastleProvider();

    this.pemParserFactory = new PemParserFactory();
    this.bcKeyParametersFactory = new BcKeyParametersFactory();

    this.pemDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
    this.pemDecryptorProviderBuilder.setProvider(provider);
    this.pkcs8DecryptorProviderBuilder = new JceOpenSSLPKCS8DecryptorProviderBuilder();
    this.pkcs8DecryptorProviderBuilder.setProvider(provider);

    this.keyGenerator = new RSAKeyPairGenerator();
    this.random = new SecureRandom();
}

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

License:Open Source License

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

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

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

License:Apache License

/**
 * Init key pair generation engine//w w w  . j  av  a  2s  .  co m
 */
private void initEngine() {
    // only public key params, see specification
    if (publicKey != null) {
        keyGenerationParameters = ((KeyImpl) publicKey).getKeyGenerationParameters(rnd);
    }
    switch (algorithm) {
    case KeyPair.ALG_RSA:
    case KeyPair.ALG_RSA_CRT:
        if (keyGenerationParameters == null) {
            keyGenerationParameters = RSAKeyImpl.getDefaultKeyGenerationParameters(keyLength, rnd);
        }
        engine = new RSAKeyPairGenerator();
        break;
    //
    case KeyPair.ALG_DSA:
        if (keyLength < 512 || keyLength > 1024 || keyLength % 64 != 0) {
            CryptoException.throwIt(CryptoException.ILLEGAL_VALUE);
        }
        if (keyGenerationParameters == null) {
            keyGenerationParameters = DSAKeyImpl.getDefaultKeyGenerationParameters(keyLength, rnd);
        }
        engine = new DSAKeyPairGenerator();
        break;

    // ecc
    case KeyPair.ALG_EC_F2M:
    case KeyPair.ALG_EC_FP:
        if (keyGenerationParameters == null) {
            keyGenerationParameters = ECKeyImpl.getDefaultKeyGenerationParameters(algorithm, keyLength, rnd);
        }
        engine = new ECKeyPairGenerator();
        break;

    default:
        CryptoException.throwIt(CryptoException.NO_SUCH_ALGORITHM);
        break;
    }
    engine.init(keyGenerationParameters);

}

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);/*from w w w .  j a v a 2s  .c  o m*/
    keyGen.init(params);
    return keyGen.generateKeyPair();
}