javax.crypto.EncryptedPrivateKeyInfo Java Examples

The following examples show how to use javax.crypto.EncryptedPrivateKeyInfo. 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: 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 #2
Source File: JKS.java    From fdroidclient with GNU General Public License v3.0 6 votes vote down vote up
public void engineSetKeyEntry(String alias, byte[] encodedKey, Certificate[] certChain)
        throws KeyStoreException {
    alias = alias.toLowerCase(Locale.ENGLISH);
    if (trustedCerts.containsKey(alias))
        throw new KeyStoreException("\"" + alias + "\" is a trusted certificate entry");
    try {
        new EncryptedPrivateKeyInfo(encodedKey);
    } catch (IOException ioe) {
        throw new KeyStoreException("encoded key is not an EncryptedPrivateKeyInfo");
    }
    privateKeys.put(alias, encodedKey);
    if (certChain != null)
        certChains.put(alias, certChain);
    else
        certChains.put(alias, new Certificate[0]);
    if (!aliases.contains(alias)) {
        dates.put(alias, new Date());
        aliases.add(alias);
    }
}
 
Example #3
Source File: OidFormat.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
static void testBad(String s) throws Exception {
    System.err.println("Trying " + s);
    try {
        new ObjectIdentifier(s);
        throw new Exception("should be invalid ObjectIdentifier");
    } catch (IOException ioe) {
        System.err.println(ioe);
    }

    try {
        new Oid(s);
        throw new Exception("should be invalid Oid");
    } catch (GSSException gsse) {
        ;
    }

    try {
        new EncryptedPrivateKeyInfo(s, new byte[8]);
        throw new Exception("should be invalid algorithm");
    } catch (NoSuchAlgorithmException e) {
        ;
    }
}
 
Example #4
Source File: OidFormat.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
static void testBad(String s) throws Exception {
    System.err.println("Trying " + s);
    try {
        new ObjectIdentifier(s);
        throw new Exception("should be invalid ObjectIdentifier");
    } catch (IOException ioe) {
        System.err.println(ioe);
    }

    try {
        new Oid(s);
        throw new Exception("should be invalid Oid");
    } catch (GSSException gsse) {
        ;
    }

    try {
        new EncryptedPrivateKeyInfo(s, new byte[8]);
        throw new Exception("should be invalid algorithm");
    } catch (NoSuchAlgorithmException e) {
        ;
    }
}
 
Example #5
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 #6
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 #7
Source File: OidFormat.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
static void testBad(String s) throws Exception {
    System.err.println("Trying " + s);
    try {
        new ObjectIdentifier(s);
        throw new Exception("should be invalid ObjectIdentifier");
    } catch (IOException ioe) {
        System.err.println(ioe);
    }

    try {
        new Oid(s);
        throw new Exception("should be invalid Oid");
    } catch (GSSException gsse) {
        ;
    }

    try {
        new EncryptedPrivateKeyInfo(s, new byte[8]);
        throw new Exception("should be invalid algorithm");
    } catch (NoSuchAlgorithmException e) {
        ;
    }
}
 
Example #8
Source File: OidFormat.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
static void testBad(String s) throws Exception {
    System.err.println("Trying " + s);
    try {
        new ObjectIdentifier(s);
        throw new Exception("should be invalid ObjectIdentifier");
    } catch (IOException ioe) {
        System.err.println(ioe);
    }

    try {
        new Oid(s);
        throw new Exception("should be invalid Oid");
    } catch (GSSException gsse) {
        ;
    }

    try {
        new EncryptedPrivateKeyInfo(s, new byte[8]);
        throw new Exception("should be invalid algorithm");
    } catch (NoSuchAlgorithmException e) {
        ;
    }
}
 
Example #9
Source File: OidFormat.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
static void testBad(String s) throws Exception {
    System.err.println("Trying " + s);
    try {
        new ObjectIdentifier(s);
        throw new Exception("should be invalid ObjectIdentifier");
    } catch (IOException ioe) {
        System.err.println(ioe);
    }

    try {
        new Oid(s);
        throw new Exception("should be invalid Oid");
    } catch (GSSException gsse) {
        ;
    }

    try {
        new EncryptedPrivateKeyInfo(s, new byte[8]);
        throw new Exception("should be invalid algorithm");
    } catch (NoSuchAlgorithmException e) {
        ;
    }
}
 
