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:org.jets3t.service.security.EncryptionUtil.java

/**
 * Generate an RSA SHA1 signature of the given data using the given private
 * key DER certificate.//from w w  w .ja  v  a2 s. co m
 *
 * Based on example code from:
 * http://www.java2s.com/Tutorial/Java/0490__Security/RSASignatureGeneration.htm
 * http://forums.sun.com/thread.jspa?threadID=5175986
 *
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws SignatureException
 * @throws InvalidKeySpecException
 * @throws NoSuchProviderException
 */
public static byte[] signWithRsaSha1(byte[] derPrivateKeyBytes, byte[] dataToSign)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, InvalidKeySpecException,
        NoSuchProviderException {
    // Build an RSA private key from private key data
    PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(derPrivateKeyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(privSpec);

    // Sign data
    Signature signature = Signature.getInstance("SHA1withRSA", "BC");
    signature.initSign(privateKey, new SecureRandom());
    signature.update(dataToSign);

    byte[] signatureBytes = signature.sign();
    return signatureBytes;
}

From source file:info.magnolia.cms.security.SecurityUtil.java

public static String encrypt(String message, String encodedKey) {
    try {/*from w  w w . j av  a  2s.  c  om*/

        // read private key
        if (StringUtils.isBlank(encodedKey)) {
            throw new SecurityException(
                    "Activation key was not found. Please make sure your instance is correctly configured.");
        }
        byte[] binaryKey = hexToByteArray(encodedKey);

        // create RSA public key cipher
        Cipher pkCipher = Cipher.getInstance(ALGORITHM, "BC");
        try {
            // create private key
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(binaryKey);
            KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC");
            PrivateKey pk = kf.generatePrivate(privateKeySpec);

            pkCipher.init(Cipher.ENCRYPT_MODE, pk);
        } catch (InvalidKeySpecException e) {
            // encrypting with public key?
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(binaryKey);
            KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC");
            PublicKey pk = kf.generatePublic(publicKeySpec);

            pkCipher.init(Cipher.ENCRYPT_MODE, pk);
        }

        // encrypt
        byte[] bytes = message.getBytes("UTF-8");
        // split bit message in chunks
        int start = 0;
        StringBuilder chaos = new StringBuilder();
        while (start < bytes.length) {
            byte[] tmp = new byte[Math.min(bytes.length - start, binaryKey.length / 8)];
            System.arraycopy(bytes, start, tmp, 0, tmp.length);
            start += tmp.length;
            byte[] encrypted = pkCipher.doFinal(tmp);
            chaos.append(byteArrayToHex(encrypted));
            chaos.append(";");
        }
        chaos.setLength(chaos.length() - 1);

        return chaos.toString();

    } catch (IOException e) {
        throw new SecurityException(
                "Failed to create authentication string. Please use Java version with cryptography support.",
                e);
    } catch (NoSuchAlgorithmException e) {
        throw new SecurityException(
                "Failed to create authentication string. Please use Java version with cryptography support.",
                e);
    } catch (NoSuchPaddingException e) {
        throw new SecurityException(
                "Failed to create authentication string. Please use Java version with cryptography support.",
                e);
    } catch (InvalidKeySpecException e) {
        throw new SecurityException(
                "Failed to create authentication string. Please use Java version with cryptography support.",
                e);
    } catch (InvalidKeyException e) {
        throw new SecurityException(
                "Failed to create authentication string. Please use Java version with cryptography support.",
                e);
    } catch (NoSuchProviderException e) {
        throw new SecurityException(
                "Failed to find encryption provider. Please use Java version with cryptography support.", e);
    } catch (IllegalBlockSizeException e) {
        throw new SecurityException(
                "Failed to encrypt string. Please use Java version with cryptography support.", e);
    } catch (BadPaddingException e) {
        throw new SecurityException(
                "Failed to encrypt string. Please use Java version with cryptography support.", e);
    }
}

From source file:com.forsrc.utils.MyRsa2Utils.java

/**
 * Gets private key./*www . j  a  v a  2 s.  co  m*/
 *
 * @param key the key
 * @return the private key
 * @throws RsaException the rsa exception
 */
public static PrivateKey getPrivateKey(String key) throws RsaException {
    byte[] keyBytes;
    try {
        keyBytes = (new Base64()).decode(key);
    } catch (Exception e) {
        throw new RsaException(e);
    }
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = null;
    try {
        keyFactory = KeyFactory.getInstance(RsaKey.ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        throw new RsaException(e);
    }
    PrivateKey privateKey = null;
    try {
        privateKey = keyFactory.generatePrivate(keySpec);
    } catch (InvalidKeySpecException e) {
        throw new RsaException(e);
    }
    return privateKey;
}

From source file:com.fujitsu.dc.common.auth.token.TransCellAccessToken.java

/**
 * X509??.//from w  ww  .j av a2s.  co m
 * @param privateKeyFileName ???
 * @param certificateFileName ??
 * @param rootCertificateFileNames ??
 * @throws IOException IOException
 * @throws NoSuchAlgorithmException NoSuchAlgorithmException
 * @throws InvalidKeySpecException InvalidKeySpecException
 * @throws CertificateException CertificateException
 */
public static void configureX509(String privateKeyFileName, String certificateFileName,
        String[] rootCertificateFileNames)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException {

    xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");

    // Read RootCA Certificate
    x509RootCertificateFileNames = new ArrayList<String>();
    if (rootCertificateFileNames != null) {
        for (String fileName : rootCertificateFileNames) {
            x509RootCertificateFileNames.add(fileName);
        }
    }

    // Read Private Key
    InputStream is = null;
    if (privateKeyFileName == null) {
        is = TransCellAccessToken.class.getClassLoader()
                .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_KEY_PATH);
    } else {
        is = new FileInputStream(privateKeyFileName);
    }

    PEMReader privateKeyPemReader = new PEMReader(is);
    byte[] privateKeyDerBytes = privateKeyPemReader.getDerBytes();
    PKCS1EncodedKeySpec keySpecRSAPrivateKey = new PKCS1EncodedKeySpec(privateKeyDerBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    privKey = keyFactory.generatePrivate(keySpecRSAPrivateKey.getKeySpec());

    // Read Certificate
    if (certificateFileName == null) {
        is = TransCellAccessToken.class.getClassLoader()
                .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_CRT_PATH);
    } else {
        is = new FileInputStream(certificateFileName);
    }
    PEMReader serverCertificatePemReader;
    serverCertificatePemReader = new PEMReader(is);
    byte[] serverCertificateBytesCert = serverCertificatePemReader.getDerBytes();
    CertificateFactory cf = CertificateFactory.getInstance(X509KeySelector.X509KEY_TYPE);
    x509Certificate = (X509Certificate) cf
            .generateCertificate(new ByteArrayInputStream(serverCertificateBytesCert));

    // Create the KeyInfo containing the X509Data
    KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
    List x509Content = new ArrayList();
    x509Content.add(x509Certificate.getSubjectX500Principal().getName());
    x509Content.add(x509Certificate);
    X509Data xd = keyInfoFactory.newX509Data(x509Content);
    keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(xd));

    // http://java.sun.com/developer/technicalArticles/xml/dig_signature_api/

}

