Example usage for java.security KeyPairGenerator initialize

List of usage examples for java.security KeyPairGenerator initialize

Introduction

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

Prototype

public void initialize(AlgorithmParameterSpec params, SecureRandom random)
        throws InvalidAlgorithmParameterException 

Source Link

Document

Initializes the key pair generator with the given parameter set and source of randomness.

Usage

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//w w w.  jav a  2s .c  o m
 * 
 * @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.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java

public X509Certificate generateX509Certificate() throws KeystoreException {

    CommonUtil commonUtil = new CommonUtil();
    Date validityBeginDate = commonUtil.getValidityStartDate();
    Date validityEndDate = commonUtil.getValidityEndDate();

    Security.addProvider(new BouncyCastleProvider());

    try {/*from  w w  w. ja v a  2  s. c o m*/
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(CertificateManagementConstants.RSA,
                CertificateManagementConstants.PROVIDER);
        keyPairGenerator.initialize(CertificateManagementConstants.RSA_KEY_LENGTH, new SecureRandom());
        KeyPair pair = keyPairGenerator.generateKeyPair();
        X500Principal principal = new X500Principal(CertificateManagementConstants.DEFAULT_PRINCIPAL);

        X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(principal,
                CommonUtil.generateSerialNumber(), validityBeginDate, validityEndDate, principal,
                pair.getPublic());
        ContentSigner contentSigner = new JcaContentSignerBuilder(CertificateManagementConstants.SHA256_RSA)
                .setProvider(CertificateManagementConstants.PROVIDER).build(pair.getPrivate());
        X509Certificate certificate = new JcaX509CertificateConverter()
                .setProvider(CertificateManagementConstants.PROVIDER)
                .getCertificate(certificateBuilder.build(contentSigner));

        // cert.checkValidity();

        certificate.verify(certificate.getPublicKey());

        List<org.wso2.carbon.certificate.mgt.core.bean.Certificate> certificates = new ArrayList<>();
        org.wso2.carbon.certificate.mgt.core.bean.Certificate certificateToStore = new org.wso2.carbon.certificate.mgt.core.bean.Certificate();
        certificateToStore.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
        certificateToStore.setCertificate(certificate);
        certificates.add(certificateToStore);
        saveCertInKeyStore(certificates);

        return certificate;
    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "No such algorithm found when generating certificate";
        throw new KeystoreException(errorMsg, e);
    } catch (NoSuchProviderException e) {
        String errorMsg = "No such provider found when generating certificate";
        throw new KeystoreException(errorMsg, e);
    } catch (OperatorCreationException e) {
        String errorMsg = "Issue in operator creation when generating certificate";
        throw new KeystoreException(errorMsg, e);
    } catch (CertificateExpiredException e) {
        String errorMsg = "Certificate expired after generating certificate";
        throw new KeystoreException(errorMsg, e);
    } catch (CertificateNotYetValidException e) {
        String errorMsg = "Certificate not yet valid when generating certificate";
        throw new KeystoreException(errorMsg, e);
    } catch (CertificateException e) {
        String errorMsg = "Certificate issue occurred when generating certificate";
        throw new KeystoreException(errorMsg, e);
    } catch (InvalidKeyException e) {
        String errorMsg = "Invalid key used when generating certificate";
        throw new KeystoreException(errorMsg, e);
    } catch (SignatureException e) {
        String errorMsg = "Signature related issue occurred when generating certificate";
        throw new KeystoreException(errorMsg, e);
    }
}

From source file:org.texai.x509.X509Utils.java

/** Creates a random 3072 bit RSA key pair.
 * @return a random 3072 bit RSA key pair
 * @throws NoSuchAlgorithmException when an invalid algorithm is given
 * @throws NoSuchProviderException  when an invalid provider is given
 * @throws InvalidAlgorithmParameterException when an invalid algorithm parameter is given
 *//*  w  w  w  .j a v  a  2s  .  co  m*/
