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:com.titilink.common.app.EncryptDecryptUtil.java

public void testRSA() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException, SignatureException {
    ///*  ww  w.jav  a 2 s  . co  m*/
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    //?
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    //??
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, privateKey, new SecureRandom());
    byte[] cipherData = cipher
            .doFinal("this is a security text from server".getBytes(Charset.forName("UTF-8")));

    //
    Cipher cipher1 = Cipher.getInstance("RSA");
    cipher1.init(Cipher.DECRYPT_MODE, publicKey, new SecureRandom());
    byte[] plainData = cipher1.doFinal(cipherData);
    System.out.println(new String(plainData, Charset.forName("UTF-8")));

    //???????
    Signature signature = Signature.getInstance("MD5withRSA");
    signature.initSign(privateKey);
    signature.update(cipherData);
    byte[] signData = signature.sign();

    //?????
    Signature signature1 = Signature.getInstance("MD5withRSA");
    signature1.initVerify(publicKey);
    signature1.update(cipherData);
    System.out.println(signature1.verify(signData));

}

From source file:com.streamsets.pipeline.lib.remote.SSHDUnitTest.java

protected KeyPair generateKeyPair() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048);/*from  ww  w  .j av a  2  s  .  co m*/
    return keyGen.generateKeyPair();
}

From source file:jenkins.security.RSAConfidentialKey.java

/**
 * Obtains the private key (lazily.)/*from   w  ww .  ja  v  a  2s  . co m*/
 * <p>
 * This method is not publicly exposed as per the design principle of {@link ConfidentialKey}.
 * Instead of exposing private key, define methods that use them in specific way, such as
 * {@link RSADigitalSignatureConfidentialKey}.
 *
 * @throws Error
 *      If key cannot be loaded for some reasons, we fail.
 */
protected synchronized RSAPrivateKey getPrivateKey() {
    try {
        if (priv == null) {
            byte[] payload = load();
            if (payload == null) {
                KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
                gen.initialize(2048, new SecureRandom()); // going beyond 2048 requires crypto extension
                KeyPair keys = gen.generateKeyPair();
                priv = (RSAPrivateKey) keys.getPrivate();
                pub = (RSAPublicKey) keys.getPublic();
                store(priv.getEncoded());
            } else {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                priv = (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(payload));

                RSAPrivateCrtKey pks = (RSAPrivateCrtKey) priv;
                pub = (RSAPublicKey) keyFactory
                        .generatePublic(new RSAPublicKeySpec(pks.getModulus(), pks.getPublicExponent()));
            }
        }
        return priv;
    } catch (IOException e) {
        throw new Error("Failed to load the key: " + getId(), e);
    } catch (GeneralSecurityException e) {
        throw new Error("Failed to load the key: " + getId(), e);
    }
}

From source file:com.streamsets.lib.security.util.DataSignature.java

public KeyPair generateKeyPair() throws GeneralSecurityException {
    KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("DSA");
    SecureRandom rng = SecureRandom.getInstance("SHA1PRNG", "SUN");
    rng.setSeed(System.currentTimeMillis());
    keyGenerator.initialize(1024, rng);//from w w  w  .jav a 2  s .  c  o m
    return keyGenerator.generateKeyPair();
}

From source file:de.rub.nds.burp.utilities.attacks.signatureFaking.helper.CertificateHandler.java

public void createFakedCertificate() throws CertificateHandlerException {
    try {/*from w  ww . j  ava  2  s.co  m*/
        Logging.getInstance().log(getClass(), "Faking the found certificate", Logging.DEBUG);

        KeyPairGenerator kpg = KeyPairGenerator.getInstance(originalPublicKey.getAlgorithm());
        kpg.initialize(((RSAPublicKey) certificate.getPublicKey()).getModulus().bitLength());
        fakedKeyPair = kpg.generateKeyPair();

        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
        v3CertGen.setSubjectDN(certificate.getSubjectX500Principal());
        v3CertGen.setIssuerDN(certificate.getIssuerX500Principal());
        v3CertGen.setNotAfter(certificate.getNotAfter());
        v3CertGen.setNotBefore(certificate.getNotBefore());
        v3CertGen.setSerialNumber(new BigInteger(64, new Random()));
        v3CertGen.setSignatureAlgorithm(certificate.getSigAlgName());
        v3CertGen.setPublicKey(fakedKeyPair.getPublic());

        fakedCertificate = v3CertGen.generate(fakedKeyPair.getPrivate());
    } catch (CertificateEncodingException | SecurityException | SignatureException | InvalidKeyException
            | NoSuchAlgorithmException e) {
        throw new CertificateHandlerException(e);
    }
}

From source file:org.candlepin.util.X509CRLEntryStreamTest.java

