Example usage for java.security KeyFactory generatePrivate

List of usage examples for java.security KeyFactory generatePrivate

Introduction

In this page you can find the example usage for java.security KeyFactory generatePrivate.

Prototype

public final PrivateKey generatePrivate(KeySpec keySpec) throws InvalidKeySpecException 

Source Link

Document

Generates a private key object from the provided key specification (key material).

Usage

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java

static PrivateKey loadPrivateKey(String file, String algorithm)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    // Read Private Key.
    File filePrivateKey = new File(file);
    FileInputStream fis = new FileInputStream(file);
    byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
    fis.read(encodedPrivateKey);//from w  w w.  j a  v  a  2  s  . c  om
    fis.close();

    // Generate KeyPair.
    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    return privateKey;
}

From source file:JALPTest.java

/**
 * Creates a Producer using the given command line params.
 *
 * @param xml            the ApplicationMetadataXML
 * @param socketPath      a String which is the path to the socket
 * @param privateKeyPath   a String which is the path to the private key in DER format
 * @param publicKeyPath      a String which is the path to the public key in DER format
 * @param certPath         a String which is the path to the certificate
 * @param hasDigest         a Boolean, true to set a digest method in the producer
 * @return   the created Producer/*w ww.j av a  2s  .c om*/
 * @throws Exception
 */
private static Producer createProducer(ApplicationMetadataXML xml, String socketPath, String privateKeyPath,
        String publicKeyPath, String certPath, Boolean hasDigest) throws Exception {
    Producer producer = new Producer(xml);
    producer.setSocketFile(socketPath);

    if (privateKeyPath != null && !"".equals(privateKeyPath)) {

        File privateKeyFile = new File(privateKeyPath);
        DataInputStream privateDis = new DataInputStream(new FileInputStream(privateKeyFile));
        byte[] privateKeyBytes = new byte[(int) privateKeyFile.length()];
        privateDis.readFully(privateKeyBytes);
        privateDis.close();

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        KeySpec privateKs = new PKCS8EncodedKeySpec(privateKeyBytes);
        PrivateKey privateKey = keyFactory.generatePrivate(privateKs);

        File publicKeyFile = new File(publicKeyPath);
        DataInputStream publicDis = new DataInputStream(new FileInputStream(publicKeyFile));
        byte[] publicKeyBytes = new byte[(int) publicKeyFile.length()];
        publicDis.readFully(publicKeyBytes);
        publicDis.close();

        KeySpec publicKs = new X509EncodedKeySpec(publicKeyBytes);
        PublicKey publicKey = keyFactory.generatePublic(publicKs);

        producer.setPrivateKey(privateKey);
        producer.setPublicKey(publicKey);
    }

    if (certPath != null && !"".equals(certPath)) {
        InputStream inputStream = new FileInputStream(certPath);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream);
        inputStream.close();
        producer.setCertificate(cert);
    }

    if (hasDigest) {
        producer.setDigestMethod(DMType.SHA256);
    }

    return producer;
}

From source file:com.streamsets.pipeline.lib.http.oauth2.OAuth2ConfigBean.java

private static PrivateKey parseRSAKey(String key, Stage.Context context, List<Stage.ConfigIssue> issues) {
    String privKeyPEM = key.replace("-----BEGIN PRIVATE KEY-----\n", "");
    privKeyPEM = privKeyPEM.replace("-----END PRIVATE KEY-----", "");
    privKeyPEM = privKeyPEM.replace("\n", "");
    privKeyPEM = privKeyPEM.replace("\r", "");

    try {//from ww  w .j  a v  a2 s.c om
        // Base64 decode the data
        byte[] encoded = Base64.getDecoder().decode(privKeyPEM.getBytes());

        // PKCS8 decode the encoded RSA private key
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);

        KeyFactory kf = KeyFactory.getInstance(RSA);
        return kf.generatePrivate(keySpec);
    } catch (NoSuchAlgorithmException ex) {
        LOG.error(Utils.format("'{}' algorithm not available", RSA), ex);
        issues.add(context.createConfigIssue(CONFIG_GROUP, PREFIX + "algorithm", HTTP_25));
    } catch (InvalidKeySpecException ex) {
        LOG.error(Utils.format("'{}' algorithm not available", RSA), ex);
        issues.add(context.createConfigIssue(CONFIG_GROUP, PREFIX + "key", HTTP_26));
    } catch (IllegalArgumentException ex) {
        LOG.error("Invalid key", ex);
        issues.add(context.createConfigIssue(CONFIG_GROUP, PREFIX + "key", HTTP_27, ex.toString()));
    }
    return null;
}

From source file:com.clustercontrol.util.KeyCheck.java

/**
 * ?//w w w .  j av a2 s .  c o m
 * com.clustercontrol.key.KeyGenerator????????public??
 * @param str
 * @return
 * @throws HinemosUnknown
 */
public static PrivateKey getPrivateKey(String str) throws HinemosUnknown {
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(string2Byte(str));
        return keyFactory.generatePrivate(privateKeySpec);
    } catch (InvalidKeySpecException e) {
        throw new HinemosUnknown("getPrivateKey fail " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new HinemosUnknown("getPrivateKey fail " + e.getMessage(), e);
    }
}

