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:com.streamsets.datacollector.credential.cyberark.TestWebServicesFetcher.java

@SuppressWarnings("deprecation")
/**//  w w w .ja v  a 2  s .c  o  m
 * Create a self-signed X.509 Certificate.
 *
 * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
 * @param pair the KeyPair
 * @param days how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 * @return the self-signed certificate
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm)
        throws CertificateEncodingException, InvalidKeyException, IllegalStateException,
        NoSuchProviderException, NoSuchAlgorithmException, SignatureException {

    Date from = new Date();
    Date to = new Date(from.getTime() + days * 86400000l);
    BigInteger sn = new BigInteger(64, new SecureRandom());
    KeyPair keyPair = pair;
    X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
    X500Principal dnName = new X500Principal(dn);

    certGen.setSerialNumber(sn);
    certGen.setIssuerDN(dnName);
    certGen.setNotBefore(from);
    certGen.setNotAfter(to);
    certGen.setSubjectDN(dnName);
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm(algorithm);

    X509Certificate cert = certGen.generate(pair.getPrivate());
    return cert;
}

From source file:mitm.djigzo.web.pages.dkim.DKIMSettings.java

protected void onValidateForm() throws HierarchicalPropertiesException, WebServiceCheckedException {
    keyPair = StringUtils.trimToNull(keyPair);

    if (keyPair != null) {
        /*/*from   ww w  .java2 s.  c o m*/
         * Check if the keyPair is really a PEM encoded keypair 
         */
        PEMReader pem = new PEMReader(new StringReader(keyPair));

        Object o = null;

        try {
            o = pem.readObject();
        } catch (IOException e) {
            logKeyPairError("The input is not valid PEM encoded");
        }

        if (o != null) {
            if (!(o instanceof KeyPair)) {
                String clazz = o.getClass().toString();

                if (o instanceof PublicKey) {
                    clazz = "public key";
                } else if (o instanceof PrivateKey) {
                    clazz = "private key";
                }

                logKeyPairError("The input is not a valid key pair but is a " + clazz);
            } else {
                KeyPair keyPair = (KeyPair) o;

                if (keyPair.getPrivate() == null) {
                    logKeyPairError("The private key is missing");
                } else if (keyPair.getPublic() == null) {
                    logKeyPairError("The public key is missing");
                }
            }
        } else {
            logKeyPairError("The input does not contain a valid key pair");
        }
    } else {
        logKeyPairError("The input does not contain a valid key pair");
    }
}

From source file:org.apache.usergrid.security.ApigeeSSO2ProviderIT.java

@Test
public void testNewPublicKeyFetch() throws Exception {

    // create old keypair
    KeyPair kp = RsaProvider.generateKeyPair(1024);
    PublicKey publicKey = kp.getPublic();
    PrivateKey privateKey = kp.getPrivate();

    // create new keypair
    KeyPair kpNew = RsaProvider.generateKeyPair(1024);
    PublicKey publicKeyNew = kpNew.getPublic();
    PrivateKey privateKeyNew = kpNew.getPrivate();

    // create mock provider with old and old key
    MockApigeeSSO2ProviderNewKey provider = new MockApigeeSSO2ProviderNewKey(publicKey, publicKeyNew);
    provider.setManagement(setup.getMgmtSvc());

    // create user, claims and a token for those things. Sign with new public key
    User user = createUser();//from   www  . j  a v  a  2s.c  o m
    long exp = System.currentTimeMillis() + 10000;
    Map<String, Object> claims = createClaims(user.getUsername(), user.getEmail(), exp);
    String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.RS256, privateKeyNew).compact();

    // test that provider can validate the token, get user, return token info
    TokenInfo tokenInfo = provider.validateAndReturnTokenInfo(token, 86400L);
    Assert.assertNotNull(tokenInfo);

    // assert that provider called for new key
    Assert.assertTrue(provider.isGetPublicKeyCalled());

    // try it again, but this time it should fail due to freshness value

    provider.setPublicKey(publicKey); // set old key

    // test that signature exception thrown
    try {
        provider.validateAndReturnTokenInfo(token, 86400L);
        Assert.fail("Should have failed due to bad signature");

    } catch (BadTokenException e) {
        Assert.assertTrue(e.getCause() instanceof SignatureException);
    }

}

