当前位置: 首页 > 面试题库 >

在Java中对文件使用基于密码的加密

潘阳舒
2023-03-14
问题内容

我正在尝试使用Java中的密码将一个文件的内容加密为另一个文件。该文件将被读取到一个字节数组,被加密为另一个字节数组,然后写入新文件。不幸的是,当我尝试反向加密时,输出文件被解密为垃圾。

我强烈怀疑问题与每次使用相同密码短语时生成相同密钥有关。我编写了一种测试方法,该方法会在每次生成密钥时将密钥转储到文件中。密钥既可以直接录制也可以编码形式录制。前者每次都是相同的,但由于某种原因后者总是不同的。

老实说,我对加密方法不了解很多,尤其是在Java中。我只需要确保数据安全性适中,并且加密不必承受来自拥有大量时间和技能的任何人的攻击。预先感谢任何对此有意见的人。

编辑:Esailija足够友好地指出,我始终使用ENCRYPT_MODE设置密码。我使用布尔参数更正了该问题,但是现在出现以下异常:

javax.crypto.IllegalBlockSizeException:使用填充密码解密时,输入长度必须是8的倍数

在我看来,密码短语使用不正确。我的印象是“
PBEWithMD5AndDES”会将其哈希为16字节的代码,该代码肯定是8的倍数。我想知道为什么密钥会生成并被用于加密模式,但是在尝试时会抱怨在完全相同的条件下解密。

import java.various.stuff;

/**Utility class to encrypt and decrypt files**/
public class FileEncryptor {
    //Arbitrarily selected 8-byte salt sequence:
    private static final byte[] salt = {
        (byte) 0x43, (byte) 0x76, (byte) 0x95, (byte) 0xc7,
        (byte) 0x5b, (byte) 0xd7, (byte) 0x45, (byte) 0x17 
    };

    private static Cipher makeCipher(String pass, Boolean decryptMode) throws GeneralSecurityException{

        //Use a KeyFactory to derive the corresponding key from the passphrase:
        PBEKeySpec keySpec = new PBEKeySpec(pass.toCharArray());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(keySpec);

        //Create parameters from the salt and an arbitrary number of iterations:
        PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 42);

        /*Dump the key to a file for testing: */
        FileEncryptor.keyToFile(key);

        //Set up the cipher:
        Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");

        //Set the cipher mode to decryption or encryption:
        if(decryptMode){
            cipher.init(Cipher.ENCRYPT_MODE, key, pbeParamSpec);
        } else {
            cipher.init(Cipher.DECRYPT_MODE, key, pbeParamSpec);
        }

        return cipher;
    }


    /**Encrypts one file to a second file using a key derived from a passphrase:**/
    public static void encryptFile(String fileName, String pass)
                                throws IOException, GeneralSecurityException{
        byte[] decData;
        byte[] encData;
        File inFile = new File(fileName);

        //Generate the cipher using pass:
        Cipher cipher = FileEncryptor.makeCipher(pass, false);

        //Read in the file:
        FileInputStream inStream = new FileInputStream(inFile);
        decData = new byte[(int)inFile.length()];
        inStream.read(decData);
        inStream.close();

        //Encrypt the file data:
        encData = cipher.doFinal(decData);


        //Write the encrypted data to a new file:
        FileOutputStream outStream = new FileOutputStream(new File(fileName + ".encrypted"));
        outStream.write(encData);
        outStream.close();
    }


    /**Decrypts one file to a second file using a key derived from a passphrase:**/
    public static void decryptFile(String fileName, String pass)
                            throws GeneralSecurityException, IOException{
        byte[] encData;
        byte[] decData;
        File inFile = new File(fileName);

        //Generate the cipher using pass:
        Cipher cipher = FileEncryptor.makeCipher(pass, true);

        //Read in the file:
        FileInputStream inStream = new FileInputStream(inFile);
        encData = new byte[(int)inFile.length()];
        inStream.read(encData);
        inStream.close();

        //Decrypt the file data:
        decData = cipher.doFinal(encData);

        //Write the decrypted data to a new file:
        FileOutputStream target = new FileOutputStream(new File(fileName + ".decrypted.txt"));
        target.write(decData);
        target.close();
    }

    /**Record the key to a text file for testing:**/
    private static void keyToFile(SecretKey key){
        try {
            File keyFile = new File("C:\\keyfile.txt");
            FileWriter keyStream = new FileWriter(keyFile);
            String encodedKey = "\n" + "Encoded version of key:  " + key.getEncoded().toString();
            keyStream.write(key.toString());
            keyStream.write(encodedKey);
            keyStream.close();
        } catch (IOException e) {
            System.err.println("Failure writing key to file");
            e.printStackTrace();
        }

    }

}

