Example usage for java.security KeyPair getPrivate

List of usage examples for java.security KeyPair getPrivate

Introduction

In this page you can find the example usage for java.security KeyPair getPrivate.

Prototype

public PrivateKey getPrivate() 

Source Link

Document

Returns a reference to the private key component of this key pair.

Usage

From source file:org.computerist.ssltools.zap.ZapSslCertificateUtils.java

/**
 * Creates a new Root CA certificate and returns private and public key as
 * {@link KeyStore}. The {@link KeyStore#getDefaultType()} is used.
 *
 * @return//from  w  w  w. j a  va  2s  .co m
 * @throws NoSuchAlgorithmException If no providers are found
 * for 'RSA' key pair generator
 * or 'SHA1PRNG' Secure random number generator
 * @throws IllegalStateException in case of errors during assembling {@link KeyStore}
 */
public static final KeyStore createRootCA() throws NoSuchAlgorithmException {
    final Date startDate = Calendar.getInstance().getTime();
    final Date expireDate = new Date(startDate.getTime() + (DEFAULT_VALID_DAYS * 24L * 60L * 60L * 1000L));

    final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA");
    g.initialize(2048, SecureRandom.getInstance("SHA1PRNG"));
    final KeyPair keypair = g.genKeyPair();
    final PrivateKey privKey = keypair.getPrivate();
    final PublicKey pubKey = keypair.getPublic();
    Random rnd = new Random();

    // using the hash code of the user's name and home path, keeps anonymity
    // but also gives user a chance to distinguish between each other
    X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
    namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA");
    namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode())
            + Integer.toHexString(System.getProperty("user.home").hashCode()));
    namebld.addRDN(BCStyle.O, "OWASP Root CA");
    namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA");
    namebld.addRDN(BCStyle.C, "xx");

    X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(),
            BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey);

    KeyStore ks = null;
    try {
        certGen.addExtension(X509Extension.subjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(pubKey));
        certGen.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(true));
        certGen.addExtension(X509Extension.keyUsage, false,
                new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
                        | KeyUsage.dataEncipherment | KeyUsage.cRLSign));

        Vector<DERObject> eku = new Vector<>(3, 1);
        eku.add(KeyPurposeId.id_kp_serverAuth);
        eku.add(KeyPurposeId.id_kp_clientAuth);
        eku.add(KeyPurposeId.anyExtendedKeyUsage);
        certGen.addExtension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku));

        final ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC")
                .build(privKey);
        final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(certGen.build(sigGen));

        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        ks.setKeyEntry(FixedSslCertificateService.ZAPROXY_JKS_ALIAS, privKey,
                FixedSslCertificateService.PASSPHRASE, new Certificate[] { cert });
    } catch (final Exception e) {
        throw new IllegalStateException("Errors during assembling root CA.", e);
    }
    return ks;
}

From source file:org.excalibur.core.util.SecurityUtils2.java

public static UserKey generateUserKey() throws Exception {
    KeyPairGenerator kpg = SecurityUtils.getKeyPairGenerator("RSA");

    kpg.initialize(1024, new SecureRandom());
    java.security.KeyPair kp = kpg.generateKeyPair();

    String priv = getKeyMaterial(kp.getPrivate());

    byte[] encoded = encode((RSAPublicKey) kp.getPublic());

    //        String pub = getKeyMaterial(kp.getPublic()).replaceAll(PUBLIC_KEY_START, "").replaceAll(PUBLIC_KEY_END, "").trim();

    return new UserKey().setPrivateKeyMaterial(priv).setPublicKeyMaterial(new String(Base64.encode(encoded)))
            .setFingerPrint(getFingerPrint((RSAPublicKey) kp.getPublic()));
}

From source file:net.arccotangent.pacchat.filesystem.KeyManager.java

private static void generateNewKeys() {
    km_log.i("Generating new keys.");
    KeyPair keyPair = RSA.generateRSAKeypair(4096);

    assert keyPair != null;
    PrivateKey privkey = keyPair.getPrivate();
    PublicKey pubkey = keyPair.getPublic();

    saveKeys(privkey, pubkey);/* ww w. j ava  2s .com*/
}

From source file:com.vmware.identity.sts.auth.impl.UserCertAuthenticatorTest.java

@BeforeClass
public static void setUp() throws Exception {
    // create key pair and client private key, certificate
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(1024, new SecureRandom());
    KeyPair userKeyPair = keyGen.generateKeyPair();
    userPrivateKey = (RSAPrivateKey) userKeyPair.getPrivate();
    x509Certificate = generateCertificate(userKeyPair, "User");
}

