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:test.unit.be.agiv.security.handler.WSSecurityHandlerTest.java

private KeyPair generateKeyPair(int keySize) throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = new SecureRandom();
    keyPairGenerator.initialize(new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F4), random);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    return keyPair;
}

From source file:org.asimba.wa.integrationtest.saml2.model.AuthnRequest.java

public String getSignedRequest(int format, InputStream keystoreStream, String keystorePassword, String keyAlias,
        String keyPassword) {//from w  w  w  . j av a 2 s . c o  m
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);

    DocumentBuilder builder;
    Document doc;
    try {
        builder = dbf.newDocumentBuilder();
        doc = builder.parse(new InputSource(new ByteArrayInputStream(getRequest(plain).getBytes("utf-8"))));

        // Prepare doc by marking attributes as referenceable:
        tagIdAttributes(doc);

        // Prepare cryptographic environemnt
        KeyStore keystore = getKeystore("JKS", keystoreStream, keystorePassword);
        if (keystore == null)
            return null;

        KeyPair kp;

        kp = getKeyPairFromKeystore(keystore, keyAlias, keyPassword);
        if (kp == null) {
            // Generate key, to prove that it works...
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
            kpg.initialize(512);
            kp = kpg.generateKeyPair();
        }

        // Set signing context with PrivateKey and root of the Document
        DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement());

        // Get SignatureFactory for creating signatures in DOM:
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

        // Create reference for "" -> root of the document
        // SAML requires enveloped transform
        Reference ref = fac.newReference("#" + this._id, fac.newDigestMethod(DigestMethod.SHA1, null),
                Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
                null, null);

        // Create SignedInfo (SAML2: Exclusive with or without comments is specified)
        SignedInfo si = fac.newSignedInfo(
                fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,
                        (C14NMethodParameterSpec) null),
                fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));

        // Add KeyInfo to the document:
        KeyInfoFactory kif = fac.getKeyInfoFactory();

        // .. get key from the generated keypair:
        KeyValue kv = kif.newKeyValue(kp.getPublic());
        KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));

        XMLSignature signature = fac.newXMLSignature(si, ki);

        String before = docToString(doc);

        // Sign!
        signature.sign(dsc);

        _authnRequestDocument = doc; // persist, as we've worked hard for it

        String after = docToString(doc);

        if (_logger.isDebugEnabled()) {
            _logger.debug("Before: {}", before);
            _logger.debug("After : {}", after);
        }

        return after;

    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (XMLStreamException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // key generation exception
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        // digest algorithm selection exception
        e.printStackTrace();
    } catch (KeyException e) {
        // when key-value was not available (when adding to KeyInfo)
        e.printStackTrace();
    } catch (MarshalException e) {
        // sign didn't work:
        e.printStackTrace();
    } catch (XMLSignatureException e) {
        // sign didn't work:
        e.printStackTrace();
    }
    return null;
}

From source file:nl.afas.cordova.plugin.secureLocalStorage.SecureLocalStorage.java

@TargetApi(18)
private KeyStore initKeyStore() throws SecureLocalStorageException {
    try {//ww  w  . ja v a 2  s  .co  m
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);

        if (!keyStore.containsAlias(SECURELOCALSTORAGEALIAS)) {

            Calendar start = Calendar.getInstance();
            Calendar end = Calendar.getInstance();
            end.add(Calendar.YEAR, 3);

            KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(_cordova.getActivity())
                    .setAlias(SECURELOCALSTORAGEALIAS)
                    .setSubject(new X500Principal(String.format("CN=%s, O=%s", "SecureLocalStorage",
                            _cordova.getActivity().getBaseContext().getPackageName())))
                    .setSerialNumber(BigInteger.ONE).setStartDate(start.getTime()).setEndDate(end.getTime())
                    .build();
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
            generator.initialize(spec);

            generator.generateKeyPair();
        }

        return keyStore;
    } catch (Exception e) {
        throw new SecureLocalStorageException("Could not initialize keyStore", e);
    }
}

From source file:mitm.common.security.ca.handlers.comodo.ComodoCertificateRequestHandler.java

