Example usage for java.security KeyPair getPublic

List of usage examples for java.security KeyPair getPublic

Introduction

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

Prototype

public PublicKey getPublic() 

Source Link

Document

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

Usage

From source file:info.magnolia.cms.security.SecurityUtil.java

public static MgnlKeyPair generateKeyPair(int keyLength) throws NoSuchAlgorithmException {
    KeyPairGenerator kgen = KeyPairGenerator.getInstance(ALGORITHM);
    kgen.initialize(keyLength);/*w  w  w  .  j a  va  2s.  c  om*/
    KeyPair key = kgen.genKeyPair();
    return new MgnlKeyPair(byteArrayToHex(key.getPrivate().getEncoded()),
            byteArrayToHex(key.getPublic().getEncoded()));
}

From source file:org.mitre.jwt.signer.service.impl.KeyStoreTest.java

/**
 * Create an RSA KeyPair and insert into specified KeyStore
 * /*w ww . ja  v  a2 s  . com*/
 * @param location
 * @param domainName
 * @param alias
 * @param keystorePassword
 * @param aliasPassword
 * @param daysNotValidBefore
 * @param daysNotValidAfter
 * @return
 * @throws GeneralSecurityException
 * @throws IOException
 */
public static java.security.KeyStore generateKeyPair(KeyStore keystore, String keyPairAlgorithm, int keySize,
        String signatureAlgorithm, String domainName, String alias, String aliasPassword,
        int daysNotValidBefore, int daysNotValidAfter) throws GeneralSecurityException, IOException {

    java.security.KeyStore ks;

    if (keystore != null) {
        ks = keystore.getKeystore();
    } else {
        ks = java.security.KeyStore.getInstance(java.security.KeyStore.getDefaultType());
        ks.load(null, null);
    }

    KeyPairGenerator rsaKeyPairGenerator = null;

    rsaKeyPairGenerator = KeyPairGenerator.getInstance(keyPairAlgorithm);

    rsaKeyPairGenerator.initialize(keySize);
    KeyPair rsaKeyPair = rsaKeyPairGenerator.generateKeyPair();

    // BC sez X509V3CertificateGenerator is deprecated and the docs say to
    // use another, but it seemingly isn't included jar...
    X509V3CertificateGenerator v3CertGen = createCertificate(domainName, daysNotValidBefore, daysNotValidAfter);

    PrivateKey privateKey = rsaKeyPair.getPrivate();

    v3CertGen.setPublicKey(rsaKeyPair.getPublic());
    v3CertGen.setSignatureAlgorithm(signatureAlgorithm);

    // BC docs say to use another, but it seemingly isn't included...
    X509Certificate certificate = v3CertGen.generateX509Certificate(privateKey);

    // if exist, overwrite
    ks.setKeyEntry(alias, privateKey, aliasPassword.toCharArray(),
            new java.security.cert.Certificate[] { certificate });

    if (keystore != null) {
        keystore.setKeystore(ks);
    }

    return ks;
}

From source file:im.whistle.crypt.Crypt.java

/**
 * Generates a private/public key pair.//from w  ww  .  ja v a 2  s .c o m
 * @param args Arguments, element at 0 is the key size
 * @param callback Callback
 */
public static void genkeys(JSONArray args, AsyncCallback<JSONArray> callback) {
    try {
        Log.i("whistle", "Generating key pair ...");
        PRNGProvider.init(); // Ensure OpenSSL fix
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        int bits = args.getInt(0);
        int exp = args.getInt(1);
        keyPairGenerator.initialize(new RSAKeyGenParameterSpec(bits, BigInteger.valueOf(exp)));
        KeyPair keyPair = keyPairGenerator.genKeyPair();
        String priv = "-----BEGIN RSA PRIVATE KEY-----\n"
                + Base64.encodeToString(keyPair.getPrivate().getEncoded(), Base64.DEFAULT).trim()
                + "\n-----END RSA PRIVATE KEY-----";
        String pub = "-----BEGIN PUBLIC KEY-----\n"
                + Base64.encodeToString(keyPair.getPublic().getEncoded(), Base64.DEFAULT).trim()
                + "\n-----END PUBLIC KEY-----";
        JSONArray res = new JSONArray();
        res.put(priv);
        res.put(pub);
        callback.success(res);
    } catch (Exception ex) {
        Log.w("whistle", "Key pair generation failed: " + ex.getMessage());
        callback.error(ex);
    }
}

From source file:net.link.util.common.KeyUtils.java

public static X509Certificate generateSelfSignedCertificate(KeyPair keyPair, String dn, DateTime notBefore,
        DateTime notAfter, @Nullable String signatureAlgorithm, boolean caCert, boolean timeStampingPurpose) {

    return generateCertificate(keyPair.getPublic(), dn, keyPair.getPrivate(), null, notBefore, notAfter,
            signatureAlgorithm, caCert, timeStampingPurpose, null);
}

From source file:MainClass.java