Example #10
Source File: OidFormat.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
static void testBad(String s) throws Exception {
    System.err.println("Trying " + s);
    try {
        new ObjectIdentifier(s);
        throw new Exception("should be invalid ObjectIdentifier");
    } catch (IOException ioe) {
        System.err.println(ioe);
    }

    try {
        new Oid(s);
        throw new Exception("should be invalid Oid");
    } catch (GSSException gsse) {
        ;
    }

    try {
        new EncryptedPrivateKeyInfo(s, new byte[8]);
        throw new Exception("should be invalid algorithm");
    } catch (NoSuchAlgorithmException e) {
        ;
    }
}
 
Example #11
Source File: OidFormat.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
static void testBad(String s) throws Exception {
    System.err.println("Trying " + s);
    try {
        new ObjectIdentifier(s);
        throw new Exception("should be invalid ObjectIdentifier");
    } catch (IOException ioe) {
        System.err.println(ioe);
    }

    try {
        new Oid(s);
        throw new Exception("should be invalid Oid");
    } catch (GSSException gsse) {
        ;
    }

    try {
        new EncryptedPrivateKeyInfo(s, new byte[8]);
        throw new Exception("should be invalid algorithm");
    } catch (NoSuchAlgorithmException e) {
        ;
    }
}
 
Example #12
Source File: OidFormat.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
static void testBad(String s) throws Exception {
    System.err.println("Trying " + s);
    try {
        new ObjectIdentifier(s);
        throw new Exception("should be invalid ObjectIdentifier");
    } catch (IOException ioe) {
        System.err.println(ioe);
    }

    try {
        new Oid(s);
        throw new Exception("should be invalid Oid");
    } catch (GSSException gsse) {
        ;
    }

    try {
        new EncryptedPrivateKeyInfo(s, new byte[8]);
        throw new Exception("should be invalid algorithm");
    } catch (NoSuchAlgorithmException e) {
        ;
    }
}
 
Example #13
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 #14
Source File: OidFormat.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
static void testBad(String s) throws Exception {
    System.err.println("Trying " + s);
    try {
        new ObjectIdentifier(s);
        throw new Exception("should be invalid ObjectIdentifier");
    } catch (IOException ioe) {
        System.err.println(ioe);
    }

    try {
        new Oid(s);
        throw new Exception("should be invalid Oid");
    } catch (GSSException gsse) {
        ;
    }

    try {
        new EncryptedPrivateKeyInfo(s, new byte[8]);
        throw new Exception("should be invalid algorithm");
    } catch (NoSuchAlgorithmException e) {
        ;
    }
}
 
Example #15
Source File: OidFormat.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
static void testBad(String s) throws Exception {
    System.err.println("Trying " + s);
    try {
        new ObjectIdentifier(s);
        throw new Exception("should be invalid ObjectIdentifier");
    } catch (IOException ioe) {
        System.err.println(ioe);
    }

    try {
        new Oid(s);
        throw new Exception("should be invalid Oid");
    } catch (GSSException gsse) {
        ;
    }

    try {
        new EncryptedPrivateKeyInfo(s, new byte[8]);
        throw new Exception("should be invalid algorithm");
    } catch (NoSuchAlgorithmException e) {
        ;
    }
}
 
Example #16
Source File: JKS.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
public void engineSetKeyEntry(String alias, byte[] encodedKey, Certificate[] certChain)
    throws KeyStoreException
{
    alias = alias.toLowerCase();
    if (trustedCerts.containsKey(alias))
        throw new KeyStoreException("\"" + alias + "\" is a trusted certificate entry");
    try
    {
        new EncryptedPrivateKeyInfo(encodedKey);
    }
    catch (IOException ioe)
    {
        throw new KeyStoreException("encoded key is not an EncryptedPrivateKeyInfo");
    }
    privateKeys.put(alias, encodedKey);
    if (certChain != null)
        certChains.put(alias, certChain);
    else
        certChains.put(alias, new Certificate[0]);
    if (!aliases.contains(alias))
    {
        dates.put(alias, new Date());
        aliases.add(alias);
    }
}
 
Example #17
Source File: OidFormat.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
static void testBad(String s) throws Exception {
    System.err.println("Trying " + s);
    try {
        new ObjectIdentifier(s);
        throw new Exception("should be invalid ObjectIdentifier");
    } catch (IOException ioe) {
        System.err.println(ioe);
    }

    try {
        new Oid(s);
        throw new Exception("should be invalid Oid");
    } catch (GSSException gsse) {
        ;
    }

    try {
        new EncryptedPrivateKeyInfo(s, new byte[8]);
        throw new Exception("should be invalid algorithm");
    } catch (NoSuchAlgorithmException e) {
        ;
    }
}
 