From source file:com.arm.connector.bridge.core.Utils.java

static public PrivateKey createPrivateKeyFromPEM(ErrorLogger logger, String pem, String algorithm) {
    try {/*from  ww  w  .  j a  va 2 s.  c  om*/
        String temp = Utils.escapeChars(pem);
        String privKeyPEM = temp.replace("-----BEGIN RSA PRIVATE KEY-----", "");
        privKeyPEM = privKeyPEM.replace("-----END RSA PRIVATE KEY-----", "");

        // DEBUG
        //logger.info("createPrivateKeyFromPEM: " + privKeyPEM);

        Base64 b64 = new Base64();
        byte[] decoded = b64.decode(privKeyPEM);

        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
        KeyFactory kf = KeyFactory.getInstance(algorithm);
        return kf.generatePrivate(spec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
        // exception caught
        logger.warning("createPrivateKeyFromPEM: Exception during private key gen", ex);
    }
    return null;
}

From source file:edu.vt.middleware.crypt.util.CryptReader.java

/**
 * Reads a DER-encoded private key in PKCS#8 format from an input stream into
 * a {@link PrivateKey} object. SSLeay-format keys may also work in some
 * cases; testing revealed SSLeay-format RSA keys generated by the OpenSSL rsa
 * command are supported./*from ww  w  . java2 s . co  m*/
 *
 * @param  keyStream  Input stream containing private key data.
 * @param  algorithm  Name of encryption algorithm used by key.
 *
 * @return  Private key containing data read from stream.
 *
 * @throws  CryptException  On key format errors.
 * @throws  IOException  On key read errors.
 */
public static PrivateKey readPrivateKey(final InputStream keyStream, final String algorithm)
        throws CryptException, IOException {
    final KeyFactory kf = CryptProvider.getKeyFactory(algorithm);
    try {
        final PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(readData(keyStream));
        return kf.generatePrivate(keysp);
    } catch (InvalidKeySpecException e) {
        throw new CryptException("Invalid private key format.", e);
    }
}

From source file:io.personium.common.auth.token.TransCellAccessToken.java

/**
 * X509??./*from   www  .  j  av  a2 s  .  c  o m*/
 * @param privateKeyFileName ???
 * @param certificateFileName ??
 * @param rootCertificateFileNames ??
 * @throws IOException IOException
 * @throws NoSuchAlgorithmException NoSuchAlgorithmException
 * @throws InvalidKeySpecException InvalidKeySpecException
 * @throws CertificateException CertificateException
 * @throws InvalidNameException InvalidNameException
 */
public static void configureX509(String privateKeyFileName, String certificateFileName,
        String[] rootCertificateFileNames) throws IOException, NoSuchAlgorithmException,
        InvalidKeySpecException, CertificateException, InvalidNameException {

    xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");

    // Read RootCA Certificate
    x509RootCertificateFileNames = new ArrayList<String>();
    if (rootCertificateFileNames != null) {
        for (String fileName : rootCertificateFileNames) {
            x509RootCertificateFileNames.add(fileName);
        }
    }

    // Read Private Key
    InputStream is = null;
    if (privateKeyFileName == null) {
        is = TransCellAccessToken.class.getClassLoader()
                .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_KEY_PATH);
    } else {
        is = new FileInputStream(privateKeyFileName);
    }

    PEMReader privateKeyPemReader = new PEMReader(is);
    byte[] privateKeyDerBytes = privateKeyPemReader.getDerBytes();
    PKCS1EncodedKeySpec keySpecRSAPrivateKey = new PKCS1EncodedKeySpec(privateKeyDerBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    privKey = keyFactory.generatePrivate(keySpecRSAPrivateKey.getKeySpec());

    // Read Certificate
    if (certificateFileName == null) {
        is = TransCellAccessToken.class.getClassLoader()
                .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_CRT_PATH);
    } else {
        is = new FileInputStream(certificateFileName);
    }
    PEMReader serverCertificatePemReader;
    serverCertificatePemReader = new PEMReader(is);
    byte[] serverCertificateBytesCert = serverCertificatePemReader.getDerBytes();
    CertificateFactory cf = CertificateFactory.getInstance(X509KeySelector.X509KEY_TYPE);
    x509Certificate = (X509Certificate) cf
            .generateCertificate(new ByteArrayInputStream(serverCertificateBytesCert));

    // Create the KeyInfo containing the X509Data
    KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
    List x509Content = new ArrayList();
    x509Content.add(x509Certificate.getSubjectX500Principal().getName());
    x509Content.add(x509Certificate);
    X509Data xd = keyInfoFactory.newX509Data(x509Content);
    keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(xd));

    // Get FQDN from Certificate and set FQDN to PersoniumCoreUtils
    String dn = x509Certificate.getSubjectX500Principal().getName();
    LdapName ln = new LdapName(dn);
    for (Rdn rdn : ln.getRdns()) {
        if (rdn.getType().equalsIgnoreCase("CN")) {
            PersoniumCoreUtils.setFQDN(rdn.getValue().toString());
            break;
        }
    }

    // http://java.sun.com/developer/technicalArticles/xml/dig_signature_api/

}

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