@Before
public void setUp() throws Exception {
    URL url = X509CRLEntryStreamTest.class.getClassLoader().getResource("crl.der");
    derFile = new File(url.getFile());

    url = X509CRLEntryStreamTest.class.getClassLoader().getResource("crl.pem");
    pemFile = new File(url.getFile());

    issuer = new X500Name("CN=Test Issuer");

    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");

    generator.initialize(2048);/* ww  w  . j  a  v  a 2s . co m*/
    keyPair = generator.generateKeyPair();

    signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC).build(keyPair.getPrivate());
}

From source file:mitm.common.security.ca.SMIMEKeyAndCertificateIssuer.java

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

    keyPairGenerator.initialize(parameters.getKeyLength(), randomSource);

    return keyPairGenerator.generateKeyPair();
}

From source file:org.gluu.com.ox_push2.u2f.v2.cert.KeyPairGeneratorImpl.java

@Override
public KeyPair generateKeyPair() throws U2FException {
    // generate ECC key
    SecureRandom random = new SecureRandom();

    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256r1");
    try {/*from w w w .  jav a2  s  .co m*/
        KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", bouncyCastleProvider);
        g.initialize(ecSpec, random);
        KeyPair keyPair = g.generateKeyPair();

        return keyPair;
    } catch (NoSuchAlgorithmException ex) {
        throw new U2FException("Failed to generate key pair", ex);
    } catch (InvalidAlgorithmParameterException ex) {
        throw new U2FException("Failed to generate key pair", ex);
    }
}

From source file:mitm.common.tools.CreateCA.java

private void generateRoot() throws Exception {
    X509CertificateBuilder certificateBuilder = securityFactory.createX509CertificateBuilder();

    KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA");

    keyPairGenerator.initialize(2048, randomSource);

    rootKeyPair = keyPairGenerator.generateKeyPair();

    X500PrincipalBuilder issuerBuilder = new X500PrincipalBuilder();

    String email = "martijn@mitm.nl";

    issuerBuilder.setCommonName("MITM Root");
    issuerBuilder.setCountryCode("NL");
    issuerBuilder.setEmail(email);/*  www  . j  a  v a2 s  .com*/
    issuerBuilder.setLocality("Amsterdam");
    issuerBuilder.setState("NH");

    AltNamesBuilder altNamesBuider = new AltNamesBuilder();

    altNamesBuider.setRFC822Names(email);

    X500Principal issuer = issuerBuilder.buildPrincipal();
    GeneralNames altNames = altNamesBuider.buildAltNames();

    Date now = new Date();

    certificateBuilder.setSubject(issuer);
    certificateBuilder.setIssuer(issuer);
    certificateBuilder.setAltNames(altNames, true);
    certificateBuilder.setNotBefore(now);
    certificateBuilder.setNotAfter(DateUtils.addYears(now, 20));
    certificateBuilder.setPublicKey(rootKeyPair.getPublic());
    certificateBuilder.setSerialNumber(serialNumberGenerator.generate());
    certificateBuilder.setSignatureAlgorithm("SHA1WithRSAEncryption");
    certificateBuilder.setIsCA(true, true);
    certificateBuilder.addSubjectKeyIdentifier(true);

    /*
     * generate self signed certificate
     */
    rootCertificate = certificateBuilder.generateCertificate(rootKeyPair.getPrivate(), null);
}

From source file:mitm.common.tools.CreateCA.java

private void generateIntermediate() throws Exception {
    X509CertificateBuilder certificateBuilder = securityFactory.createX509CertificateBuilder();

    KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA");

    keyPairGenerator.initialize(2048, randomSource);

    intermediateKeyPair = keyPairGenerator.generateKeyPair();

    X500PrincipalBuilder issuerBuilder = new X500PrincipalBuilder();

    String email = "martijn@mitm.nl";

    issuerBuilder.setCommonName("MITM Intermediate");
    issuerBuilder.setCountryCode("NL");
    issuerBuilder.setEmail(email);/*from w  ww  .  j av  a  2 s.  c  o  m*/
    issuerBuilder.setLocality("Amsterdam");
    issuerBuilder.setState("NH");

    AltNamesBuilder altNamesBuider = new AltNamesBuilder();

    altNamesBuider.setRFC822Names(email);

    X500Principal issuer = issuerBuilder.buildPrincipal();
    GeneralNames altNames = altNamesBuider.buildAltNames();

    Date now = new Date();

    certificateBuilder.setSubject(issuer);
    certificateBuilder.setIssuer(rootCertificate.getSubjectX500Principal());
    certificateBuilder.setAltNames(altNames, true);
    certificateBuilder.setNotBefore(now);
    certificateBuilder.setNotAfter(DateUtils.addYears(now, 20));
    certificateBuilder.setPublicKey(intermediateKeyPair.getPublic());
    certificateBuilder.setSerialNumber(serialNumberGenerator.generate());
    certificateBuilder.setSignatureAlgorithm("SHA1WithRSAEncryption");
    certificateBuilder.setIsCA(true, true);
    certificateBuilder.addSubjectKeyIdentifier(true);

    intermediateCertificate = certificateBuilder.generateCertificate(rootKeyPair.getPrivate(),
            intermediateCertificate);
}