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:com.joyent.manta.config.TestConfigContext.java

/**
 * Some test cases need a direct reference to a KeyPair along with it's associated config. Manually calling
 * KeyPairFactory with a half-baked config can get cumbersome, so let's build a ConfigContext which has
 * everything ready and supplies the relevant KeyPair.
 *
 * @return the generated keypair and a config which uses a serialized version of that keypair
 *//*  w ww.  j  a va2 s  .c  o m*/
public static ImmutablePair<KeyPair, BaseChainedConfigContext> generateKeyPairBackedConfig(
        final String passphrase) {
    final KeyPair keyPair;
    try {
        keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
    } catch (final NoSuchAlgorithmException impossible) {
        throw new Error(impossible); // "RSA" is always provided
    }

    final Object keySerializer;
    if (passphrase != null) {
        try {
            keySerializer = new JcaMiscPEMGenerator(keyPair.getPrivate(),
                    new JcePEMEncryptorBuilder("AES-128-CBC").build(passphrase.toCharArray()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } else {
        keySerializer = keyPair.getPrivate();
    }

    final String keyContent;
    try (final StringWriter content = new StringWriter();
            final JcaPEMWriter writer = new JcaPEMWriter(content)) {
        writer.writeObject(keySerializer);
        writer.flush();
        keyContent = content.toString();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    final BaseChainedConfigContext config = new ChainedConfigContext(DEFAULT_CONFIG)
            // we need to unset the key path in case one exists at ~/.ssh/id_rsa
            // see the static initializer in DefaultsConfigContext
            .setMantaKeyPath(null).setPrivateKeyContent(keyContent)
            .setMantaKeyId(KeyFingerprinter.md5Fingerprint(keyPair));

    if (passphrase != null) {
        config.setPassword(passphrase);
    }

    return new ImmutablePair<>(keyPair, config);
}

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

public static PrivateKeyEntry generatePrivateKeyEntry(KeyAlgorithm keyAlgorithm, String dn) {

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

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

public static X509Certificate generateSelfSignedCertificate(KeyPair keyPair, String dn, DateTime notBefore,
        DateTime notAfter, @Nullable String signatureAlgorithm, boolean includeAuthorityKeyIdentifier,
        boolean caCert, boolean timeStampingPurpose)
        throws IllegalStateException, IOException, CertificateException, OperatorCreationException {

    return generateCertificate(keyPair.getPublic(), dn, keyPair.getPrivate(), null, notBefore, notAfter,
            signatureAlgorithm, includeAuthorityKeyIdentifier, caCert, timeStampingPurpose, 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   www . ja v  a  2  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:gemlite.core.util.RSAUtils.java

/**
 * <p>//from w  ww .  java2 s. c o  m
 * ?(?)
 * </p>
 * 
 * @return
 * @throws Exception
 */
public static Map<String, Object> genKeyPair() throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    keyPairGen.initialize(512);
    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:com.glaf.core.security.RSAUtils.java

/**
 * ?/*from w  w w .  j a  va  2  s .  co  m*/
 * <p />
 * {@code encrypttext}  {@code null} {@code null} ???
 * {@code null}
 * 
 * @param encrypttext
 *            
 * @return 
 */
public static String decryptString(String encrypttext) {
    if (StringUtils.isEmpty(encrypttext)) {
        return null;
    }
    KeyPair keyPair = getKeyPair();
    try {
        byte[] en_data = Hex.decodeHex(encrypttext.toCharArray());
        byte[] data = decrypt((RSAPrivateKey) keyPair.getPrivate(), en_data);
        return new String(data);
    } catch (Exception ex) {
        LOGGER.error(String.format("\"%s\" Decryption failed. Cause: %s", encrypttext, ex.getMessage()));
    }
    return null;
}

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

public static PKCS10CertificationRequest newCertificateRequest(X500Name principal, KeyPair p) {
    try {//from www . jav  a 2  s  .c o  m
        PKCS10CertificationRequestBuilder b = new JcaPKCS10CertificationRequestBuilder(principal,
                p.getPublic());
        ContentSigner s = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider("BC")
                .build(p.getPrivate());
        return b.build(s);
    } catch (OperatorCreationException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

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:cloudeventbus.pki.CertificateUtils.java

public static Certificate generateSelfSignedCertificate(KeyPair keyPair, long expirationDate,
        List<Subject> subscribePermissions, List<Subject> publishPermissions, String comment) {
    final long serialNumber = secureRandom.get().nextLong();
    final Certificate certificate = new Certificate(Certificate.Type.AUTHORITY, serialNumber, serialNumber,
            expirationDate, keyPair.getPublic(), subscribePermissions, publishPermissions, comment, null);
    return signCertificate(certificate, keyPair.getPrivate(), certificate);
}

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);//  ww  w. java  2 s . c om
    store.setKeyEntry(alias, keyPair.getPrivate(), pwd, chain);

    return store;
}