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:fi.okm.mpass.idp.authn.impl.ValidateOIDCIDTokenSignatureTest.java

protected static RSAKey buildRsaKey(final KeyPair keyPair, final String kid) throws URISyntaxException {
    return new RSAKey((RSAPublicKey) keyPair.getPublic(), KeyUse.SIGNATURE, null, new Algorithm("RS256"), kid,
            new URI("https://mock"), new Base64URL(""), new ArrayList<Base64>());

}

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

public static KeyStore getPKCS12KeyStore(String alias, Certificate[] certChain, KeyPair keyPair, char[] passwd)
        throws Exception {

    PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) keyPair.getPrivate();
    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
    SubjectKeyIdentifier pubKeyId = new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic());
    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, pubKeyId);
    KeyStore store = KeyStore.getInstance(KEY_STORE_TYPE, JCE_PROVIDER);
    store.load(null, null);/*from www  .j a  va2s. c  om*/
    store.setKeyEntry(alias, keyPair.getPrivate(), passwd, certChain);
    return store;
}

From source file:cn.util.RSAUtils.java

/**
 * ??//from w w w.j  a va2  s  .  c o  m
 * @throws NoSuchAlgorithmException 
 *
 */
public static HashMap<String, Object> getKeys() throws NoSuchAlgorithmException {
    HashMap<String, Object> map = new HashMap<String, Object>();
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
    keyPairGen.initialize(1024);
    KeyPair keyPair = keyPairGen.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    map.put("public", publicKey);
    map.put("private", privateKey);
    return map;
}

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static void writeCrypt(File file, File keystore, InputStream stream) throws IOException {
    if (keystore.exists()) {
        KeyPair keyPair = load(keystore);
        if (keyPair != null) {
            try {
                byte[] decrypt = encrypt(keyPair.getPublic(), IOUtils.toByteArray(stream));
                FileUtils.writeByteArrayToFile(file, decrypt);
            } catch (Exception e) {
                logger.trace(e);// w  w w . ja  va  2s.  c  o  m
            }
        }
    }
}

From source file:org.apache.nifi.toolkit.tls.util.TlsHelper.java

public static JcaPKCS10CertificationRequest generateCertificationRequest(String requestedDn,
        String domainAlternativeNames, KeyPair keyPair, String signingAlgorithm)
        throws OperatorCreationException {
    JcaPKCS10CertificationRequestBuilder jcaPKCS10CertificationRequestBuilder = new JcaPKCS10CertificationRequestBuilder(
            new X500Name(requestedDn), keyPair.getPublic());

    // add Subject Alternative Name(s)
    if (StringUtils.isNotBlank(domainAlternativeNames)) {
        try {//from  ww w  . ja v  a2s. co  m
            jcaPKCS10CertificationRequestBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
                    createDomainAlternativeNamesExtensions(domainAlternativeNames));
        } catch (IOException e) {
            throw new OperatorCreationException(
                    "Error while adding " + domainAlternativeNames + " as Subject Alternative Name.", e);
        }
    }

    JcaContentSignerBuilder jcaContentSignerBuilder = new JcaContentSignerBuilder(signingAlgorithm);
    return new JcaPKCS10CertificationRequest(
            jcaPKCS10CertificationRequestBuilder.build(jcaContentSignerBuilder.build(keyPair.getPrivate())));
}

From source file:org.kaaproject.kaa.common.endpoint.security.KeyUtil.java

/**
 * Saves public and private keys to specified streams.
 *
 * @param keyPair          the key pair//w  ww  . j  a  v a2  s  . co m
 * @param privateKeyOutput the private key output stream
 * @param publicKeyOutput  the public key output stream
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void saveKeyPair(KeyPair keyPair, OutputStream privateKeyOutput, OutputStream publicKeyOutput)
        throws IOException {
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    // Store Public Key.
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
    publicKeyOutput.write(x509EncodedKeySpec.getEncoded());

    // Store Private Key.
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    privateKeyOutput.write(pkcs8EncodedKeySpec.getEncoded());
}

From source file:org.red5.server.net.rtmp.RTMPHandshake.java

/**
 * Returns the public key for a given key pair.
 * /*  www  .  j av  a 2 s .  c  o m*/
 * @param keyPair
 * @return public key
 */
protected static byte[] getPublicKey(KeyPair keyPair) {
    DHPublicKey incomingPublicKey = (DHPublicKey) keyPair.getPublic();
    BigInteger dhY = incomingPublicKey.getY();
    log.debug("Public key: {}", dhY);
    byte[] result = dhY.toByteArray();
    //log.debug("Public key as bytes - length [{}]: {}", result.length, Hex.encodeHexString(result));
    byte[] temp = new byte[KEY_LENGTH];
    if (result.length < KEY_LENGTH) {
        System.arraycopy(result, 0, temp, KEY_LENGTH - result.length, result.length);
        result = temp;
        log.debug("Padded public key length to 128");
    } else if (result.length > KEY_LENGTH) {
        System.arraycopy(result, result.length - KEY_LENGTH, temp, 0, KEY_LENGTH);
        result = temp;
        log.debug("Truncated public key length to 128");
    }
    return result;
}

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

public static PKCS10CertificationRequest newCertificateRequest(X500Name principal, KeyPair p) {
    try {//from  w ww  .j a  v a  2s.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.firejack.platform.web.security.x509.KeyUtils.java

public static void setProperties(File properties, File keystore, Map<String, String> append)
        throws IOException {
    Properties props = getProperties(properties, keystore);

    if (properties.exists() || properties.createNewFile()) {
        props.putAll(append);/*from  w w w.  j av a2 s . co m*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        props.store(baos, null);

        InputStream stream = new ByteArrayInputStream(baos.toByteArray());
        if (keystore.exists()) {
            KeyPair keyPair = load(keystore);
            if (keyPair != null) {
                try {
                    byte[] decrypt = encrypt(keyPair.getPublic(), baos.toByteArray());
                    stream = new ByteArrayInputStream(decrypt);
                } catch (Exception e) {
                    logger.trace(e);
                }
            }
        }

        FileOutputStream writer = new FileOutputStream(properties);
        IOUtils.copy(stream, writer);
        IOUtils.closeQuietly(writer);
    }
}

From source file:com.owncloud.android.utils.PushUtils.java

private static int generateRsa2048KeyPair() {
    String keyPath = MainApp.getStoragePath() + File.separator + MainApp.getDataFolder() + File.separator
            + KEYPAIR_FOLDER;/*from  w w  w  .  jav  a2  s  .c  o  m*/

    String privateKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PRIV_EXTENSION;
    String publicKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PUB_EXTENSION;
    File keyPathFile = new File(keyPath);

    if (!new File(privateKeyPath).exists() && !new File(publicKeyPath).exists()) {
        try {
            if (!keyPathFile.exists()) {
                keyPathFile.mkdir();
            }
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
            keyGen.initialize(2048);

            KeyPair pair = keyGen.generateKeyPair();
            int statusPrivate = saveKeyToFile(pair.getPrivate(), privateKeyPath);
            int statusPublic = saveKeyToFile(pair.getPublic(), publicKeyPath);

            if (statusPrivate == 0 && statusPublic == 0) {
                // all went well
                return 0;
            } else {
                return -2;
            }
        } catch (NoSuchAlgorithmException e) {
            Log_OC.d(TAG, "RSA algorithm not supported");
        }
    } else {
        // we already have the key
        return -1;
    }

    // we failed to generate the key
    return -2;
}