From source file:com.aqnote.shared.cryptology.cert.gen.CertGenerator.java

public PKCS10CertificationRequest createCSR(X500Name x500Name, KeyPair keyPair) throws Exception {
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();
    PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(x500Name,
            publicKey);//www  . ja  v  a  2s  . co m
    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(ALG_SIG_SHA256_RSA);
    ContentSigner signer = csBuilder.build(privateKey);
    PKCS10CertificationRequest csr = p10Builder.build(signer);

    return csr;
}

From source file:com.aqnote.shared.cryptology.cert.gen.CertGenerator.java

private X509Certificate createRootCaCert(X500Name idn, KeyPair keyPair) throws Exception {

    PublicKey pubKey = keyPair.getPublic();
    PrivateKey privKey = keyPair.getPrivate();

    BigInteger sno = BigInteger.valueOf(1);
    Date nb = new Date(System.currentTimeMillis() - ONE_DAY);
    Date na = new Date(nb.getTime() + TWENTY_YEAR);

    X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(idn, sno, nb, na, idn, pubKey);

    addSubjectKID(certBuilder, pubKey);//from   www  .  jav a 2  s.  co  m
    addAuthorityKID(certBuilder, pubKey);
    addCRLDistributionPoints(certBuilder);
    addAuthorityInfoAccess(certBuilder);
    certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(Boolean.TRUE));

    X509Certificate certificate = signCert(certBuilder, privKey);
    certificate.checkValidity(new Date());
    certificate.verify(pubKey);

    setPKCS9Info(certificate);

    return certificate;
}

From source file:com.aqnote.shared.encrypt.cert.gen.BCCertGenerator.java

public X509Certificate createClass1EndCert(X500Name sdn, PublicKey pubKey, KeyPair pKeyPair) throws Exception {

    PublicKey pPubKey = pKeyPair.getPublic();
    PrivateKey pPrivKey = pKeyPair.getPrivate();

    X500Name issuer = X500NameUtil.createClass1RootPrincipal();
    BigInteger sno = BigInteger.valueOf(System.currentTimeMillis());
    Date nb = new Date(System.currentTimeMillis() - HALF_DAY);
    Date na = new Date(nb.getTime() + FIVE_YEAR);

    X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, sno, nb, na, sdn, pubKey);

    addSubjectKID(certBuilder, pubKey);//from   w  w w.j  av a 2  s .  co m
    addAuthorityKID(certBuilder, pPubKey);
    certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(BASE_EKU));
    certBuilder.addExtension(Extension.keyUsage, false, new KeyUsage(END_KEY_USAGE));

    X509Certificate certificate = signCert(certBuilder, pPrivKey);
    certificate.checkValidity(new Date());
    certificate.verify(pPubKey);

    setPKCS9Info(certificate);

    return certificate;
}

From source file:hudson.cli.Connection.java

/**
 * Used in conjunction with {@link #verifyIdentity(byte[])} to prove
 * that we actually own the private key of the given key pair.
 */// w w w  . java2 s.  co m
public void proveIdentity(byte[] sharedSecret, KeyPair key) throws IOException, GeneralSecurityException {
    String algorithm = detectKeyAlgorithm(key);
    writeUTF(algorithm);
    writeKey(key.getPublic());

    Signature sig = Signature.getInstance("SHA1with" + algorithm);
    sig.initSign(key.getPrivate());
    sig.update(key.getPublic().getEncoded());
    sig.update(sharedSecret);
    writeObject(sig.sign());
}

From source file:com.example.android.basicandroidkeystore.BasicAndroidKeyStoreFragment.java

