Java Code Examples for javax.crypto.EncryptedPrivateKeyInfo#getKeySpec()

The following examples show how to use javax.crypto.EncryptedPrivateKeyInfo#getKeySpec() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KeyCertLoader.java    From WeCross with Apache License 2.0 6 votes vote down vote up
PKCS8EncodedKeySpec generateKeySpec(char[] password, byte[] key)
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException,
                InvalidKeySpecException, InvalidKeyException,
                InvalidAlgorithmParameterException {

    if (password == null) {
        return new PKCS8EncodedKeySpec(key);
    }

    EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(key);
    SecretKeyFactory keyFactory =
            SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName());
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);

    Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName());
    cipher.init(Cipher.DECRYPT_MODE, pbeKey, encryptedPrivateKeyInfo.getAlgParameters());

    return encryptedPrivateKeyInfo.getKeySpec(cipher);
}
 
Example 2
Source File: PrivateKeyEventDecryptor.java    From xyz-hub with Apache License 2.0 6 votes vote down vote up
/**
 * This method decrypts the private key that was encrypted using PKCS#8 scheme.
 *
 * @param pkcs8Data The private key in PEM format without header and footer.
 * @param passphrase The passphrase for decrypting the private key.
 * @return Returns the {@link PrivateKey} or null if there a problem.
 */
public static PrivateKey decryptPrivateKey(final String pkcs8Data, final String passphrase) {
  if (passphrase == null || pkcs8Data == null) {
    logger.error("Could not create private key because passphrase or key is null");
    return null;
  }
  try {
    PBEKeySpec pbeSpec = new PBEKeySpec(passphrase.toCharArray());
    EncryptedPrivateKeyInfo pkinfo = new EncryptedPrivateKeyInfo(Base64.getDecoder().decode(pkcs8Data.getBytes(UTF_8)));
    SecretKeyFactory skf = SecretKeyFactory.getInstance(pkinfo.getAlgName());
    Key secret = skf.generateSecret(pbeSpec);
    PKCS8EncodedKeySpec keySpec = pkinfo.getKeySpec(secret);
    KeyFactory keyFactory = KeyFactory.getInstance(RSA);
    return keyFactory.generatePrivate(keySpec);
  } catch (Exception e) {
    logger.error("Could not create encrypted private key from environment variable", e);
    return null;
  }
}
 
Example 3
Source File: SslContext.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a key specification for an (encrypted) private key.为(加密的)私钥生成密钥规范。
 *
 * @param password characters, if {@code null} an unencrypted key is assumed
 * @param key bytes of the DER encoded private key
 *
 * @return a key specification
 *
 * @throws IOException if parsing {@code key} fails
 * @throws NoSuchAlgorithmException if the algorithm used to encrypt {@code key} is unknown
 * @throws NoSuchPaddingException if the padding scheme specified in the decryption algorithm is unknown
 * @throws InvalidKeySpecException if the decryption key based on {@code password} cannot be generated
 * @throws InvalidKeyException if the decryption key based on {@code password} cannot be used to decrypt
 *                             {@code key}
 * @throws InvalidAlgorithmParameterException if decryption algorithm parameters are somehow faulty
 */
protected static PKCS8EncodedKeySpec generateKeySpec(char[] password, byte[] key)
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException,
        InvalidKeyException, InvalidAlgorithmParameterException {

    if (password == null) {
        return new PKCS8EncodedKeySpec(key);
    }

    EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(key);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName());
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);

    Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName());
    cipher.init(Cipher.DECRYPT_MODE, pbeKey, encryptedPrivateKeyInfo.getAlgParameters());

    return encryptedPrivateKeyInfo.getKeySpec(cipher);
}
 
Example 4
Source File: Algorithm.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] argv) throws Exception {
    EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo(
            Base64.getMimeDecoder().decode(PKCS8PrivateKey));
    PBEKeySpec pks = new PBEKeySpec(password.toCharArray());
    SecretKeyFactory skf = SecretKeyFactory.getInstance(epki.getAlgName());
    SecretKey sk = skf.generateSecret(pks);
    PKCS8EncodedKeySpec keySpec = epki.getKeySpec(sk);

    // Get the key algorithm and make sure it's what we expect
    String alg = keySpec.getAlgorithm();
    if (!alg.equals(keyAlg)) {
        throw new Exception("Expected: " + keyAlg + ", Got: " + alg);
    }

    System.out.println("Test passed");
}
 