public static KeyPair loadKeyPair(String filename, String algorithm)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    // Read public key from file.
    FileInputStream keyfis = new FileInputStream(filename + ".pub");
    byte[] encodedPublicKey = new byte[keyfis.available()];
    keyfis.read(encodedPublicKey);//from  w  ww  . j  a v a2 s.  c  o  m
    keyfis.close();

    // Read private key from file.
    keyfis = new FileInputStream(filename);
    byte[] encodedPrivateKey = new byte[keyfis.available()];
    keyfis.read(encodedPrivateKey);
    keyfis.close();

    // Generate KeyPair from public and private keys.
    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    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:com.owncloud.android.utils.PushUtils.java

public static Key readKeyFromFile(boolean readPublicKey) {
    String keyPath = MainApp.getStoragePath() + File.separator + MainApp.getDataFolder() + File.separator
            + KEYPAIR_FOLDER;//from   www.  ja  va2 s .c  om

    String privateKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PRIV_EXTENSION;
    String publicKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PUB_EXTENSION;

    String path;

    if (readPublicKey) {
        path = publicKeyPath;
    } else {
        path = privateKeyPath;
    }

    FileInputStream fileInputStream = null;
    try {
        fileInputStream = new FileInputStream(path);
        byte[] bytes = new byte[fileInputStream.available()];
        fileInputStream.read(bytes);
        fileInputStream.close();

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        if (readPublicKey) {
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
            return keyFactory.generatePublic(keySpec);
        } else {
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
            return keyFactory.generatePrivate(keySpec);
        }

    } catch (FileNotFoundException e) {
        Log_OC.d(TAG, "Failed to find path while reading the Key");
    } catch (IOException e) {
        Log_OC.d(TAG, "IOException while reading the key");
    } catch (InvalidKeySpecException e) {
        Log_OC.d(TAG, "InvalidKeySpecException while reading the key");
    } catch (NoSuchAlgorithmException e) {
        Log_OC.d(TAG, "RSA algorithm not supported");
    }

    return null;
}