public static KeyPair generateRSAKeyPair3072()
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", BOUNCY_CASTLE_PROVIDER);
    final AlgorithmParameterSpec algorithmParameterSpec = new RSAKeyGenParameterSpec(3072,
            RSAKeyGenParameterSpec.F4);
    keyPairGenerator.initialize(algorithmParameterSpec, getSecureRandom());
    return keyPairGenerator.generateKeyPair();
}

From source file:org.texai.x509.X509Utils.java

/** Creates a random 2048 bit RSA key pair.
 * @return a random 2048 bit RSA key pair
 * @throws NoSuchAlgorithmException when an invalid algorithm is given
 * @throws NoSuchProviderException  when an invalid provider is given
 * @throws InvalidAlgorithmParameterException when an invalid algorithm parameter is given
 *//*from  w  w  w . jav a  2  s.  c o m*/
public static KeyPair generateRSAKeyPair2048()
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", BOUNCY_CASTLE_PROVIDER);
    final AlgorithmParameterSpec algorithmParameterSpec = new RSAKeyGenParameterSpec(2048,
            RSAKeyGenParameterSpec.F4);
    keyPairGenerator.initialize(algorithmParameterSpec, getSecureRandom());
    return keyPairGenerator.generateKeyPair();
}

From source file:net.sourceforge.msscodefactory.cflib.v2_1.CFLib.Tip.CFTipEnvelopeHandler.java

public void initServerKeys() throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException,
        IllegalBlockSizeException {
    if (serverKeyPair == null) {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(2048, new SecureRandom());
        serverKeyPair = kpg.generateKeyPair();
    }/* w  w w  .j a v a  2s.c  om*/

    byte encodedPKey[] = getEncodedServerPublicKey();
    String encoded = new String(Base64.encodeBase64(encodedPKey));
    serverInfo.setServerLoginKey(encoded);
}

From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java

private KeyPair generateKey(String encryptionName, String curveName) throws CryptoException {
    try {//from w w  w.  j av a 2 s .  c  om
        ECGenParameterSpec ecGenSpec = new ECGenParameterSpec(curveName);
        KeyPairGenerator g = SECURITY_PROVIDER == null ? KeyPairGenerator.getInstance(encryptionName)
                : KeyPairGenerator.getInstance(encryptionName, SECURITY_PROVIDER);
        g.initialize(ecGenSpec, new SecureRandom());
        return g.generateKeyPair();
    } catch (Exception exp) {
        throw new CryptoException("Unable to generate key pair", exp);
    }
}

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

/**
 * Generates a keypair//w w w .  j a  va 2 s  .c  o  m
 * 
 * @param keySpec
 *            string specification of keys to generate, typical value is 2048 for RSA keys,
 *            1024 for DSA keys, secp256r1 for ECDSA keys, or null if algspec is to be used.
 * @param algSpec
 *            AlgorithmParameterSpec of keys to generate, typically an EXParameterSpec for EC keys, or null if keySpec is to be used.
 * @param keyAlg
 *            algorithm of keys to generate, typical value is RSA, DSA or ECDSA, see AlgorithmConstants.KEYALGORITHM_XX
 * 
 * @see org.cesecore.certificates.util.core.model.AlgorithmConstants
 * @see org.bouncycastle.asn1.x9.X962NamedCurves
 * @see org.bouncycastle.asn1.nist.NISTNamedCurves
 * @see org.bouncycastle.asn1.sec.SECNamedCurves
 * 
 * @return KeyPair the generated keypair
 * @throws InvalidAlgorithmParameterException
 * @see org.cesecore.certificates.util.AlgorithmConstants#KEYALGORITHM_RSA
 */
