使用AES加密/解密并将信息存储在文本文件

时间:2015-12-11 02:05:47

标签: java encryption file-io cryptography

我一直致力于自己的小项目,我正在尝试创建一个简单的密码管理器。我目前遇到的问题是让它以某种方式工作,以便在运行时将加密的密码保存到文件中,然后在另一次运行时,您可以调用它并将其解密,显示您的密码您拨打的用户名。

对于我想稍后添加到程序中的内容,我确实需要将加密/解密方法分开。

目前的错误是:

  

线程“main”中的异常javax.crypto.IllegalBlockSizeException:使用填充密码解密时,输入长度必须是16的倍数

非常感谢任何帮助。

代码如下:

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;

import javax.crypto.*;
import javax.crypto.spec.*;
import java.util.Scanner;
import javax.crypto.spec.SecretKeySpec;

public class PasswordManager3
{

    static String key = "SimplePasswordMg";
    static String password1 = "";
    static String password2 = "";
    static String username = "";


    public static void main(String[] args) 
             throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, 
             BadPaddingException, IOException 
    {

        Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");

        System.out.println("Enter New to input a new password, or Retrieve to retrieve an old password:");
        Scanner scanner1 = new Scanner(System.in);
        String answer = scanner1.nextLine();

        if(answer.equalsIgnoreCase("New")) {

            System.out.println("Please enter a username: ");
            Scanner scanner2 = new Scanner(System.in);
            username = scanner2.nextLine();

            System.out.println("Please enter a password: ");
            Scanner scanner3 = new Scanner(System.in);
            password1 = scanner3.nextLine();

            System.out.println("Please enter your password again: ");
            Scanner scanner4 = new Scanner(System.in);
            password2 = scanner4.nextLine();

            if (password1.equalsIgnoreCase(password2)) {

                Files.write(Paths.get(username + ".txt"), encrypt(password1, cipher, aesKey));
                System.out.println("Your password has been stored.");
            }

            else {
                System.out.println("The passwords you entered did not match. Exiting password manager.");
            }

        }

        else if(answer.equalsIgnoreCase("Retrieve")) {

            System.out.println("Please enter the username you would like to retrieve the password for: ");
            Scanner scanner5 = new Scanner(System.in);
            username = scanner5.nextLine();
            BufferedReader in = new BufferedReader(new FileReader(username + ".txt"));
            String encryptedpass = in.readLine();
            byte[] encryptedpass2 = encryptedpass.getBytes("UTF-8");
            System.out.println(decrypt(encryptedpass2, cipher, aesKey));
        }

        else {
            System.out.println("You entered an incorrect option, program exited.");
        }

    }

     public static byte[] encrypt(String str, Cipher cipher, Key aesKey) 
             throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException 
     {

          cipher.init(Cipher.ENCRYPT_MODE, aesKey);

          byte[] encrypted = cipher.doFinal(key.getBytes("UTF-8"));

          return encrypted;
     }

    public static String decrypt(byte[] byte1, Cipher cipher, Key aesKey) 
            throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException 

    {

        cipher.init(Cipher.DECRYPT_MODE, aesKey);
        String decrypted = new String(cipher.doFinal(byte1));
        return decrypted;
    }

}

1 个答案:

答案 0 :(得分:2)

您没有撰写文本文件。加密数据实际上是随机位,您的mainencrypt的返回值直接传递给Files.write(Path,byte[])它是二进制的。

当您使用FileReader读回来时,它会使用您未识别的平台的默认编码,有时还会使用您的用户环境,这可能会或可能不会破坏某些字节;使用readLine()可能会丢弃部分数据,并使用getBytes("UTF-8")对其进行编码,因为它始终是有效字符,大约99.6%肯定会破坏任何剩余的数据。因此,传递给decrypt的值完全错误,无法解密。

简单,对称的修复是使用File.readAllBytes(Path)将(整个)文件读取为二进制,并解密返回的byte[]值。

或者,如果你真的想要文本文件由于某种原因(我没有看到任何),你需要首先将加密值编码为文本形式并写入,可能添加了行终止符,然后读取它返回(如果您选择了该行,则为一行)并在解密之前对其进行解码。 Base64和十六进制(缩写为十六进制)是两种最常用的文本编码二进制数据的方法。

另外:使用一个全部可打印的ASCII键,甚至包含部分英文单词,大大削弱了你的加密,从标称的128位到更像20-30位,这很容易被任何半职能的攻击者打破。使用任何硬编码密钥也是一种危险,尽管这是一个更难的问题,并且没有单一,简单和良好的解决方案。

默认情况下,您在ECB模式下使用AES。使用ECB密码(以及其他任何东西)是一个坏主意;了解为什么google“ECB penguin”和“Adobe密码泄露”和/或看到
https://crypto.stackexchange.com/questions/11451/can-ecb-mode-really-leak-some-characters
https://crypto.stackexchange.com/questions/11456/what-does-it-mean-if-second-half-of-8-char-string-encrypted-in-3des-is-always-id