/**
 * Creates a public and private key and stores it using the Android Key Store, so that only
 * this application will be able to access the keys.
 *//*ww  w. j  a  v  a2  s.  co  m*/
public void createKeys(Context context)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    // BEGIN_INCLUDE(create_valid_dates)
    // Create a start and end time, for the validity range of the key pair that's about to be
    // generated.
    Calendar start = new GregorianCalendar();
    Calendar end = new GregorianCalendar();
    end.add(Calendar.YEAR, 1);
    //END_INCLUDE(create_valid_dates)

    // BEGIN_INCLUDE(create_spec)
    // The KeyPairGeneratorSpec object is how parameters for your key pair are passed
    // to the KeyPairGenerator.  For a fun home game, count how many classes in this sample
    // start with the phrase "KeyPair".
    KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
            // You'll use the alias later to retrieve the key.  It's a key for the key!
            .setAlias(mAlias)
            // The subject used for the self-signed certificate of the generated pair
            .setSubject(new X500Principal("CN=" + mAlias))
            // The serial number used for the self-signed certificate of the
            // generated pair.
            .setSerialNumber(BigInteger.valueOf(1337))
            // Date range of validity for the generated pair.
            .setStartDate(start.getTime()).setEndDate(end.getTime()).build();
    // END_INCLUDE(create_spec)

    // BEGIN_INCLUDE(create_keypair)
    // Initialize a KeyPair generator using the the intended algorithm (in this example, RSA
    // and the KeyStore.  This example uses the AndroidKeyStore.
    KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance(SecurityConstants.TYPE_RSA,
            SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE);
    kpGenerator.initialize(spec);
    KeyPair kp = kpGenerator.generateKeyPair();
    Log.d(TAG, "Public Key is: " + kp.getPublic().toString());
    // END_INCLUDE(create_keypair)
}

From source file:org.apache.accumulo.test.util.CertUtils.java

public void createSelfSignedCert(File targetKeystoreFile, String keyName, String keystorePassword)
        throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException,
        OperatorCreationException, AccumuloSecurityException, NoSuchProviderException {
    if (targetKeystoreFile.exists()) {
        throw new FileExistsException(targetKeystoreFile);
    }//from   w ww  .  jav  a 2 s  .  com

    KeyPair kp = generateKeyPair();

    X509CertificateObject cert = generateCert(keyName, kp, true, kp.getPublic(), kp.getPrivate());

    char[] password = keystorePassword.toCharArray();
    KeyStore keystore = KeyStore.getInstance(keystoreType);
    keystore.load(null, null);
    keystore.setCertificateEntry(keyName + "Cert", cert);
    keystore.setKeyEntry(keyName + "Key", kp.getPrivate(), password, new Certificate[] { cert });
    try (FileOutputStream fos = new FileOutputStream(targetKeystoreFile)) {
        keystore.store(fos, password);
    }
}

From source file:com.aqnote.shared.encrypt.cert.gen.BCCertGenerator.java

public X509Certificate createRootCaCert(final KeyPair keyPair) throws Exception {

    PublicKey pubKey = keyPair.getPublic();
    PrivateKey privKey = keyPair.getPrivate();

    X500Name idn = X500NameUtil.createRootPrincipal();
    BigInteger sno = BigInteger.valueOf(1);
    Date nb = new Date(System.currentTimeMillis() - ONE_DAY);
    Date na = new Date(nb.getTime() + TWENTY_YEAR);

    X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(idn, sno, nb, na, idn, pubKey);

    addSubjectKID(certBuilder, pubKey);//from w ww.j a v  a 2 s  . co  m
    addAuthorityKID(certBuilder, pubKey);
    addCRLDistributionPoints(certBuilder);
    addAuthorityInfoAccess(certBuilder);
    certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(Boolean.TRUE));

    X509Certificate certificate = signCert(certBuilder, privKey);
    certificate.checkValidity(new Date());
    certificate.verify(pubKey);

    setPKCS9Info(certificate);

    return certificate;
}