public static KeyPair genKeys(final String keySpec, final AlgorithmParameterSpec algSpec, final String keyAlg)
        throws InvalidAlgorithmParameterException {
    if (log.isTraceEnabled()) {
        log.trace(">genKeys(" + keySpec + ", " + keyAlg + ")");
    }

    KeyPairGenerator keygen;
    try {
        keygen = KeyPairGenerator.getInstance(keyAlg, BouncyCastleProvider.PROVIDER_NAME);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("Algorithm " + keyAlg + "was not recognized.", e);
    } catch (NoSuchProviderException e) {
        throw new IllegalStateException("BouncyCastle was not found as a provider.", e);
    }
    if (StringUtils.equals(keyAlg, AlgorithmConstants.KEYALGORITHM_ECDSA)) {
        AlgorithmParameterSpec ecSpec = null;
        if ((keySpec != null) && !StringUtils.equals(keySpec, "implicitlyCA")) {
            log.debug("Generating named curve ECDSA key pair: " + keySpec);
            // We have EC keys
            ECGenParameterSpec bcSpec = new ECGenParameterSpec(keySpec);
            keygen.initialize(bcSpec, new SecureRandom());
            // The old code should work in BC v1.50b6 and later, but in vesions prior to that the below produces a key with explicit parameter encoding instead of named curves.
            // There is a test for this in KeyToolsTest.testGenKeysECDSAx9
            //                ecSpec = ECNamedCurveTable.getParameterSpec(keySpec);
            //                if (ecSpec == null) {
            //                    throw new InvalidAlgorithmParameterException("keySpec " + keySpec + " is invalid for ECDSA.");
            //                }
            //                keygen.initialize(ecSpec, new SecureRandom());
        } else if (algSpec != null) {
            log.debug("Generating ECDSA key pair from AlgorithmParameterSpec: " + algSpec);
            ecSpec = algSpec;
            keygen.initialize(ecSpec, new SecureRandom());
        } else if (StringUtils.equals(keySpec, "implicitlyCA")) {
            log.debug("Generating implicitlyCA encoded ECDSA key pair");
            // If the keySpec is null, we have "implicitlyCA" defined EC parameters
            // The parameters were already installed when we installed the provider
            // We just make sure that ecSpec == null here
            keygen.initialize(ecSpec, new SecureRandom());
        } else {
            throw new InvalidAlgorithmParameterException("No keySpec no algSpec and no implicitlyCA specified");
        }
    } else if (keyAlg.equals(AlgorithmConstants.KEYALGORITHM_ECGOST3410)) {
        AlgorithmParameterSpec ecSpec = null;
        if (keySpec != null) {
            log.debug("Generating keys from given key specifications : " + keySpec);
            ecSpec = ECGOST3410NamedCurveTable.getParameterSpec(keySpec);
            if (ecSpec == null)
                throw new InvalidAlgorithmParameterException(
                        "Key specification " + keySpec + " is invalid for ECGOST3410");
        } else if (algSpec != null) {
            log.debug("Generating keys from given algorithm parameters : " + algSpec);
            ecSpec = algSpec;
        } else {
            throw new InvalidAlgorithmParameterException("No key or algorithm specifications");
        }
        keygen.initialize(ecSpec, new SecureRandom());
    } else if (keyAlg.equals(AlgorithmConstants.KEYALGORITHM_DSTU4145)) {
        AlgorithmParameterSpec ecSpec = null;
        if (keySpec != null) {
            log.debug("Generating keys from given key specifications : " + keySpec);
            ecSpec = dstuOidToAlgoParams(keySpec);
            if (ecSpec == null)
                throw new InvalidAlgorithmParameterException(
                        "Key specification " + keySpec + " is invalid for DSTU4145");
        } else if (algSpec != null) {
            log.debug("Generating keys from given algorithm parameters : " + algSpec);
            ecSpec = algSpec;
        } else {
            throw new InvalidAlgorithmParameterException("No key or algorithm specifications");
        }
        keygen.initialize(ecSpec, new SecureRandom());
    } else if (keySpec.startsWith("DSA")) {
        // DSA key with "DSA" in keyspec
        final int keysize = Integer.parseInt(keySpec.substring(3));
        keygen.initialize(keysize);
    } else {
        // RSA or DSA key where keyspec is simply the key length
        final int keysize = Integer.parseInt(keySpec);
        keygen.initialize(keysize);
    }

    final KeyPair keys = keygen.generateKeyPair();

    if (log.isDebugEnabled()) {
        final PublicKey pk = keys.getPublic();
        final int len = getKeyLength(pk);
        log.debug("Generated " + keys.getPublic().getAlgorithm() + " keys with length " + len);
    }
    log.trace("<genKeys()");
    return keys;
}

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