From source file:net.sf.keystore_explorer.crypto.privatekey.Pkcs8Util.java

/**
 * Load an unencrypted PKCS #8 private key from the stream. The encoding of
 * the private key may be PEM or DER./* w  ww .  j  a  v  a 2 s.co m*/
 *
 * @param is
 *            Stream to load the unencrypted private key from
 * @return The private key
 * @throws PrivateKeyEncryptedException
 *             If private key is encrypted
 * @throws CryptoException
 *             Problem encountered while loading the private key
 * @throws IOException
 *             If an I/O error occurred
 */
public static PrivateKey load(InputStream is) throws CryptoException, IOException {
    byte[] streamContents = ReadUtil.readFully(is);

    // Check pkcs #8 is unencrypted
    EncryptionType encType = getEncryptionType(new ByteArrayInputStream(streamContents));

    if (encType == null) {
        // Not a valid PKCS #8 private key
        throw new CryptoException(res.getString("NotValidPkcs8.exception.message"));
    }

    if (encType == ENCRYPTED) {
        throw new PrivateKeyEncryptedException(res.getString("Pkcs8IsEncrypted.exception.message"));
    }

    byte[] pvkBytes = null;
    // Check if stream is PEM encoded
    PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(streamContents));

    if (pemInfo != null) {
        // It is - get DER from PEM
        pvkBytes = pemInfo.getContent();
    }

    /*
     * If we haven't got the key bytes via PEM then just use stream
     * contents directly (assume it is DER encoded)
     */
    if (pvkBytes == null) {
        // Read in private key bytes
        pvkBytes = streamContents;
    }

    try {
        // Determine private key algorithm from key bytes
        String privateKeyAlgorithm = getPrivateKeyAlgorithm(pvkBytes);

        // Convert bytes to private key
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(pvkBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(privateKeyAlgorithm);
        PrivateKey pvk = keyFactory.generatePrivate(privateKeySpec);

        return pvk;
    } catch (NoSuchAlgorithmException ex) {
        throw new CryptoException(res.getString("NoLoadPkcs8PrivateKey.exception.message"), ex);
    } catch (InvalidKeySpecException ex) {
        throw new CryptoException(res.getString("NoLoadPkcs8PrivateKey.exception.message"), ex);
    }
}