Example #18
Source File: OidFormat.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
static void testBad(String s) throws Exception {
    System.err.println("Trying " + s);
    try {
        new ObjectIdentifier(s);
        throw new Exception("should be invalid ObjectIdentifier");
    } catch (IOException ioe) {
        System.err.println(ioe);
    }

    try {
        new Oid(s);
        throw new Exception("should be invalid Oid");
    } catch (GSSException gsse) {
        ;
    }

    try {
        new EncryptedPrivateKeyInfo(s, new byte[8]);
        throw new Exception("should be invalid algorithm");
    } catch (NoSuchAlgorithmException e) {
        ;
    }
}
 
Example #19
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 #20
Source File: OidFormat.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
static void testBad(String s) throws Exception {
    System.err.println("Trying " + s);
    try {
        new ObjectIdentifier(s);
        throw new Exception("should be invalid ObjectIdentifier");
    } catch (IOException ioe) {
        System.err.println(ioe);
    }

    try {
        new Oid(s);
        throw new Exception("should be invalid Oid");
    } catch (GSSException gsse) {
        ;
    }

    try {
        new EncryptedPrivateKeyInfo(s, new byte[8]);
        throw new Exception("should be invalid algorithm");
    } catch (NoSuchAlgorithmException e) {
        ;
    }
}
 
Example #21
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 #22
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;
	} 
}
 
Example #23
Source File: JKS.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
private static byte[] encryptKey(Key key, byte[] passwd)
    throws KeyStoreException
{
    try
    {
        MessageDigest sha = MessageDigest.getInstance("SHA1");
        SecureRandom rand = SecureRandom.getInstance("SHA1PRNG");
        byte[] k = key.getEncoded();
        byte[] encrypted = new byte[k.length + 40];
        byte[] keystream = rand.getSeed(20);
        System.arraycopy(keystream, 0, encrypted, 0, 20);
        int count = 0;
        while (count < k.length)
        {
            sha.reset();
            sha.update(passwd);
            sha.update(keystream);
            sha.digest(keystream, 0, keystream.length);
            for (int i = 0; i < keystream.length && count < k.length; i++)
            {
                encrypted[count+20] = (byte) (keystream[i] ^ k[count]);
                count++;
            }
        }
        sha.reset();
        sha.update(passwd);
        sha.update(k);
        sha.digest(encrypted, encrypted.length - 20, 20);
        // 1.3.6.1.4.1.42.2.17.1.1 is Sun's private OID for this
        // encryption algorithm.
        return new EncryptedPrivateKeyInfo("1.3.6.1.4.1.42.2.17.1.1",
            encrypted).getEncoded();
    }
    catch (Exception x)
    {
        throw new KeyStoreException(x.getMessage());
    }
}
 
Example #24
Source File: JKS.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
private static byte[] decryptKey(byte[] encryptedPKI, byte[] passwd)
    throws UnrecoverableKeyException
{
    try
    {
        EncryptedPrivateKeyInfo epki =
            new EncryptedPrivateKeyInfo(encryptedPKI);
        byte[] encr = epki.getEncryptedData();
        byte[] keystream = new byte[20];
        System.arraycopy(encr, 0, keystream, 0, 20);
        byte[] check = new byte[20];
        System.arraycopy(encr, encr.length-20, check, 0, 20);
        byte[] key = new byte[encr.length - 40];
        MessageDigest sha = MessageDigest.getInstance("SHA1");
        int count = 0;
        while (count < key.length)
        {
            sha.reset();
            sha.update(passwd);
            sha.update(keystream);
            sha.digest(keystream, 0, keystream.length);
            for (int i = 0; i < keystream.length && count < key.length; i++)
            {
                key[count] = (byte) (keystream[i] ^ encr[count+20]);
                count++;
            }
        }
        sha.reset();
        sha.update(passwd);
        sha.update(key);
        if (!MessageDigest.isEqual(check, sha.digest()))
            throw new UnrecoverableKeyException("checksum mismatch");
        return key;
    }
    catch (Exception x)
    {
        throw new UnrecoverableKeyException(x.getMessage());
    }
}
 
