Example usage for java.security KeyPairGenerator generateKeyPair

List of usage examples for java.security KeyPairGenerator generateKeyPair

Introduction

In this page you can find the example usage for java.security KeyPairGenerator generateKeyPair.

Prototype

public KeyPair generateKeyPair() 

Source Link

Document

Generates a key pair.

Usage

From source file:be.e_contract.mycarenet.common.SessionKey.java

/**
 * Generator constructor. Creates a new MyCareNet session key.
 * //from w w w  . j  a  v  a 2  s . c  o  m
 * @param keySize
 *            the RSA key size.
 */
public SessionKey(int keySize) {
    KeyPairGenerator keyPairGenerator;
    try {
        keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("RSA algo not available", e);
    }
    SecureRandom random = new SecureRandom();
    try {
        keyPairGenerator.initialize(new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F4), random);
    } catch (InvalidAlgorithmParameterException e) {
        throw new RuntimeException("unsupported key size: " + keySize);
    }
    this.keyPair = keyPairGenerator.generateKeyPair();
}

From source file:org.apache.xml.security.test.encryption.XMLCipherTester.java

/**
 * Test encryption using a generated AES 256 bit key that is
 * encrypted using an RSA key.  Reverse using KEK
 *///  w w w .j  a v a 2 s . com

public void testAES128ElementRSAKWCipherUsingKEK() throws Exception {

    Document d = document(); // source
    Document ed = null;
    Document dd = null;
    Element e = (Element) d.getElementsByTagName(element()).item(index());
    Element ee = null;

    String source = null;
    String target = null;

    if (haveISOPadding) {

        source = toString(d);

        // Generate an RSA key
        KeyPairGenerator rsaKeygen = KeyPairGenerator.getInstance("RSA");
        KeyPair kp = rsaKeygen.generateKeyPair();
        PrivateKey priv = kp.getPrivate();
        PublicKey pub = kp.getPublic();

        // Generate a traffic key
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        keygen.init(256);
        Key key = keygen.generateKey();

        cipher = XMLCipher.getInstance(XMLCipher.RSA_v1dot5);
        cipher.init(XMLCipher.WRAP_MODE, pub);
        EncryptedKey encryptedKey = cipher.encryptKey(d, key);

        // encrypt
        cipher = XMLCipher.getInstance(XMLCipher.AES_256);
        cipher.init(XMLCipher.ENCRYPT_MODE, key);
        EncryptedData builder = cipher.getEncryptedData();

        KeyInfo builderKeyInfo = builder.getKeyInfo();
        if (builderKeyInfo == null) {
            builderKeyInfo = new KeyInfo(d);
            builder.setKeyInfo(builderKeyInfo);
        }

        builderKeyInfo.add(encryptedKey);

        ed = cipher.doFinal(d, e);
        log.debug("Encrypted document");
        log.debug(toString(ed));

        //decrypt
        key = null;
        ee = (Element) ed.getElementsByTagName("xenc:EncryptedData").item(0);
        cipher = XMLCipher.getInstance(XMLCipher.AES_128);
        cipher.init(XMLCipher.DECRYPT_MODE, null);
        cipher.setKEK(priv);
        dd = cipher.doFinal(ed, ee);

        target = toString(dd);
        log.debug("Output document");
        log.debug(target);

        Assert.assertEquals(source, target);
    } else {
        log.warn("Test testAES128ElementRSAKWCipherUsingKEK skipped as necessary algorithms not available");
    }
}

From source file:org.mitre.openid.connect.client.AbstractOIDCAuthenticationFilter.java

@Override
public void afterPropertiesSet() {
    super.afterPropertiesSet();

    Assert.notNull(errorRedirectURI, "An Error Redirect URI must be supplied");

    KeyPairGenerator keyPairGenerator;

    try {//from  w  w  w .  j a  va  2  s . co m
        keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(KEY_SIZE);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        publicKey = keyPair.getPublic();
        privateKey = keyPair.getPrivate();

        signer = Signature.getInstance(SIGNING_ALGORITHM);
    } catch (GeneralSecurityException generalSecurityException) {
        // generalSecurityException.printStackTrace();
        throw new IllegalStateException(generalSecurityException);
    }

    // prepend the spec necessary SCOPE
    setScope((scope != null && !scope.isEmpty()) ? SCOPE + " " + scope : SCOPE);
}

From source file:org.ejbca.util.keystore.KeyStoreContainerBase.java