private synchronized KeyPair generateKeyPair(int keyLength)
        throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA");

    keyPairGenerator.initialize(keyLength, randomSource);

    return keyPairGenerator.generateKeyPair();
}

From source file:netinf.common.security.identity.impl.IdentityManagerImpl.java

/**
 * @see IdentityManager#createNewMasterIdentity()
 *///from w  ww  .  j a v a2s.  c  o m
@Override
public IdentityObject createNewMasterIdentity() throws NetInfCheckedException {
    // as soon as a new Master Identity is created, all Identites known to this IdentityManager will be stored to file. Thus,
    // ensure that identities are loaded from file before
    if (this.privateKeys.size() == 0) {
        try {
            loadIdentities();
        } catch (NetInfCheckedException e) {
            LOG.warn("Unable to load key file. " + e.getMessage());
        }
    }

    KeyPairGenerator k;
    try {
        k = KeyPairGenerator.getInstance("RSA");

    } catch (Exception e) {
        LOG.warn(e.getMessage());
        return null;
    }

    k.initialize(1024);
    KeyPair pair = k.generateKeyPair();

    // A new Master Identity implies a new Identity Object. Create it
    IdentityObject newIdentity = ValidCreator.createValidIdentityObject(pair.getPublic());

    // Derive the "Identity-Path"
    String pathToKey = newIdentity.getIdentifier().toString() + IntegrityImpl.PATH_SEPERATOR
            + DefinedAttributeIdentification.PUBLIC_KEY.getURI();

    this.privateKeys.put(pathToKey, pair.getPrivate());

    LOG.info("Private Key: " + Utils.objectToString(pair.getPrivate()));
    LOG.info("Public Key: " + Utils.objectToString(pair.getPublic()));

    // save private keys to file
    writePrivateKeysToFile(this.defaultFilepath, this.defaultKeyAlgorithmName, this.defaultPassword);

    return newIdentity;
}

From source file:org.kuali.rice.ksb.security.admin.service.impl.JavaSecurityManagementServiceImpl.java

public KeyStore generateClientKeystore(String alias, String clientPassphrase) throws GeneralSecurityException {
    if (isAliasInKeystore(alias)) {
        throw new KeyStoreException("Alias '" + alias + "' already exists in module keystore");
    }// w ww .  j a va  2s .  c  om
    //        Certificate[] clientCertificateChain = {};
    //        PrivateKey clientPrivateKey = null;
    KeyStore ks = null;
    try {
        // generate a key pair for the client
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(CLIENT_KEY_GENERATOR_ALGORITHM);
        //            SecureRandom random = SecureRandom.getInstance(CLIENT_SECURE_RANDOM_ALGORITHM);
        keyGen.initialize(CLIENT_KEY_PAIR_KEY_SIZE);
        //            keyGen.initialize(new RSAKeyGenParameterSpec(512,RSAKeyGenParameterSpec.F0));
        KeyPair pair = keyGen.generateKeyPair();

        //            PublicKey clientPublicKey = pair.getPublic();
        //            clientPrivateKey = pair.getPrivate();
        //            // generate the Certificate
        //            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
        ////            X509Name nameInfo = new X509Name(false,"CN=" + alias);
        //            certificateGenerator.setSignatureAlgorithm("MD5WithRSA");
        //            certificateGenerator.setSerialNumber(new java.math.BigInteger("1"));
        //            X509Principal nameInfo = new X509Principal("CN=" + alias);
        //            certificateGenerator.setIssuerDN(nameInfo);
        //            certificateGenerator.setSubjectDN(nameInfo);                       // note: same as issuer
        //            certificateGenerator.setNotBefore(new Date());
        //            Calendar c = Calendar.getInstance();
        //            c.add(Calendar.DATE, CLIENT_CERT_EXPIRATION_DAYS);
        //            certificateGenerator.setNotAfter(c.getTime());
        //            certificateGenerator.setPublicKey(clientPublicKey);
        //            X509Certificate cert = certificateGenerator.generateX509Certificate(clientPrivateKey);
        //            clientCertificateChain = new Certificate[]{cert};
        //
        //            // generate client keyStore file
        //            ks = KeyStore.getInstance(getModuleKeyStoreType());
        //            ks.load(null, clientPassphrase.toCharArray());
        //            // set client private key on keyStore file
        //            ks.setEntry(alias, new KeyStore.PrivateKeyEntry(clientPrivateKey, clientCertificateChain), new KeyStore.PasswordProtection(clientPassphrase.toCharArray()));
        Certificate cert = generateCertificate(pair, alias);
        ks = generateKeyStore(cert, pair.getPrivate(), alias, clientPassphrase);

        // set the module certificate on the client keyStore file
        ks.setEntry(getModuleKeyStoreAlias(),
                new KeyStore.TrustedCertificateEntry(getCertificate(getModuleKeyStoreAlias())), null);

        // add the client certificate to the module keyStore
        addClientCertificateToModuleKeyStore(alias, cert);

        return ks;
    } catch (IOException e) {
        throw new RuntimeException("Could not create new KeyStore", e);
    }
}

