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.intuit.s3encrypt.S3Encrypt.java

public static void saveKeyPair(String filename, KeyPair keyPair) throws IOException {
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    // Save public key to file.
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
    FileOutputStream keyfos = new FileOutputStream(filename + ".pub");
    keyfos.write(x509EncodedKeySpec.getEncoded());
    keyfos.close();/*  w w w .  j a  v  a  2  s.c o m*/

    // Save private key to file.
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    keyfos = new FileOutputStream(filename);
    keyfos.write(pkcs8EncodedKeySpec.getEncoded());
    keyfos.close();

}

From source file:net.nicholaswilliams.java.licensing.licensor.TestLicenseCreator.java

@BeforeClass
public static void setUpClass() throws Exception {
    TestLicenseCreator.control = EasyMock.createStrictControl();

    TestLicenseCreator.passwordProvider = TestLicenseCreator.control.createMock(PasswordProvider.class);
    TestLicenseCreator.keyDataProvider = TestLicenseCreator.control.createMock(PrivateKeyDataProvider.class);

    try {//from w w  w  . ja  va2 s .  c om
        LicenseCreator.getInstance();
        fail("Expected java.lang.IllegalArgumentException, got no exception.");
    } catch (IllegalArgumentException ignore) {
    }

    LicenseCreatorProperties.setPrivateKeyDataProvider(TestLicenseCreator.keyDataProvider);

    try {
        LicenseCreator.getInstance();
        fail("Expected java.lang.IllegalArgumentException, got no exception.");
    } catch (IllegalArgumentException ignore) {
    }

    LicenseCreatorProperties.setPrivateKeyPasswordProvider(TestLicenseCreator.passwordProvider);

    LicenseCreator.getInstance();

    KeyPair keyPair = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair();

    TestLicenseCreator.publicKey = keyPair.getPublic();

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyPair.getPrivate().getEncoded());
    IOUtils.write(Encryptor.encryptRaw(pkcs8EncodedKeySpec.getEncoded(), keyPassword), outputStream);
    TestLicenseCreator.encryptedPrivateKey = outputStream.toByteArray();
}

From source file:com.zxy.commons.codec.rsa.RSAUtils.java

/**
 * <p>// ww  w .  j  a  v a  2s  .com
 * ?(?)
 * </p>
 * 
 * @return Map<String, Object>
 * @throws Exception Exception
 */
public static Map<String, Object> genKeyPair() throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    keyPairGen.initialize(1024);
    KeyPair keyPair = keyPairGen.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    Map<String, Object> keyMap = new HashMap<String, Object>(2);
    keyMap.put(PUBLIC_KEY, publicKey);
    keyMap.put(PRIVATE_KEY, privateKey);
    return keyMap;
}

From source file:no.digipost.api.client.ApiServiceMock.java

static EncryptionKey createFakeEncryptionKey() {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (Writer osWriter = new OutputStreamWriter(baos); PEMWriter writer = new PEMWriter(osWriter)) {

        KeyPairGenerator factory = KeyPairGenerator.getInstance("RSA");
        factory.initialize(2048);/*from   w  w  w. j  av  a  2  s  .  co m*/
        KeyPair keyPair = factory.generateKeyPair();

        writer.writeObject(keyPair.getPublic());

    } catch (Exception e) {
        throw new RuntimeException("Failed creation of fake encryption key.", e);
    }

    EncryptionKey fakeKey = new EncryptionKey();
    fakeKey.setKeyId("fake-hash");
    fakeKey.setValue(new String(baos.toByteArray()));

    return fakeKey;
}

From source file:com.intuit.s3encrypt.S3Encrypt.java

private static KeyPair createKeyFile(String filename)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {

    KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
    keyGenerator.initialize(2048, new SecureRandom());
    KeyPair myKeyPair = keyGenerator.generateKeyPair();

    PublicKey publicKey = myKeyPair.getPublic();
    PrivateKey privateKey = myKeyPair.getPrivate();

    System.out.println("keys created... " + filename);

    saveKeyPair(filename, myKeyPair);//  w  w w .j a va  2 s  .  c o  m
    return myKeyPair;
}

From source file:org.ourgrid.common.util.SelfSignedCertificateGenerator.java