private byte[] generate(final KeyPairGenerator kpg, final String keyEntryName, final String sigAlgName)
        throws Exception {
    // We will make a loop to retry key generation here. Using the IAIK provider it seems to give
    // CKR_OBJECT_HANDLE_INVALID about every second time we try to store keys
    // But if we try again it succeeds
    int bar = 0;//  w  w w .  ja  v  a  2 s  .com
    while (bar < 3) {
        bar++;
        try {
            log.debug("generating...");
            final KeyPair keyPair = kpg.generateKeyPair();
            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = getSelfCertificate("CN=some guy, L=around, C=US", (long) 30 * 24 * 60 * 60 * 365,
                    sigAlgName, keyPair);
            log.debug("Creating certificate with entry " + keyEntryName + '.');
            setKeyEntry(keyEntryName, keyPair.getPrivate(), chain);
            break; // success no need to try more
        } catch (KeyStoreException e) {
            log.info("Failed to generate or store new key, will try 3 times. This was try: " + bar, e);
        }
    }
    return storeKeyStore();
}

From source file:org.bedework.util.security.pki.PKITools.java

/**
 * @return RSAKeys/*from   w  ww.  jav a 2 s  .c o m*/
 * @throws PKIException
 */
public RSAKeys genRSAKeys() throws PKIException {
    RSAKeys keys = new RSAKeys();

    try {
        SecureRandom secureRandom = new SecureRandom();
        secureRandom.nextBytes(new byte[1]);
        KeyPairGenerator rsaKeyGen;

        if (curSchema.pName == null) {
            rsaKeyGen = KeyPairGenerator.getInstance(curSchema.keyFactory);
        } else {
            rsaKeyGen = KeyPairGenerator.getInstance(curSchema.keyFactory, curSchema.pName);
        }

        rsaKeyGen.initialize(1024, secureRandom);

        if (trace()) {
            trace("Generating keys...");
        }

        KeyPair rsaKeyPair = rsaKeyGen.generateKeyPair();

        if (trace()) {
            trace("Saving Public Key...");
        }

        keys.privateKey = rsaKeyPair.getPrivate().getEncoded();
        keys.publicKey = rsaKeyPair.getPublic().getEncoded();

        if (trace()) {
            trace("Done...");
        }

        return keys;
    } catch (Throwable t) {
        throw new PKIException(t);
    }
}

From source file:org.tolven.config.model.CredentialManager.java

private X509CertificatePrivateKeyPair createSelfSignedCertificate(X500Principal subjectX500Principal)
        throws GeneralSecurityException {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024);/*ww w.  j  a  v a  2 s  .  com*/
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    X509Certificate certificate = signCertificate(subjectX500Principal, keyPair.getPublic(),
            subjectX500Principal, keyPair.getPrivate());
    return new X509CertificatePrivateKeyPair(certificate, keyPair.getPrivate());
}

From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java

/**
 * Create a keystore for this user to be used for document signing, store it associated with the user's
 * person node/*from  ww  w .j  av  a  2s . c  om*/
 * 
 * @param person
 * @param password
 * 
 * @return a Java KeyStore object suitable for document signing
 * @throws NoSuchAlgorithmException 
 * @throws NoSuchProviderException 
 * @throws KeyStoreException 
 * @throws IOException 
 * @throws CertificateException 
 */
private KeyStore createUserKeyStore(NodeRef person, String password) throws NoSuchAlgorithmException,
        NoSuchProviderException, KeyStoreException, CertificateException, IOException {

    // get the alias from the configuration
    String alias = config.getProperty(RepositoryManagedSignatureProviderFactory.ALIAS);

    // initialize key generator
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
    keyGen.initialize(2048, random);

    // generate a keypair
    KeyPair pair = keyGen.generateKeyPair();
    PrivateKey priv = pair.getPrivate();
    PublicKey pub = pair.getPublic();

    // generate the user certificate
    Certificate cert = generateCertificate(pair, person);

    // get the ca cert used to sign and create cert chain
    KeyStore trustedKs = getTrustedKeyStore();
    Certificate[] caChain = getCaCertChain(trustedKs);
    Certificate[] certChain = new Certificate[caChain.length + 1];
    certChain[0] = cert;
    for (int i = 0; i < caChain.length; i++) {
        certChain[i + 1] = caChain[i];
    }

    // create keystore, adding private key and cert chain
    KeyStore ks = KeyStore.getInstance("pkcs12");
    ks.load(null, password.toCharArray());
    ks.setKeyEntry(alias, priv, password.toCharArray(), certChain);

    // save the keystore
    saveUserKeyStore(person, ks, password);

    // also save the public key separately, will need it 
    // for later validaiton activities
    saveUserPublicKey(person, pub);

    // return the generated keystore
    return ks;

}