From source file:de.pawlidi.openaletheia.utils.CipherUtils.java

/**
 * //from w ww . jav  a  2  s.  co  m
 * @param data
 * @return
 */
public static RSAPrivateKey buildPrivateKey(final String key) {
    if (StringUtils.isNotEmpty(key)) {
        try {
            byte[] bytes = Converter.toBytes(key);
            KeyFactory keyFactory = KeyFactory.getInstance(CIPHER_ALGORITHM);
            PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(bytes);
            return (RSAPrivateKey) keyFactory.generatePrivate(privSpec);
        } catch (Exception e) {
            throw new RuntimeException("Cannot create " + CIPHER_ALGORITHM + " private key from " + key, e);
        }
    }
    return null;
}

From source file:org.umit.icm.mobile.utils.RSACrypto.java

public static PrivateKey generatePrivateKey(BigInteger modulus, BigInteger exponential)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    RSAPrivateKeySpec rsaKeySpec = new RSAPrivateKeySpec(modulus, exponential);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePrivate(rsaKeySpec);
}

From source file:org.umit.icm.mobile.utils.RSACrypto.java

/**
* Converts a {@link String} to {@link PrivateKey}.
*    /* www.  j a v a  2s .c om*/
                             
@param  privateKeyString  An object of the type {@link String}
*                                  
        
@return  {@link PrivateKey}
* 
        
@see         PKCS8EncodedKeySpec
*
        
@see         KeyFactory
*/
public static PrivateKey stringToPrivateKey(String privateKeyString)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyString.getBytes()));
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePrivate(spec);
}

From source file:com.google.u2f.TestUtils.java

public static PrivateKey parsePrivateKey(String keyBytesHex) {
    try {//www.  j a  v a 2  s .  c o m
        KeyFactory fac = KeyFactory.getInstance("ECDSA");
        X9ECParameters curve = SECNamedCurves.getByName("secp256r1");
        ECParameterSpec curveSpec = new ECParameterSpec(curve.getCurve(), curve.getG(), curve.getN(),
                curve.getH());
        ECPrivateKeySpec keySpec = new ECPrivateKeySpec(new BigInteger(keyBytesHex, 16), curveSpec);
        return fac.generatePrivate(keySpec);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.vexsoftware.votifier.util.rsa.RSAIO.java

/**
 * Loads an RSA key pair from a directory. The directory must have the files
 * "public.key" and "private.key".//from w w w. j av  a 2  s . co m
 * 
 * @param directory
 *            The directory to load from
 * @return The key pair
 * @throws Exception
 *             If an error occurs
 */
public static KeyPair load(File directory) throws Exception {
    // Read the public key file.
    File publicKeyFile = new File(directory + "/public.key");
    FileInputStream in = null;
    byte[] encodedPublicKey;
    try {
        in = new FileInputStream(directory + "/public.key");
        encodedPublicKey = new byte[(int) publicKeyFile.length()];
        in.read(encodedPublicKey);
        encodedPublicKey = DatatypeConverter.parseBase64Binary(new String(encodedPublicKey));
    } finally {
        try {
            in.close();
        } catch (Exception exception) {
            // ignore
        }
    }

    // Read the private key file.
    File privateKeyFile = new File(directory + "/private.key");
    byte[] encodedPrivateKey;
    try {
        in = new FileInputStream(directory + "/private.key");
        encodedPrivateKey = new byte[(int) privateKeyFile.length()];
        in.read(encodedPrivateKey);
        encodedPrivateKey = DatatypeConverter.parseBase64Binary(new String(encodedPrivateKey));
    } finally {
        try {
            in.close();
        } catch (Exception exception) {
            // ignore
        }
    }

    // Instantiate and return the key pair.
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
    return new KeyPair(publicKey, privateKey);
}

From source file:org.umit.icm.mobile.utils.RSACrypto.java

/**
* Reads an RSA {@link PrivateKey} from disk.
*    /*w  w  w . j  av a2  s  . com*/
*
                             
@param  fileName  An object of the type {@link String}
*                                  
        
@return  {@link PrivateKey}
* 
        
@see         SDCardReadWrite
*/
public static PrivateKey readPrivateKey(String fileName) throws IOException {

    File sdCard = Environment.getExternalStorageDirectory();
    File keyDir = new File(sdCard.getAbsolutePath() + Constants.KEYS_DIR);
    File file = new File(keyDir, fileName);
    InputStream inputStream = new FileInputStream(file.toString());
    ObjectInputStream objInputStream = new ObjectInputStream(new BufferedInputStream(inputStream));
    try {
        BigInteger modulus = (BigInteger) objInputStream.readObject();
        BigInteger exponential = (BigInteger) objInputStream.readObject();
        RSAPrivateKeySpec rsaKeySpec = new RSAPrivateKeySpec(modulus, exponential);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(rsaKeySpec);
    } catch (Exception e) {
        throw new RuntimeException("readPrivateKey exception", e);
    } finally {
        objInputStream.close();
    }

}