/**
 * Generates a keypair/*  ww  w .  ja va  2s. c o  m*/
 *
 * @param keySpec string specification of keys to generate, typical value is 1024 for RSA or DSA keys, or prime192v1 for ECDSA keys or null of algspec is to be used.
 * @param algSpec AlgorithmParameterSpec of keys to generate, typically an EXParameterSpec for EC keys, or null if keySpec is to be used.
 * @param keyAlg algorithm of keys to generate, typical value is RSA, DSA or ECDSA, see AlgorithmConstants.KEYALGORITHM_XX
 * 
 * @see org.ejbca.core.model.AlgorithmConstants
 * @see org.bouncycastle.asn1.x9.X962NamedCurves
 * @see org.bouncycastle.asn1.nist.NISTNamedCurves
 * @see org.bouncycastle.asn1.sec.SECNamedCurves
 * 
 * @return KeyPair the generated keypair
 * @throws InvalidAlgorithmParameterException 
 * @see org.ejbca.core.model.AlgorithmConstants#KEYALGORITHM_RSA
 */
public static KeyPair genKeys(final String keySpec, final AlgorithmParameterSpec algSpec, final String keyAlg)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
    if (log.isTraceEnabled()) {
        log.trace(">genKeys(" + keySpec + ", " + keyAlg + ")");
    }

    final KeyPairGenerator keygen = KeyPairGenerator.getInstance(keyAlg, "BC");
    if (StringUtils.equals(keyAlg, AlgorithmConstants.KEYALGORITHM_ECDSA)) {
        AlgorithmParameterSpec ecSpec = null;
        if ((keySpec != null) && !StringUtils.equals(keySpec, "implicitlyCA")) {
            log.debug("Generating named curve ECDSA key pair: " + keySpec);
            // We have EC keys
            ecSpec = ECNamedCurveTable.getParameterSpec(keySpec);
            if (ecSpec == null) {
                throw new InvalidAlgorithmParameterException("keySpec " + keySpec + " is invalid for ECDSA.");
            }
        } else if (algSpec != null) {
            log.debug("Generating ECDSA key pair from AlgorithmParameterSpec: " + algSpec);
            ecSpec = algSpec;
        } else if (StringUtils.equals(keySpec, "implicitlyCA")) {
            log.debug("Generating implicitlyCA encoded ECDSA key pair");
            // If the keySpec is null, we have "implicitlyCA" defined EC parameters
            // The parameters were already installed when we installed the provider
            // We just make sure that ecSpec == null here
        } else {
            throw new InvalidAlgorithmParameterException("No keySpec no algSpec and no implicitlyCA specified");
        }
        keygen.initialize(ecSpec, new SecureRandom());
    } else {
        // RSA or DSA keys
        final int keysize = Integer.parseInt(keySpec);
        keygen.initialize(keysize);
    }

    final KeyPair keys = keygen.generateKeyPair();

    if (log.isDebugEnabled()) {
        final PublicKey pk = keys.getPublic();
        final int len = getKeyLength(pk);
        log.debug("Generated " + keys.getPublic().getAlgorithm() + " keys with length " + len);
    }
    log.trace("<genKeys()");
    return keys;
}