Search in sources :

Example 6 with KeyPairGenerator

use of java.security.KeyPairGenerator in project Openfire by igniterealtime.

the class KeystoreTestUtils method generateCertificateChainWithExpiredRootCert.

/**
     * Generates a chain of certificates, identical to {@link #generateValidCertificateChain()}, with one exception:
     * the last certificate (the root CA) is expired.
     *
     * @return an array of certificates. Never null, never an empty array.
     */
public static X509Certificate[] generateCertificateChainWithExpiredRootCert() throws Exception {
    int length = 4;
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(512);
    // Root certificate (representing the CA) is self-signed.
    KeyPair subjectKeyPair = keyPairGenerator.generateKeyPair();
    KeyPair issuerKeyPair = subjectKeyPair;
    final X509Certificate[] result = new X509Certificate[length];
    for (int i = length - 1; i >= 0; i--) {
        // root certificate needs to be expired!
        boolean isValid = (i != length - 1);
        result[i] = generateTestCertificate(isValid, issuerKeyPair, subjectKeyPair, i);
        // Further away from the root CA, each certificate is issued by the previous subject.
        issuerKeyPair = subjectKeyPair;
        subjectKeyPair = keyPairGenerator.generateKeyPair();
    }
    return result;
}
Also used : KeyPair(java.security.KeyPair) KeyPairGenerator(java.security.KeyPairGenerator) X509Certificate(java.security.cert.X509Certificate)

Example 7 with KeyPairGenerator

use of java.security.KeyPairGenerator in project Openfire by igniterealtime.

the class KeystoreTestUtils method generateTestCertificate.

private static X509Certificate generateTestCertificate(final boolean isValid, final boolean isSelfSigned, int indexAwayFromEndEntity) throws Exception {
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(512);
    final KeyPair subjectKeyPair;
    final KeyPair issuerKeyPair;
    if (isSelfSigned) {
        // Self signed: subject and issuer are the same entity.
        subjectKeyPair = keyPairGenerator.generateKeyPair();
        issuerKeyPair = subjectKeyPair;
    } else {
        subjectKeyPair = keyPairGenerator.generateKeyPair();
        issuerKeyPair = keyPairGenerator.generateKeyPair();
    }
    return generateTestCertificate(isValid, issuerKeyPair, subjectKeyPair, indexAwayFromEndEntity);
}
Also used : KeyPair(java.security.KeyPair) KeyPairGenerator(java.security.KeyPairGenerator)

Example 8 with KeyPairGenerator

use of java.security.KeyPairGenerator in project Android-Developers-Samples by johnjohndoe.

the class BasicAndroidKeyStoreFragment method createKeys.

/**
     * Creates a public and private key and stores it using the Android Key Store, so that only
     * this application will be able to access the keys.
     */
public void createKeys(Context context) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    // BEGIN_INCLUDE(create_valid_dates)
    // Create a start and end time, for the validity range of the key pair that's about to be
    // generated.
    Calendar start = new GregorianCalendar();
    Calendar end = new GregorianCalendar();
    end.add(1, Calendar.YEAR);
    //END_INCLUDE(create_valid_dates)
    // BEGIN_INCLUDE(create_spec)
    // The KeyPairGeneratorSpec object is how parameters for your key pair are passed
    // to the KeyPairGenerator.  For a fun home game, count how many classes in this sample
    // start with the phrase "KeyPair".
    KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context).setAlias(mAlias).setSubject(new X500Principal("CN=" + mAlias)).setSerialNumber(BigInteger.valueOf(1337)).setStartDate(start.getTime()).setEndDate(end.getTime()).build();
    // END_INCLUDE(create_spec)
    // BEGIN_INCLUDE(create_keypair)
    // Initialize a KeyPair generator using the the intended algorithm (in this example, RSA
    // and the KeyStore.  This example uses the AndroidKeyStore.
    KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance(SecurityConstants.TYPE_RSA, SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE);
    kpGenerator.initialize(spec);
    KeyPair kp = kpGenerator.generateKeyPair();
    Log.d(TAG, "Public Key is: " + kp.getPublic().toString());
// END_INCLUDE(create_keypair)
}
Also used : KeyPairGeneratorSpec(android.security.KeyPairGeneratorSpec) KeyPair(java.security.KeyPair) GregorianCalendar(java.util.GregorianCalendar) Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) X500Principal(javax.security.auth.x500.X500Principal) KeyPairGenerator(java.security.KeyPairGenerator)

Example 9 with KeyPairGenerator

use of java.security.KeyPairGenerator in project PushSms by koush.

the class MiddlewareService method getOrCreateKeyPair.