From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java

/**
 * Initialize the Diffie-Hellman keys. This method is not thread safe
 *//*from   w  ww.j a v  a2  s. co  m*/
public static void initDHKeys(DistributionConfig config) throws Exception {

    dhSKAlgo = config.getSecurityClientDHAlgo();
    dhPrivateKey = null;
    dhPublicKey = null;
    // Initialize the keys when either the host is a client that has
    // non-blank setting for DH symmetric algo, or this is a server
    // that has authenticator defined.
    if ((dhSKAlgo != null && dhSKAlgo.length() > 0) /* || securityService.isClientSecurityRequired() */) {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
        DHParameterSpec dhSpec = new DHParameterSpec(dhP, dhG, dhL);
        keyGen.initialize(dhSpec);
        KeyPair keypair = keyGen.generateKeyPair();

        // Get the generated public and private keys
        dhPrivateKey = keypair.getPrivate();
        dhPublicKey = keypair.getPublic();

        random = new SecureRandom();
        // Force the random generator to seed itself.
        byte[] someBytes = new byte[48];
        random.nextBytes(someBytes);
    }
}

From source file:org.cesecore.keys.util.KeyStoreTools.java

private void generateKeyPair(final KeyPairGenerator kpg, final String keyEntryName, final String sigAlgName) {
    // We will make a loop to retry key generation here. Using the IAIK provider it seems to give
    // CKR_OBJECT_HANDLE_INVALID about every second time we try to store keys
    // But if we try again it succeeds
    int bar = 0;/*w ww .ja  v a 2  s .  c o m*/
    while (bar < 3) {
        bar++;
        try {
            log.debug("generating...");
            final KeyPair keyPair = kpg.generateKeyPair();
            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = getSelfCertificate("CN=some guy, L=around, C=US", (long) 30 * 24 * 60 * 60 * 365,
                    sigAlgName, keyPair);
            log.debug("Creating certificate with entry " + keyEntryName + '.');
            setKeyEntry(keyEntryName, keyPair.getPrivate(), chain);
            break; // success no need to try more
        } catch (KeyStoreException e) {
            log.info("Failed to generate or store new key, will try 3 times. This was try: " + bar, e);
        } catch (CertificateException e) {
            throw new KeyCreationException(
                    "Can't create keystore because dummy certificate chain creation failed.", e);
        } catch (InvalidKeyException e) {
            throw new KeyCreationException("Dummy certificate chain was created with an invalid key", e);
        }
    }
}

From source file:it.scoppelletti.security.keypairgen.KeyPairGeneratorBean.java

/**
 * Esegue l&rsquo;operazione./* w w w  .  j a va2 s  . c om*/
 */
public void run() {
    Properties props;
    OutputStream publicOut = null;
    OutputStream privateOut = null;
    KeyPair keyPair;
    KeyPairGenerator keyGen;

    if (myConfigFile == null) {
        throw new PropertyNotSetException(toString(), "configFile");
    }
    if (myPublicFile == null) {
        throw new PropertyNotSetException(toString(), "publicFile");
    }
    if (myPrivateFile == null) {
        throw new PropertyNotSetException(toString(), "privateFile");
    }

    try {
        props = loadConfig();
        publicOut = openOutput(myPublicFile);
        if (publicOut == null) {
            return;
        }
        privateOut = openOutput(myPrivateFile);
        if (privateOut == null) {
            return;
        }

        keyGen = CryptoUtils.getKeyPairGenerator(props, myPrefix);
        keyPair = keyGen.generateKeyPair();

        props = CryptoUtils.toProperties(keyPair.getPublic(), myEncoded);
        props.store(publicOut, null);

        props = CryptoUtils.toProperties(keyPair.getPrivate(), myEncoded);
        props.store(privateOut, null);
    } catch (IOException ex) {
        throw new IOOperationException(ex);
    } finally {
        if (publicOut != null) {
            IOUtils.close(publicOut);
            publicOut = null;
        }
        if (privateOut != null) {
            IOUtils.close(privateOut);
            privateOut = null;
        }
    }
}