等效的openssl命令来加密密码

时间:2015-12-22 16:17:30

标签: java encryption openssl

我有一个Java库来读取和解密密码。我按照它如何读取密码来生成密码文件,它工作正常。现在我想弄清楚如何使用openssl命令生成密码文件,因为这是我们支持使用的标准。我无法使用openssl找出正确的命令来完成这项工作。

这是我生成密码文件的测试代码。它工作正常。

import org.apache.commons.io.IOUtils;

public class CryptoTest extends TestCase {

    public void testEncryption() throws Exception {

        String DEFAULT_ALG = "AES/ECB/PKCS5Padding";
        String DEFAULT_SALT = "SALT";
        int DEFAULT_ITERATIONS = 10000;
        int DEFAULT_KEY_LEN = 128;

        String alg = DEFAULT_ALG;
        String salt = DEFAULT_SALT;
        int iterations = DEFAULT_ITERATIONS;
        int keyLen = DEFAULT_KEY_LEN;

        SecretKeyFactory factory = null;
        String passPhrase = "password";
        String algOnly = alg.split("/")[0];
        String password = "CDE#VFR$";

        try {
            factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        } catch (NoSuchAlgorithmException e) {
            throw new IOException("Can't load SecretKeyFactory", e);
        }

        SecretKeySpec key = null;
        try {
            key = new SecretKeySpec(
                    factory.generateSecret(
                            new PBEKeySpec(passPhrase.toCharArray(), salt.getBytes(), iterations, keyLen)).getEncoded(),
                    algOnly);
        } catch (Exception e) {
            throw new IOException("Can't generate secret key", e);
        }

        Cipher crypto = null;

        try {
            crypto = Cipher.getInstance(alg);
        } catch (Exception e) {
            throw new IOException("Can't initialize the decryptor", e);
        }

        byte[] encryptedBytes;

        try {
            crypto.init(Cipher.ENCRYPT_MODE, key);
            encryptedBytes = crypto.doFinal(password.getBytes());

            OutputStream os = new FileOutputStream("encrypted.txt");
            IOUtils.write(encryptedBytes, os);

        } catch (Exception e) {
            throw new IOException("Can't decrypt the password", e);
        }
    }
}

我想使用openssl生成encrypted.txt文件以获得相同的结果。

1 个答案:

答案 0 :(得分:0)

你应该可以使用以下方法创建hmac: 回声"秘密" | openssl dgst -sha1 -hmac" key"