// create/read the keypair as necessary
private void getOrCreateKeyPair() {
    String encodedKeyPair = settings.getString("keypair", null);
    if (encodedKeyPair != null) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            ByteArrayInputStream bin = new ByteArrayInputStream(Base64.decode(encodedKeyPair, Base64.DEFAULT));
            ObjectInputStream in = new ObjectInputStream(bin);
            rsaPublicKeySpec = new RSAPublicKeySpec((BigInteger) in.readObject(), (BigInteger) (in.readObject()));
            RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec((BigInteger) in.readObject(), (BigInteger) (in.readObject()));
            PublicKey pub = keyFactory.generatePublic(rsaPublicKeySpec);
            PrivateKey priv = keyFactory.generatePrivate(rsaPrivateKeySpec);
            keyPair = new KeyPair(pub, priv);
            return;
        } catch (Exception e) {
            Log.e(LOGTAG, "KeyPair load error", e);
        }
    }
    try {
        KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
        gen.initialize(2048);
        keyPair = gen.generateKeyPair();
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        rsaPublicKeySpec = keyFactory.getKeySpec(keyPair.getPublic(), RSAPublicKeySpec.class);
        RSAPrivateKeySpec privateKeySpec = keyFactory.getKeySpec(keyPair.getPrivate(), RSAPrivateKeySpec.class);
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bout);
        out.writeObject(rsaPublicKeySpec.getModulus());
        out.writeObject(rsaPublicKeySpec.getPublicExponent());
        out.writeObject(privateKeySpec.getModulus());
        out.writeObject(privateKeySpec.getPrivateExponent());
        out.flush();
        settings.edit().putString("keypair", Base64.encodeToString(bout.toByteArray(), Base64.DEFAULT)).commit();
        settings.edit().putBoolean("needs_register", true).commit();
    } catch (Exception e) {
        Log.wtf(LOGTAG, "KeyPair generation error", e);
        keyPair = null;
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) KeyPairGenerator(java.security.KeyPairGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) RemoteException(android.os.RemoteException) IOException(java.io.IOException) RSAPrivateKeySpec(java.security.spec.RSAPrivateKeySpec) ByteArrayInputStream(java.io.ByteArrayInputStream) BigInteger(java.math.BigInteger) KeyFactory(java.security.KeyFactory) ObjectInputStream(java.io.ObjectInputStream)

Example 10 with KeyPairGenerator

use of java.security.KeyPairGenerator in project jjwt by jwtk.

the class RsaProvider method generateKeyPair.

/**
     * Generates a new secure-random key pair of the specified size using the specified SecureRandom according to the
     * specified {@code jcaAlgorithmName}.
     *
     * @param jcaAlgorithmName the name of the JCA algorithm to use for key pair generation, for example, {@code RSA}.
     * @param keySizeInBits    the key size in bits (<em>NOT bytes</em>)
     * @param random           the SecureRandom generator to use during key generation.
     * @return a new secure-randomly generated key pair of the specified size using the specified SecureRandom according
     * to the specified {@code jcaAlgorithmName}.
     * @see #generateKeyPair()
     * @see #generateKeyPair(int)
     * @see #generateKeyPair(int, SecureRandom)
     * @since 0.5
     */
protected static KeyPair generateKeyPair(String jcaAlgorithmName, int keySizeInBits, SecureRandom random) {
    KeyPairGenerator keyGenerator;
    try {
        keyGenerator = KeyPairGenerator.getInstance(jcaAlgorithmName);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("Unable to obtain an RSA KeyPairGenerator: " + e.getMessage(), e);
    }
    keyGenerator.initialize(keySizeInBits, random);
    return keyGenerator.genKeyPair();
}
Also used : KeyPairGenerator(java.security.KeyPairGenerator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Aggregations

KeyPairGenerator (java.security.KeyPairGenerator)197 KeyPair (java.security.KeyPair)145 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)43 SecureRandom (java.security.SecureRandom)39 PublicKey (java.security.PublicKey)27 PrivateKey (java.security.PrivateKey)26 X509Certificate (java.security.cert.X509Certificate)23 KeyFactory (java.security.KeyFactory)21 IOException (java.io.IOException)19 BigInteger (java.math.BigInteger)17 GeneralSecurityException (java.security.GeneralSecurityException)15 Signature (java.security.Signature)15 Date (java.util.Date)15 Cipher (javax.crypto.Cipher)15 KeyAgreement (javax.crypto.KeyAgreement)15 RSAPublicKey (java.security.interfaces.RSAPublicKey)14 X500Principal (javax.security.auth.x500.X500Principal)13 ECPrivateKey (java.security.interfaces.ECPrivateKey)12 ECPublicKey (java.security.interfaces.ECPublicKey)12 HashMap (java.util.HashMap)11