问题答案:

您同时使用Cipher.ENCRYPT_MODE解密和加密。您应该使用它Cipher.DECRYPT_MODE来解密文件

该问题已得到解决,但您的布尔值是错误的。加密时为true,解密时为false。我强烈建议您不要将其false/true用作函数参数,而应始终使用Cipher.ENCRYPT

然后,您将加密为.encrypted文件,但尝试解密原始的纯文本文件。

然后,您不将填充应用于加密。我很惊讶这实际上是必须手动完成的,但是这里会解释填充。填充方案PKCS5似乎在这里隐式使用。

这是完整的工作代码,将加密文件写入test.txt.encrypted,将解密文件写入test.txt.decrypted.txt。注释中说明了在加密中添加填充并在解密中删除填充。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

public class FileEncryptor {

    public static void main( String[] args ) {

        try {
            encryptFile( "C:\\test.txt", "password" );
            decryptFile( "C:\\test.txt", "password" );
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (GeneralSecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //Arbitrarily selected 8-byte salt sequence:
    private static final byte[] salt = {
        (byte) 0x43, (byte) 0x76, (byte) 0x95, (byte) 0xc7,
        (byte) 0x5b, (byte) 0xd7, (byte) 0x45, (byte) 0x17 
    };

    private static Cipher makeCipher(String pass, Boolean decryptMode) throws GeneralSecurityException{

        //Use a KeyFactory to derive the corresponding key from the passphrase:
        PBEKeySpec keySpec = new PBEKeySpec(pass.toCharArray());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(keySpec);

        //Create parameters from the salt and an arbitrary number of iterations:
        PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 42);

        /*Dump the key to a file for testing: */
        FileEncryptor.keyToFile(key);

        //Set up the cipher:
        Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");

        //Set the cipher mode to decryption or encryption:
        if(decryptMode){
            cipher.init(Cipher.ENCRYPT_MODE, key, pbeParamSpec);
        } else {
            cipher.init(Cipher.DECRYPT_MODE, key, pbeParamSpec);
        }

        return cipher;
    }


    /**Encrypts one file to a second file using a key derived from a passphrase:**/
    public static void encryptFile(String fileName, String pass)
                                throws IOException, GeneralSecurityException{
        byte[] decData;
        byte[] encData;
        File inFile = new File(fileName);
        //Generate the cipher using pass:
        Cipher cipher = FileEncryptor.makeCipher(pass, true);

        //Read in the file:
        FileInputStream inStream = new FileInputStream(inFile);

        int blockSize = 8;
        //Figure out how many bytes are padded
        int paddedCount = blockSize - ((int)inFile.length()  % blockSize );

        //Figure out full size including padding
        int padded = (int)inFile.length() + paddedCount;

        decData = new byte[padded];


        inStream.read(decData);

        inStream.close();

        //Write out padding bytes as per PKCS5 algorithm
        for( int i = (int)inFile.length(); i < padded; ++i ) {
            decData[i] = (byte)paddedCount;
        }

        //Encrypt the file data:
        encData = cipher.doFinal(decData);


        //Write the encrypted data to a new file:
        FileOutputStream outStream = new FileOutputStream(new File(fileName + ".encrypted"));
        outStream.write(encData);
        outStream.close();
    }


    /**Decrypts one file to a second file using a key derived from a passphrase:**/
    public static void decryptFile(String fileName, String pass)
                            throws GeneralSecurityException, IOException{
        byte[] encData;
        byte[] decData;
        File inFile = new File(fileName+ ".encrypted");

        //Generate the cipher using pass:
        Cipher cipher = FileEncryptor.makeCipher(pass, false);

        //Read in the file:
        FileInputStream inStream = new FileInputStream(inFile );
        encData = new byte[(int)inFile.length()];
        inStream.read(encData);
        inStream.close();
        //Decrypt the file data:
        decData = cipher.doFinal(encData);

        //Figure out how much padding to remove

        int padCount = (int)decData[decData.length - 1];

        //Naive check, will fail if plaintext file actually contained
        //this at the end
        //For robust check, check that padCount bytes at the end have same value
        if( padCount >= 1 && padCount <= 8 ) {
            decData = Arrays.copyOfRange( decData , 0, decData.length - padCount);
        }

        //Write the decrypted data to a new file:



        FileOutputStream target = new FileOutputStream(new File(fileName + ".decrypted.txt"));
        target.write(decData);
        target.close();
    }

    /**Record the key to a text file for testing:**/
    private static void keyToFile(SecretKey key){
        try {
            File keyFile = new File("C:\\keyfile.txt");
            FileWriter keyStream = new FileWriter(keyFile);
            String encodedKey = "\n" + "Encoded version of key:  " + key.getEncoded().toString();
            keyStream.write(key.toString());
            keyStream.write(encodedKey);
            keyStream.close();
        } catch (IOException e) {
            System.err.println("Failure writing key to file");
            e.printStackTrace();
        }

    }
}


 类似资料:
  • 问题内容: 我有一个名为’filename.txt.pgp’的PGP文件,需要解密。当我从命令行运行解密时,它仅询问我密码。我使用gpg命令: 密码足够,我的文件已解密。我可以阅读它的内容。 现在,我应该用Java创建一个实用程序。经过研究,我发现Bouncy Castle图书馆是我最好的选择。但是我可以找到的所有Java示例都使用我没有的公共/专用密钥文件。 您能帮我举一个Java示例,该示例仅

  • 问题内容: 我找到了用Java实施AES加密/解密的指南,并试图理解每一行并将其放入自己的解决方案中。但是,我没有完全理解它,因此出现了问题。最终目标是拥有基于密码的加密/解密。我已经阅读了有关此的其他文章/ stackoverflow帖子,但是大多数文章没有提供足够的解释(我对Java加密非常陌生) 我现在的主要问题是,即使设置了 I,最后还是会得到不同的Base64结果(每次都是随机的,但是我

  • 问题内容: 我需要实现256位AES加密,但是我在网上找到的所有示例都使用“ KeyGenerator”来生成256位密钥,但是我想使用自己的密码。如何创建自己的密钥?我尝试将其填充到256位,但是随后出现错误消息,提示密钥太长。我确实安装了无限管辖权补丁,所以那不是问题:) 就是 KeyGenerator看起来像这样… 从这里获取的代码 编辑 我实际上是将密码填充到256个字节而不是位,这太长了

  • 问题内容: 我有一个程序从配置文件中读取服务器信息,并希望对该配置中的密码进行加密,该密码可由我的程序读取并解密。 要求: 加密要存储在文件中的纯文本密码 解密从我的程序从文件读取的加密密码 关于我将如何做到这一点的任何建议?我当时在考虑编写自己的算法,但我认为这绝对是不安全的。 问题答案: 一种简单的方法是在Java中使用基于密码的加密。这使你可以使用密码来加密和解密文本。 这基本上意味着初始化

  • null 我正在尝试使用Jasypt的StandardPBEStringEncryptor类 当我这样做时,我会得到以下异常: java.security.NosuchAlgorithmException:AES/CBC/PKCS5Padding SecretKeyFactory不可用 谢谢

  • 问题内容: 如何基于Java 256位AES密码的加密? 问题答案: 与带外接收者共享和salt 所选择的 - 8个字节,这是个好习惯,不需要保密)。然后从此信息中得出一个好的密钥: 幻数(可以在某处定义为常数)65536和256分别是密钥派生迭代计数和密钥大小。 迭代密钥派生功能需要大量的计算工作,并且可以防止攻击者快速尝试许多不同的密码。可以根据可用的计算资源来更改迭代次数。 密钥大小可以减少