public static X509Certificate generateV1Certificate(KeyPair pair)
        throws InvalidKeyException, NoSuchProviderException, SignatureException {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X500Principal("CN=Test Certificate"));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 10000));
    certGen.setSubjectDN(new X500Principal("CN=Test Certificate"));
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    return certGen.generateX509Certificate(pair.getPrivate(), "BC");
}

From source file:MainClass.java

public static X509Certificate generateV3Certificate(KeyPair pair)
        throws InvalidKeyException, NoSuchProviderException, SignatureException {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X500Principal("CN=Test Certificate"));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 10000));
    certGen.setSubjectDN(new X500Principal("CN=Test Certificate"));
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    certGen.addExtension(X509Extensions.SubjectAlternativeName, false,
            new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test")));

    return certGen.generateX509Certificate(pair.getPrivate(), "BC");
}

From source file:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java

/**
 * Creates a new self-signed X509 certificate
 *
 * @param pair the public/private keypair- the pubkey will be added to the cert and the private
 * key will be used to sign the certificate
 * @param subject the distinguished name of the subject
 * @param isAuthority true to make the cert a CA cert, false otherwise
 * @return//from   w  w w  .  j a  v a  2  s. c  o m
 */
public static X509Certificate newSelfSignedCertificate(KeyPair pair, X500Name subject, boolean isAuthority) {
    X509v3CertificateBuilder b = new JcaX509v3CertificateBuilder(subject,
            BigInteger.probablePrime(128, new SecureRandom()), Date.from(Instant.now().minusSeconds(1)),
            Date.from(LocalDateTime.now().plusYears(3).toInstant(ZoneOffset.UTC)), subject, pair.getPublic());
    try {
        b.addExtension(Extension.basicConstraints, true, new BasicConstraints(isAuthority));
    } catch (CertIOException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        X509CertificateHolder bcCert = b.build(
                new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider("BC").build(pair.getPrivate()));
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(bcCert);
    } catch (CertificateException | OperatorCreationException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:net.padlocksoftware.padlock.KeyManager.java

/**
 * Export the supplied Keypair to an output Stream.
 *
 * @param pair The KeyPair to export.  KeyPairs should only be pairs
 * created with the createKeyPair(int) method.
 *
 * @param stream The stream to write the KeyPair to.  Key streams contain both the
 * public and private keys and should be secured.
 *
 * @throws java.io.IOException For any Stream IO related exceptions
 * @throws java.lang.NullPointerException If either parameter is null
 * @since 2.0/*from w  w w .  j  a va2  s  .  com*/
 */
public static void exportKeyPair(KeyPair pair, OutputStream stream) throws IOException {
    if (pair == null) {
        throw new IllegalArgumentException("KeyPair may not be null");
    }

    if (stream == null) {
        throw new IllegalArgumentException("Stream may not be null");
    }

    //
    // Turn the keypair into properties
    //
    Properties p = new Properties();

    String pri = new String(Hex.encodeHex(pair.getPrivate().getEncoded()));
    String pub = new String(Hex.encodeHex((pair.getPublic().getEncoded())));
    p.setProperty("public", pub);
    p.setProperty("private", pri);

    p.store(stream, null);
    stream.flush();
    stream.close();

}

From source file:MainClass.java

public static PKCS10CertificationRequest generateRequest(KeyPair pair) throws Exception {
    GeneralNames subjectAltName = new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"));
    Vector oids = new Vector();
    Vector values = new Vector();

    oids.add(X509Extensions.SubjectAlternativeName);
    values.add(new X509Extension(false, new DEROctetString(subjectAltName)));

    X509Extensions extensions = new X509Extensions(oids, values);

    Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
            new DERSet(extensions));

    return new PKCS10CertificationRequest("SHA256withRSA", new X500Principal("CN=Requested Test Certificate"),
            pair.getPublic(), new DERSet(attribute), pair.getPrivate());
}

From source file:Main.java

public static String getJwkPrivate(KeyPair kp) {
    try {/*www  .  ja  v a  2 s. co m*/
        JSONObject jk = new JSONObject();
        jk.put("kty", "RSA");
        // generate random kid 
        SecureRandom random = new SecureRandom();
        String kid = new BigInteger(130, random).toString(32);
        jk.put("kid", kid);
        jk.put("e", "AQAB");

        KeyFactory kfactory = KeyFactory.getInstance("RSA");

        RSAPrivateKeySpec privkspec = (RSAPrivateKeySpec) kfactory.getKeySpec(kp.getPrivate(),
                RSAPrivateKeySpec.class);
        RSAPublicKeySpec pubkspec = (RSAPublicKeySpec) kfactory.getKeySpec(kp.getPublic(),
                RSAPublicKeySpec.class);

        // Log.d("getJwkPrivate n",pubkspec.getPublicExponent().toString());
        // Log.d("getJwkPrivate d",privkspec.getPrivateExponent().toString());

        jk.put("n", encodeB64(pubkspec.getModulus().toByteArray()));
        jk.put("d", encodeB64(privkspec.getPrivateExponent().toByteArray()));
        JSONArray ja = new JSONArray();
        ja.put(jk);
        JSONObject jo = new JSONObject();
        jo.put("keys", ja);

        return jo.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}