From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java

public KeyPair generateKeyPair() throws CryptoException {
    try {//ww w .  ja v  a 2 s.  c om
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(this.keySize);

        KeyPair keyPair = keyGen.generateKeyPair();
        return keyPair;
    } catch (NoSuchAlgorithmException e) {
        this.logger.error("NoSuchAlgorithmException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    }
}

From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java

private X509Certificate createSelfSignedCertificate(KeyStore keyStore, String dn, String alias) {
    try {//from w w  w  .j a va  2 s .  c  o  m
        // create new key pair for the node
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(keySize, new SecureRandom());
        KeyPair keypair = keyGen.generateKeyPair();
        PublicKey publicKey = keypair.getPublic();
        PrivateKey privateKey = keypair.getPrivate();

        Certificate cert = certificateService.generateCertificate(dn, publicKey, privateKey);
        keyStore.setKeyEntry(alias, privateKey, getKeyStorePassword().toCharArray(),
                new Certificate[] { cert });
        saveKeyStore(keyStore);
        return (X509Certificate) cert;
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateException("Error setting up node key pair", e);
    } catch (KeyStoreException e) {
        throw new CertificateException("Error setting up node key pair", e);
    }
}

From source file:com.cellngine.crypto.RSACipher.java

@Override
public void generateKeypair(final int keyLength) {
    if (keyLength <= 0) {
        throw new IllegalArgumentException("Key length must be positive and nonzero");
    }/*from w w  w. j a v a2 s.  com*/

    final KeyPairGenerator generator;
    try {
        generator = KeyPairGenerator.getInstance(ALGORITHM);
    } catch (final NoSuchAlgorithmException e) {
        LOG.error("Unable to get key generator instance (" + ALGORITHM + ")", e);
        return;
    }

    try {
        generator.initialize(keyLength, this.random);
    } catch (final InvalidParameterException e) {
        throw new IllegalArgumentException("Unsupported key length");
    }

    final KeyPair pair = generator.generateKeyPair();
    this.publicKey = pair.getPublic();
    this.privateKey = pair.getPrivate();
}

From source file:com.eucalyptus.crypto.DefaultCryptoProvider.java

/**
 * @see com.eucalyptus.crypto.CertificateProvider#generateKeyPair()
 *//*  ww w. ja v a  2s  .com*/
@Override
public KeyPair generateKeyPair() {
    KeyPairGenerator keyGen = null;
    try {
        EventRecord.caller(DefaultCryptoProvider.class, EventType.GENERATE_KEYPAIR);
        keyGen = KeyPairGenerator.getInstance(KEY_ALGORITHM, PROVIDER);
        SecureRandom random = Crypto.getSecureRandomSupplier().get();
        //TODO: RELEASE: see line:110
        keyGen.initialize(KEY_SIZE, random);
        KeyPair keyPair = keyGen.generateKeyPair();
        return keyPair;
    } catch (Exception e) {
        LOG.fatal(e, e);
        return null;
    }
}