From source file:nu.yona.server.messaging.entities.MessageSource.java

public static MessageSource createInstance() {
    KeyPair pair = PublicKeyUtil.generateKeyPair();

    MessageDestination messageDestination = MessageDestination.createInstance(pair.getPublic());
    return new MessageSource(UUID.randomUUID(), pair.getPrivate(), messageDestination);
}

From source file:net.link.util.test.pkix.PkiTestUtils.java

public static KeyStore.PrivateKeyEntry generateKeyEntry(String dn) throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, IOException, CertificateException, OperatorCreationException {

    KeyPair keyPair = generateKeyPair();
    return new KeyStore.PrivateKeyEntry(keyPair.getPrivate(),
            new Certificate[] { generateSelfSignedCertificate(keyPair, dn) });
}

From source file:de.pawlidi.openaletheia.utils.CipherUtils.java

/**
 * /*from w w w. j  a  v  a  2  s  .c  o m*/
 * @param keyPair
 * @return
 */
public static String getPrivateKey(KeyPair keyPair) {
    if (keyPair != null && keyPair.getPrivate() != null) {
        return Converter.toString(keyPair.getPrivate().getEncoded());
    }
    return null;
}

From source file:com.vmware.identity.sts.auth.impl.UserCertAuthenticatorTest.java

private static X509Certificate generateCertificate(KeyPair keyPair, String dn) throws Exception {
    ContentSigner sigGen = new JcaContentSignerBuilder("SHA1withRSA").build(keyPair.getPrivate());

    Date startDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
    Date endDate = new Date(System.currentTimeMillis() + 365 * 24 * 60 * 60 * 1000);

    X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(new X500Name("CN=" + dn),
            new BigInteger(64, new SecureRandom()), startDate, endDate, new X500Name("CN=" + dn),
            keyPair.getPublic());//from   www .j  ava 2 s . c  o  m
    v3CertGen.addExtension(Extension.subjectAlternativeName, true,
            new GeneralNames(new GeneralName(GeneralName.otherName,
                    new DERSequence(new ASN1Encodable[] { new DERObjectIdentifier("1.3.6.1.4.1.311.20.2.3"),
                            new DERTaggedObject(true, 0, new DERUTF8String(upn)) }))));

    X509CertificateHolder certHolder = v3CertGen.build(sigGen);
    X509Certificate x509Certificate = new JcaX509CertificateConverter().getCertificate(certHolder);
    return x509Certificate;
}

From source file:cloudeventbus.cli.Certs.java

private static void createCertificate(TrustStore trustStore, Certificate.Type type,
        AbstractCreateClientServerCommand createCommand) throws Exception {
    final Certificate issuerCertificate = trustStore.get(createCommand.issuer);
    if (issuerCertificate == null) {
        throw new IllegalArgumentException(
                "No certificate found in trust store with serial number " + createCommand.issuer);
    }//from   w w w  . j  a v  a 2s  .co  m
    final PrivateKey issuerPrivateKey = CertificateUtils.loadPrivateKey(createCommand.issuerPrivateKey);
    final KeyPair keyPair = CertificateUtils.generateKeyPair();
    CertificateUtils.savePrivateKey(keyPair.getPrivate(), createCommand.privateKey);
    final Certificate certificate = CertificateUtils.generateSignedCertificate(issuerCertificate,
            issuerPrivateKey, keyPair.getPublic(), type, getExpirationDate(createCommand.expirationDate),
            Subject.list(createCommand.subscribePermissions), Subject.list(createCommand.publishPermissions),
            createCommand.comment);
    final CertificateChain chain = new CertificateChain(certificate);
    CertificateUtils.saveCertificates(createCommand.certificate, chain);
}

From source file:com.example.license.RSAUtil.java

/**
 * ?//  w w w.  java 2  s  .c o  m
 * 
 * @param data
 *            ?
 * @param key
 *            
 * @return ??
 */
public static String encrypt(String data, String seed) throws Exception {
    KeyPair keyPair = generatorKeyPair(seed);
    // Cipher??
    Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
    // SecureRandom random = new SecureRandom();
    // ?Cipher?
    cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate());
    byte[] results = cipher.doFinal(data.getBytes());
    // http://tripledes.online-domain-tools.com/??
    for (int i = 0; i < results.length; i++) {
        System.out.print(results[i] + " ");
    }
    System.out.println();
    // ??Base64?
    return Base64.encodeBase64String(results);
}