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:org.candlepin.CRLWriteBenchmark.java

@Setup(Level.Trial)
public void buildMassiveCRL() throws Exception {
    issuer = new X500Name("CN=Test Issuer");

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

    generator.initialize(2048);/*  w w  w . jav a 2s . c o m*/
    KeyPair keyPair = generator.generateKeyPair();

    bc = new BouncyCastleProvider();
    signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(bc).build(keyPair.getPrivate());

    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, new Date());
    crlBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(keyPair.getPublic()));
    /* With a CRL number of 127, incrementing it should cause the number of bytes in the length
     * portion of the TLV to increase by one.*/
    crlBuilder.addExtension(X509Extension.cRLNumber, false, new CRLNumber(new BigInteger("127")));

    for (int i = 0; i < 2000000; i++) {
        crlBuilder.addCRLEntry(new BigInteger(String.valueOf(i)), new Date(), CRLReason.unspecified);
    }

    X509CRLHolder holder = crlBuilder.build(signer);
    X509CRL crl = new JcaX509CRLConverter().setProvider(bc).getCRL(holder);

    crlFile = File.createTempFile("crl", ".der");
    System.out.println("\nWrote test crl to " + crlFile.getAbsolutePath());
    FileUtils.writeByteArrayToFile(crlFile, crl.getEncoded());
}

From source file:org.apache.abdera2.common.security.DHBase.java

private void init(BigInteger p, BigInteger g, int l, byte[] key)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeySpecException {
    DHParameterSpec spec = new DHParameterSpec(p, g, l);
    KeyPairGenerator keypairgen = KeyPairGenerator.getInstance("DH");
    keypairgen.initialize(spec);//  www .j a v a2s.c o m
    keyPair = keypairgen.generateKeyPair();
    publicKey = decode(key);
}

From source file:org.xdi.oxauth.model.crypto.signature.ECDSAKeyFactory.java

public ECDSAKeyFactory(SignatureAlgorithm signatureAlgorithm, String dnName) throws InvalidParameterException,
        NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        SignatureException, InvalidKeyException, CertificateEncodingException {
    if (signatureAlgorithm == null) {
        throw new InvalidParameterException("The signature algorithm cannot be null");
    }// w w w  .ja va  2s  .c o  m

    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(signatureAlgorithm.getCurve());

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDSA", "BC");
    keyGen.initialize(ecSpec, new SecureRandom());

    KeyPair keyPair = keyGen.generateKeyPair();
    JCEECPrivateKey privateKeySpec = (JCEECPrivateKey) keyPair.getPrivate();
    JCEECPublicKey publicKeySpec = (JCEECPublicKey) keyPair.getPublic();

    BigInteger x = publicKeySpec.getQ().getX().toBigInteger();
    BigInteger y = publicKeySpec.getQ().getY().toBigInteger();
    BigInteger d = privateKeySpec.getD();

    ecdsaPrivateKey = new ECDSAPrivateKey(d);
    ecdsaPublicKey = new ECDSAPublicKey(signatureAlgorithm, x, y);

    if (StringUtils.isNotBlank(dnName)) {
        // Create certificate
        GregorianCalendar startDate = new GregorianCalendar(); // time from which certificate is valid
        GregorianCalendar expiryDate = new GregorianCalendar(); // time after which certificate is not valid
        expiryDate.add(Calendar.YEAR, 1);
        BigInteger serialNumber = new BigInteger(1024, new Random()); // serial number for certificate

        X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
        X500Principal principal = new X500Principal(dnName);

        certGen.setSerialNumber(serialNumber);
        certGen.setIssuerDN(principal);
        certGen.setNotBefore(startDate.getTime());
        certGen.setNotAfter(expiryDate.getTime());
        certGen.setSubjectDN(principal); // note: same as issuer
        certGen.setPublicKey(keyPair.getPublic());
        certGen.setSignatureAlgorithm("SHA256WITHECDSA");

        X509Certificate x509Certificate = certGen.generate(privateKeySpec, "BC");
        certificate = new Certificate(signatureAlgorithm, x509Certificate);
    }
}

From source file:org.xdi.oxauth.model.crypto.signature.RSAKeyFactory.java

