Example usage for javax.crypto EncryptedPrivateKeyInfo getAlgName

List of usage examples for javax.crypto EncryptedPrivateKeyInfo getAlgName

Introduction

In this page you can find the example usage for javax.crypto EncryptedPrivateKeyInfo getAlgName.

Prototype

public String getAlgName() 

Source Link

Document

Returns the encryption algorithm.

Usage

From source file:com.adeptj.modules.security.jwt.internal.JwtKeys.java

static PrivateKey createSigningKey(JwtConfig jwtConfig, SignatureAlgorithm signatureAlgo) {
    LOGGER.info("Creating RSA signing key!!");
    String keyData = jwtConfig.privateKey();
    Assert.isTrue(StringUtils.startsWithAny(keyData, PRIVATE_ENCRYPTED_KEY_HEADER, PRIVATE_KEY_HEADER),
            INVALID_PRIVATE_KEY_MSG);//from   www.j  a  v a2  s  . c  o m
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(signatureAlgo.getFamilyName());
        if (StringUtils.startsWith(keyData, PRIVATE_ENCRYPTED_KEY_HEADER)) {
            LOGGER.info("Creating PKCS8EncodedKeySpec from private [encrypted] key !!");
            Assert.hasText(jwtConfig.privateKeyPassword(), KEYPASS_NULL_MSG);
            byte[] privateKeyData = decodePrivateKeyData(keyData, true);
            EncryptedPrivateKeyInfo privateKeyInfo = new EncryptedPrivateKeyInfo(privateKeyData);
            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(privateKeyInfo.getAlgName());
            PBEKeySpec keySpec = new PBEKeySpec(jwtConfig.privateKeyPassword().toCharArray());
            SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
            Cipher cipher = Cipher.getInstance(privateKeyInfo.getAlgName());
            cipher.init(DECRYPT_MODE, secretKey, privateKeyInfo.getAlgParameters());
            return keyFactory.generatePrivate(privateKeyInfo.getKeySpec(cipher));
        }
        LOGGER.info("Creating PKCS8EncodedKeySpec from private key !!");
        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(decodePrivateKeyData(keyData, false)));
    } catch (GeneralSecurityException | IOException ex) {
        LOGGER.error(ex.getMessage(), ex);
        throw new KeyInitializationException(ex.getMessage(), ex);
    }
}

From source file:Main.java