Example 5
Source File: KeyPairSnowflakeCredentials.java    From beam with Apache License 2.0 6 votes vote down vote up
private PrivateKey getPrivateKey(String privateKeyPath, String privateKeyPassphrase) {
  try {
    byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyPath));

    String encrypted = new String(keyBytes, Charset.defaultCharset());
    encrypted = encrypted.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----", "");
    encrypted = encrypted.replace("-----END ENCRYPTED PRIVATE KEY-----", "");
    EncryptedPrivateKeyInfo pkInfo =
        new EncryptedPrivateKeyInfo(Base64.getMimeDecoder().decode(encrypted));
    PBEKeySpec keySpec = new PBEKeySpec(privateKeyPassphrase.toCharArray());
    SecretKeyFactory pbeKeyFactory = SecretKeyFactory.getInstance(pkInfo.getAlgName());
    PKCS8EncodedKeySpec encodedKeySpec = pkInfo.getKeySpec(pbeKeyFactory.generateSecret(keySpec));

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePrivate(encodedKeySpec);
  } catch (IOException
      | NoSuchAlgorithmException
      | InvalidKeySpecException
      | InvalidKeyException ex) {
    throw new RuntimeException("Can't create PrivateKey from options");
  }
}
 
Example 6
Source File: SslContext.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a key specification for an (encrypted) private key.
 *
 * @param password characters, if {@code null} or empty an unencrypted key is assumed
 * @param key bytes of the DER encoded private key
 *
 * @return a key specification
 *
 * @throws IOException if parsing {@code key} fails
 * @throws NoSuchAlgorithmException if the algorithm used to encrypt {@code key} is unkown
 * @throws NoSuchPaddingException if the padding scheme specified in the decryption algorithm is unkown
 * @throws InvalidKeySpecException if the decryption key based on {@code password} cannot be generated
 * @throws InvalidKeyException if the decryption key based on {@code password} cannot be used to decrypt
 *                             {@code key}
 * @throws InvalidAlgorithmParameterException if decryption algorithm parameters are somehow faulty
 */
protected static PKCS8EncodedKeySpec generateKeySpec(char[] password, byte[] key)
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException,
        InvalidKeyException, InvalidAlgorithmParameterException {

    if (password == null || password.length == 0) {
        return new PKCS8EncodedKeySpec(key);
    }

    EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(key);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName());
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);

    Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName());
    cipher.init(Cipher.DECRYPT_MODE, pbeKey, encryptedPrivateKeyInfo.getAlgParameters());

    return encryptedPrivateKeyInfo.getKeySpec(cipher);
}
 
Example 7
Source File: SecurityUtils.java    From RISE-V2G with MIT License 5 votes vote down vote up
/**
 * Reads the private key from an encrypted PKCS#8 file and returns it as an ECPrivateKey instance.
 * 
 * ----- !! IMPORTANT NOTE!! -----
 * The PKCS#8 key file must be encrypted using a PKCS#12 encryption scheme, since JCE parsing of Pbes2Parameters (as defined in PKCS#5) 
 * is buggy in Java 1.8, see also https://bugs.openjdk.java.net/browse/JDK-8076999. The bug results in an IOException when trying to 
 * instantiate the EncryptedPrivateKeyInfo class.
 * 
 * The OpenSSL command used to create the DER-encoded and encrypted PKCS#8 file needs to use the 'v1 alg' option, specifying a proper algorithm. 
 * Example: '-v1 PBE-SHA1-3DES' (see https://www.openssl.org/docs/man1.0.2/man1/openssl-pkcs8.html).
 * -----
 * 
 * @param A PKCS#8 (.key) file containing the private key with value "s"
 * @return The private key as an ECPrivateKey instance
 */
public static ECPrivateKey getPrivateKey(String keyFilePath) {
	Path fileLocation = Paths.get(keyFilePath);
	byte[] pkcs8ByteArray;
	
	try {
		pkcs8ByteArray = Files.readAllBytes(fileLocation);
		
		// Get the password that was used to encrypt the private key
		PBEKeySpec password = new PBEKeySpec(GlobalValues.PASSPHRASE_FOR_CERTIFICATES_AND_KEYS.toString().toCharArray());
		
		// Read the ASN.1 structure of the PKCS#8 DER-encoded file
	    EncryptedPrivateKeyInfo encryptedPrivKeyInfo = new EncryptedPrivateKeyInfo(pkcs8ByteArray);
	    
	    // Instantiate the key factory which will create the symmetric (secret) key using algorithm that is encoded in the ASN.1 structure 
	    // (see 'v1 alg' in OpenSSL's pkcs8 command) and the given password
	    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(encryptedPrivKeyInfo.getAlgName());
	    
	    // Create the symmetric key from the given password
	    Key decryptKey = secretKeyFactory.generateSecret(password);
	    
	    // Extract the PKCS8EncodedKeySpec object from the encrypted data
	    PKCS8EncodedKeySpec pkcs8PrivKeySpec = encryptedPrivKeyInfo.getKeySpec(decryptKey);
	    
	    // Generate the EC private key
		ECPrivateKey privateKey = (ECPrivateKey) KeyFactory.getInstance("EC").generatePrivate(pkcs8PrivKeySpec);

		return privateKey;
	} catch (IOException | InvalidKeySpecException | NoSuchAlgorithmException | InvalidKeyException e) {
		getLogger().error(e.getClass().getSimpleName() + " occurred while trying to access private key at " +
				  "location '" + keyFilePath + "'");
		e.printStackTrace();
		return null;
	} 
}