Example #25
Source File: Pkcs8Util.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * PKCS #8 encode and encrypt a private key.
 *
 * @return The encrypted encoding
 * @param privateKey
 *            The private key
 * @param pbeType
 *            PBE algorithm to use for encryption
 * @param password
 *            Encryption password
 * @throws CryptoException
 *             Problem encountered while getting the encoded private key
 * @throws IOException
 *             If an I/O error occurred
 */
public static byte[] getEncrypted(PrivateKey privateKey, Pkcs8PbeType pbeType, Password password)
		throws CryptoException, IOException {
	try {
		byte[] pkcs8 = get(privateKey);

		// Generate PBE secret key from password
		SecretKeyFactory keyFact = SecretKeyFactory.getInstance(pbeType.jce());
		PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
		SecretKey pbeKey = keyFact.generateSecret(pbeKeySpec);

		// Generate random salt and iteration count
		byte[] salt = generateSalt();
		int iterationCount = generateIterationCount();

		// Store in algorithm parameters
		PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, iterationCount);
		AlgorithmParameters params = AlgorithmParameters.getInstance(pbeType.jce());
		params.init(pbeParameterSpec);

		// Create PBE cipher from key and params
		Cipher cipher = Cipher.getInstance(pbeType.jce());
		cipher.init(Cipher.ENCRYPT_MODE, pbeKey, params);

		// Encrypt key
		byte[] encPkcs8 = cipher.doFinal(pkcs8);

		// Create and return encrypted private key information
		EncryptedPrivateKeyInfo encPrivateKeyInfo = new EncryptedPrivateKeyInfo(params, encPkcs8);

		return encPrivateKeyInfo.getEncoded();
	} catch (GeneralSecurityException ex) {
		throw new CryptoException("NoEncryptPkcs8PrivateKey.exception.message", ex);
	}
}
 
Example #26
Source File: JKS.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
private static byte[] decryptKey(byte[] encryptedPKI, byte[] passwd)
        throws UnrecoverableKeyException {
    try {
        EncryptedPrivateKeyInfo epki =
                new EncryptedPrivateKeyInfo(encryptedPKI);
        byte[] encr = epki.getEncryptedData();
        byte[] keystream = new byte[20];
        System.arraycopy(encr, 0, keystream, 0, 20);
        byte[] check = new byte[20];
        System.arraycopy(encr, encr.length - 20, check, 0, 20);
        byte[] key = new byte[encr.length - 40];
        MessageDigest sha = MessageDigest.getInstance("SHA1");
        int count = 0;
        while (count < key.length) {
            sha.reset();
            sha.update(passwd);
            sha.update(keystream);
            sha.digest(keystream, 0, keystream.length);
            for (int i = 0; i < keystream.length && count < key.length; i++) {
                key[count] = (byte) (keystream[i] ^ encr[count + 20]);
                count++;
            }
        }
        sha.reset();
        sha.update(passwd);
        sha.update(key);
        if (!MessageDigest.isEqual(check, sha.digest()))
            throw new UnrecoverableKeyException("checksum mismatch");
        return key;
    } catch (Exception x) {
        throw new UnrecoverableKeyException(x.getMessage());
    }
}
 
Example #27
Source File: JKS.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
private static byte[] encryptKey(Key key, byte[] passwd)
        throws KeyStoreException {
    try {
        MessageDigest sha = MessageDigest.getInstance("SHA1");
        SecureRandom rand = SecureRandom.getInstance("SHA1PRNG");
        byte[] k = key.getEncoded();
        byte[] encrypted = new byte[k.length + 40];
        byte[] keystream = rand.getSeed(20);
        System.arraycopy(keystream, 0, encrypted, 0, 20);
        int count = 0;
        while (count < k.length) {
            sha.reset();
            sha.update(passwd);
            sha.update(keystream);
            sha.digest(keystream, 0, keystream.length);
            for (int i = 0; i < keystream.length && count < k.length; i++) {
                encrypted[count + 20] = (byte) (keystream[i] ^ k[count]);
                count++;
            }
        }
        sha.reset();
        sha.update(passwd);
        sha.update(k);
        sha.digest(encrypted, encrypted.length - 20, 20);
        // 1.3.6.1.4.1.42.2.17.1.1 is Sun's private OID for this
        // encryption algorithm.
        return new EncryptedPrivateKeyInfo("1.3.6.1.4.1.42.2.17.1.1",
                encrypted).getEncoded();
    } catch (Exception x) {
        throw new KeyStoreException(x.getMessage());
    }
}