public static void generateX509Certificate(KeyPair keyPair, String dnData, String certFilePath)
        throws CertificateEncodingException, InvalidKeyException, IllegalStateException,
        NoSuchAlgorithmException, SignatureException, IOException {

    X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();

    certGenerator.setSerialNumber(BigInteger.valueOf(1));
    certGenerator.setPublicKey(keyPair.getPublic());
    certGenerator.setSubjectDN(new X500Principal(dnData));
    certGenerator.setIssuerDN(new X500Principal(dnData));
    certGenerator.setNotBefore(new Date(System.currentTimeMillis() - VALIDITY_INTERVAL));
    certGenerator.setNotAfter(new Date(System.currentTimeMillis() + VALIDITY_INTERVAL));
    certGenerator.setSignatureAlgorithm(SignatureConstants.SIGN_ALGORITHM);

    X509Certificate certificate = certGenerator.generate(keyPair.getPrivate());

    File file = new File(certFilePath);
    if (!file.exists()) {
        FileUtils.touch(file);//from  w w w  . j  ava  2 s .c  o m
    }

    FileOutputStream fosP = new FileOutputStream(file);
    fosP.write(certificate.getEncoded());

    fosP.close();
}

From source file:cloudeventbus.cli.Certs.java

private static void chainCertificate(ChainCertificateCommand command) throws Exception {
    final CertificateChain certificates = CertificateUtils.loadCertificateChain(command.existingCertificate);
    final PrivateKey privateKey = CertificateUtils.loadPrivateKey(command.existingPrivateKey);

    final KeyPair keyPair = CertificateUtils.generateKeyPair();
    final Certificate certificate = CertificateUtils.generateSignedCertificate(certificates.getLast(),
            privateKey, keyPair.getPublic(), certificates.getLast().getType(),
            getExpirationDate(command.expirationDate), Subject.list(command.subscribePermissions),
            Subject.list(command.publishPermissions), command.comment);
    certificates.add(certificate);//from w  ww  .j  a v  a 2  s.  co m
    CertificateUtils.saveCertificates(command.certificate, certificates);
    CertificateUtils.savePrivateKey(keyPair.getPrivate(), command.privateKey);
}

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

public static X509Certificate generateTestSelfSignedCert(@Nullable URI ocspUri) throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, IOException, OperatorCreationException, CertificateException {

    KeyPair keyPair = generateKeyPair();
    DateTime now = new DateTime();
    DateTime notBefore = now.minusDays(1);
    DateTime notAfter = now.plusDays(1);
    return generateCertificate(keyPair.getPublic(), "CN=Test", keyPair.getPrivate(), null, notBefore, notAfter,
            null, true, true, false, ocspUri);
}

From source file:com.github.aynu.yukar.framework.util.SecurityHelper.java

/**
 * RSA???/*from  ww  w  .j  av a2 s. c o  m*/
 * <dl>
 * <dt>?
 * <dd>RSA??????2048??????
 * </dl>
 * @return RSA?
 */
public static KeyPair createKeyPair() {
    try {
        final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(2048);
        final KeyPair pair = generator.generateKeyPair();
        if (LOG.isDebugEnabled()) {
            final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic();
            final RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate();
            LOG.debug("public-modulus={}", Base64.encodeBase64String(publicKey.getModulus().toByteArray()));
            LOG.debug("public-exponent={}",
                    Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray()));
            LOG.debug("private-modulus={}", Base64.encodeBase64String(privateKey.getModulus().toByteArray()));
            LOG.debug("private-exponent={}",
                    Base64.encodeBase64String(privateKey.getPrivateExponent().toByteArray()));
        }
        return pair;
    } catch (final NoSuchAlgorithmException e) {
        throw new StandardRuntimeException(e);
    }
}

From source file:com.aqnote.shared.cryptology.cert.util.KeyStoreUtil.java

public static KeyStore readPKCS12KeyStore(String alias, Certificate[] chain, KeyPair keyPair, char[] pwd)
        throws Exception {
    PKCS12SafeBagBuilder BagBuilder = new JcaPKCS12SafeBagBuilder((X509Certificate) chain[0]);
    BagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString(alias));
    SubjectKeyIdentifier pubKeyId = new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic());
    BagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId);

    KeyStore store = KeyStore.getInstance(KEY_STORE_TYPE, JCE_PROVIDER);
    store.load(null, null);//from www  .  j av a2s .  co m
    store.setKeyEntry(alias, keyPair.getPrivate(), pwd, chain);

    return store;
}