private static PKCS8EncodedKeySpec decryptPrivateKey(byte[] encryptedPrivateKey)
        throws GeneralSecurityException {
    EncryptedPrivateKeyInfo epkInfo;
    try {//from  w  w  w  .  j  a v  a 2  s  .c o m
        epkInfo = new EncryptedPrivateKeyInfo(encryptedPrivateKey);
    } catch (IOException ex) {
        // Probably not an encrypted key.
        return null;
    }

    char[] password = System.console().readPassword("Password for the private key file: ");

    SecretKeyFactory skFactory = SecretKeyFactory.getInstance(epkInfo.getAlgName());
    Key key = skFactory.generateSecret(new PBEKeySpec(password));
    Arrays.fill(password, '\0');

    Cipher cipher = Cipher.getInstance(epkInfo.getAlgName());
    cipher.init(Cipher.DECRYPT_MODE, key, epkInfo.getAlgParameters());

    try {
        return epkInfo.getKeySpec(cipher);
    } catch (InvalidKeySpecException ex) {
        System.err.println("Password may be bad.");
        throw ex;
    }
}

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

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

    // Check pkcs #8 is not 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 == UNENCRYPTED) {
        throw new PrivateKeyUnencryptedException(res.getString("Pkcs8IsUnencrypted.exception.message"));
    }

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

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

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

    try {
        // Create encrypted private key information from bytes
        EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo(encPvk);

        // Get wrapping algorithm
        String encAlg = epki.getAlgName();

        // Check algorithm is supported
        if (!checkSupportedForDecrypt(encAlg)) {
            throw new PrivateKeyPbeNotSupportedException(encAlg, MessageFormat
                    .format(res.getString("PrivateKeyWrappingAlgUnsupported.exception.message"), encAlg));
        }

        // Create algorithm parameters and decryption key
        AlgorithmParameters encAlgParams = epki.getAlgParameters();
        PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
        SecretKeyFactory keyFact = SecretKeyFactory.getInstance(encAlg);
        SecretKey pbeKey = keyFact.generateSecret(pbeKeySpec);

        // Create cipher to create
        Cipher cipher = Cipher.getInstance(encAlg);

        // Do decryption
        cipher.init(Cipher.DECRYPT_MODE, pbeKey, encAlgParams);
        PKCS8EncodedKeySpec privateKeySpec = epki.getKeySpec(cipher);

        // Get encoding of private key
        byte[] pvkBytes = privateKeySpec.getEncoded();

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

        // Use Key Factory to create private key from encoding
        KeyFactory keyFactory = KeyFactory.getInstance(privateKeyAlgorithm);
        PrivateKey pvk = keyFactory.generatePrivate(privateKeySpec);

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

From source file:com.jrummyapps.busybox.signing.ZipSigner.java

/**
 * Decrypt an encrypted PKCS 8 format private key.
 *
 * Based on ghstark's post on Aug 6, 2006 at
 * http://forums.sun.com/thread.jspa?threadID=758133&messageID=4330949
 *
 * @param encryptedPrivateKey/*ww  w. j a  v  a2s  .co  m*/
 *     The raw data of the private key
 */
private static KeySpec decryptPrivateKey(final byte[] encryptedPrivateKey) throws GeneralSecurityException {
    EncryptedPrivateKeyInfo epkInfo;
    try {
        epkInfo = new EncryptedPrivateKeyInfo(encryptedPrivateKey);
    } catch (final IOException ex) {
        // Probably not an encrypted key.
        return null;
    }

    final String pass = "android";
    final char[] password = pass.toCharArray();
    final SecretKeyFactory skFactory = SecretKeyFactory.getInstance(epkInfo.getAlgName());
    final Key key = skFactory.generateSecret(new PBEKeySpec(password));
    final Cipher cipher = Cipher.getInstance(epkInfo.getAlgName());
    cipher.init(Cipher.DECRYPT_MODE, key, epkInfo.getAlgParameters());

    try {
        return epkInfo.getKeySpec(cipher);
    } catch (final InvalidKeySpecException ex) {
        Log.e(TAG, "Password for keyFile may be bad.", ex);
        return null;
    }
}

From source file:org.casbah.provider.KeyHelper.java

public static PrivateKey readKey(String keypass, byte[] keyData) throws CAProviderException {
    try {//from w  ww.  j av  a  2  s  .  co  m
        EncryptedPrivateKeyInfo pkInfo = new EncryptedPrivateKeyInfo(keyData);
        PBEKeySpec keySpec = new PBEKeySpec(keypass.toCharArray());
        SecretKeyFactory pbeKeyFactory = SecretKeyFactory.getInstance(pkInfo.getAlgName());
        PKCS8EncodedKeySpec encodedKeySpec = pkInfo.getKeySpec(pbeKeyFactory.generateSecret(keySpec));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPrivateCrtKey) keyFactory.generatePrivate(encodedKeySpec);
    } catch (Exception e) {
        throw new CAProviderException("Could not decode private key", e);
    }

}

From source file:org.tolven.config.model.CredentialManager.java

private PrivateKey getDERPrivateKey(CertificateKeyDetail keyDetail, char[] password)
        throws IOException, GeneralSecurityException {
    File privateKeyFile = new File(keyDetail.getSource());
    if (!privateKeyFile.exists()) {
        throw new RuntimeException("Cannot find PrivateKey file: " + privateKeyFile.getPath());
    }//w  w w .  j a  v a 2  s  .c o m
    byte[] privateKey = FileUtils.readFileToByteArray(privateKeyFile);
    EncryptedPrivateKeyInfo encryptedKeyInfo = new EncryptedPrivateKeyInfo(privateKey);
    AlgorithmParameters params = encryptedKeyInfo.getAlgParameters();
    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(encryptedKeyInfo.getAlgName());
    PBEKeySpec passwordSpec = new PBEKeySpec(password);
    SecretKey secretKey = secretKeyFactory.generateSecret(passwordSpec);
    Cipher cipher = Cipher.getInstance(encryptedKeyInfo.getAlgName());
    cipher.init(Cipher.DECRYPT_MODE, secretKey, params);
    PKCS8EncodedKeySpec keySpec = encryptedKeyInfo.getKeySpec(cipher);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePrivate(keySpec);
}