public RSAKeyFactory(SignatureAlgorithm signatureAlgorithm, String dnName)
        throws InvalidParameterException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException,
        InvalidKeyException, CertificateEncodingException {
    if (signatureAlgorithm == null) {
        throw new InvalidParameterException("The signature algorithm cannot be null");
    }//from   w ww.  j  ava  2 s. c  om

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
    keyGen.initialize(2048, new SecureRandom());

    KeyPair keyPair = keyGen.generateKeyPair();

    JCERSAPrivateCrtKey jcersaPrivateCrtKey = (JCERSAPrivateCrtKey) keyPair.getPrivate();
    JCERSAPublicKey jcersaPublicKey = (JCERSAPublicKey) keyPair.getPublic();

    rsaPrivateKey = new RSAPrivateKey(jcersaPrivateCrtKey.getModulus(),
            jcersaPrivateCrtKey.getPrivateExponent());

    rsaPublicKey = new RSAPublicKey(jcersaPublicKey.getModulus(), jcersaPublicKey.getPublicExponent());

    if (StringUtils.isNotBlank(dnName)) {
        // Create certificate
        GregorianCalendar startDate = new GregorianCalendar(); // time from which certificate is valid
        GregorianCalendar expiryDate = new GregorianCalendar(); // time after which certificate is not valid
        expiryDate.add(Calendar.YEAR, 1);
        BigInteger serialNumber = new BigInteger(1024, new Random()); // serial number for certificate

        X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
        X500Principal principal = new X500Principal(dnName);

        certGen.setSerialNumber(serialNumber);
        certGen.setIssuerDN(principal);
        certGen.setNotBefore(startDate.getTime());
        certGen.setNotAfter(expiryDate.getTime());
        certGen.setSubjectDN(principal); // note: same as issuer
        certGen.setPublicKey(keyPair.getPublic());
        certGen.setSignatureAlgorithm(signatureAlgorithm.getAlgorithm());

        X509Certificate x509Certificate = certGen.generate(jcersaPrivateCrtKey, "BC");
        certificate = new Certificate(signatureAlgorithm, x509Certificate);
    }
}

From source file:com.buzzcoders.security.cryptoutils.asymmetric.AbstractAsymmetricEncryptionModule.java

public KeyPair generateKeyPair(int keyLength) {
    KeyPair kp = null;/*from  ww w.j a  va  2 s.  c o  m*/
    try {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(getAlgorithm());
        kpg.initialize(keyLength);
        kp = kpg.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        LOG.error("Error generating the key pair.", e);
    }
    return kp;
}

From source file:org.apache.abdera2.common.security.DHBase.java

private void init() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        InvalidParameterSpecException, InvalidKeySpecException {
    AlgorithmParameterGenerator pgen = AlgorithmParameterGenerator.getInstance("DH");
    pgen.init(512);/*w w w . j  a  v a  2  s . c  o m*/
    AlgorithmParameters params = pgen.generateParameters();
    DHParameterSpec dhspec = (DHParameterSpec) params.getParameterSpec(DHParameterSpec.class);
    KeyPairGenerator keypairgen = KeyPairGenerator.getInstance("DH");
    keypairgen.initialize(dhspec);
    keyPair = keypairgen.generateKeyPair();
    p = dhspec.getP();
    g = dhspec.getG();
    l = dhspec.getL();
}

From source file:org.apache.sshd.common.config.keys.loader.pem.PKCS8PEMResourceKeyPairParserTest.java

@Test // see SSHD-760
public void testPkcs8() throws IOException, GeneralSecurityException {
    KeyPairGenerator generator = SecurityUtils.getKeyPairGenerator(algorithm);
    if (keySize > 0) {
        generator.initialize(keySize);//from w w w. j a v a 2 s  . c om
    }
    KeyPair kp = generator.generateKeyPair();

    try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
        Collection<Object> items = new ArrayList<>();
        PrivateKey prv1 = kp.getPrivate();
        items.add(new PEMItem(prv1.getEncoded(), "PRIVATE KEY"));
        byte[] bytes = PEMUtil.encode(items);
        os.write(bytes);
        os.close();

        try (ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) {
            KeyPair kp2 = SecurityUtils.loadKeyPairIdentity(getCurrentTestName(), bais, null);

            assertEquals("Mismatched public key", kp.getPublic(), kp2.getPublic());
            assertEquals("Mismatched private key", prv1, kp2.getPrivate());
        }
    }
}

From source file:jef.tools.security.EncrypterUtil.java

/**
 * ?KEY/*from w w  w .  j  a v  a2 s . co  m*/
 * 
 * @param algom
 *            ? DSA RSA
 * @return
 */
public static final KeyPair generateKeyPair(String algom) {
    try {
        java.security.KeyPairGenerator keygen = java.security.KeyPairGenerator.getInstance(algom);
        SecureRandom secrand = new SecureRandom();
        secrand.setSeed("\n".getBytes()); // ??
        //  512  1024  64 ?
        keygen.initialize(1024, secrand); // ??
        // keygen.initialize(512);
        KeyPair keys = keygen.generateKeyPair(); // ?
        return keys;
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:SecureConnection.java

private byte[] getPublicKeyStep2(DHParameterSpec dhParamSpec) throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DH");
    keyPairGen.initialize(dhParamSpec);//from  ww  w.  j  a  v  a 2  s  . c om
    KeyPair keyPair = keyPairGen.generateKeyPair();
    this.keyAgree = KeyAgreement.getInstance("DH");
    this.keyAgree.init(keyPair.getPrivate());
    return keyPair.getPublic().getEncoded();
}

From source file:org.metaeffekt.dcc.agent.AuthenticationKeyGenerator.java

private KeyPair generateKey() throws NoSuchAlgorithmException {
    final KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    keyGenerator.initialize(DEFAULT_KEY_SIZE);

    return keyGenerator.generateKeyPair();
}