java-使用base64解密文件 [英] java - decrypt a file with base64

查看:47
本文介绍了java-使用base64解密文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,选择了一个文本文件并将其加密.加密的文本和密钥分别保存.现在,我尝试创建一个程序,当正确的密钥文件可用时,该程序将对文件进行解密.我认为解密程序必须看起来像 DECRYPT_MODE 中的加密程序.当我读入密钥时,我不知道如何对密钥进行下一步以解密文本文件.也许任何人都可以帮助我,如何使用.txt文件中的密钥并将其用于解密编码的文件.

In my project a textfile is chosen and become encrypted. The encrypted text is saved seperatly as well as the key. Now I try to create a program which is decrypting the file when the right keyfile is available. I think the decrypting program needs to look pretty like the encrypting program just in DECRYPT_MODE. When I read in the key I don't know how to do the next step at it to decrypt the textfile. Maybe anyone can help me how I use the key from .txt file and use it to decrypt the encoded file.

加密程序:

public class encrypt {

    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {
        //Key is created and saved in File
        KeyGenerator keygenerator = KeyGenerator.getInstance("AES");
        SecretKey myDesKey = keygenerator.generateKey();
        String encodedKey = Base64.getEncoder().encodeToString(myDesKey.getEncoded());
        Path keypath = Paths.get("C:/xxx/key.txt");
        Path keyfile = Files.createFile(keypath);
        Files.write(keyfile, encodedKey.getBytes(), StandardOpenOption.WRITE);

        Cipher desalgCipher;
        desalgCipher = Cipher.getInstance("AES");
        desalgCipher.init(Cipher.ENCRYPT_MODE, myDesKey);

        Path target = Paths.get("C:/xxx/encrypted.txt");
        Path file = Files.createFile(target);

        Path path = Paths.get("test.txt");               
        try(InputStream is = Files.newInputStream(path);      
        CipherInputStream cipherIS = new CipherInputStream(is, desalgCipher);   
        BufferedReader reader = new BufferedReader(new InputStreamReader(cipherIS));){  
            String line;
            while((line = reader.readLine()) != null){
                System.out.println(line);
                Files.write(file, line.getBytes(), StandardOpenOption.WRITE);
            }
        }          
    }
}

解密:读入密钥并解密

    public class decrypt {

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

            try {
                File fileDir = new File("C:/Users/JT/Desktop/key.txt");

                BufferedReader in = new BufferedReader(
                   new InputStreamReader(new FileInputStream(fileDir), "UTF-8"));

                String str;

                while ((str = in.readLine()) != null) {
                    System.out.println(str);
                }
                        in.close();
                } 
                catch (UnsupportedEncodingException e) 
                {
                    System.out.println(e.getMessage());
                } 
                catch (IOException e) 
                {
                    System.out.println(e.getMessage());
                }
                catch (Exception e)
                {
                    System.out.println(e.getMessage());
                }

               byte[] decodedKey = Base64.getDecoder().decode(sb.toString());
    SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES"); 
    SecretKeySpec key = new SecretKeySpec(sb.toString().getBytes(), "Base64");

    Cipher desalgCipher;
    desalgCipher = Cipher.getInstance("AES");
    desalgCipher.init(Cipher.DECRYPT_MODE, key);

    Path path = Paths.get("encrypted.txt");                // path to your file
    try(InputStream is = Files.newInputStream(path);        // get an IS on your file
    CipherInputStream cipherIS = new CipherInputStream(is, desalgCipher);   // wraps stream using cipher
    BufferedReader reader = new BufferedReader(new InputStreamReader(cipherIS));){   // init reader.
        String line;
        while((line = reader.readLine()) != null){
            System.out.println(line);

            }
        }

     }
}

推荐答案

您的应用程序的编程方式不正确.当前,您尝试通过使用 CipherInputStream 实例包装输入流来进行加密.然后,该实例再次被 BufferedReader 实例包装.

Your application is not being programmed the right way. Currently you try to encrypt by wrapping the input stream with a CipherInputStream instance. Then this instance again is wrapped with a BufferedReader instance.

因此,您要做的是首先将输入文件的字节(可能是文本)转换为密文.该密文可以包含任何字节值.然后,您尝试使用默认字符集和行尾逐行读取那些字节.显然,在加密之后,甚至行的 都不存在了,因此您将在最后一步中丢失数据.

So what you are doing is to first convert the bytes of the input file - probably text - into ciphertext. This ciphertext can contain any byte value. Then you try to read those bytes in line-by-line using the default character set and line endings. Obviously after encryption even the notion of lines doesn't exist anymore, so you'll loose data in that final step.

然后将其转换回字节,然后(以某种方式)尝试将其解密.显然,这将失败,因为您在 readLine 语句期间丢失了数据.

Then you convert back to bytes, which you then (somehow) try to decrypt. This will obviously fail as you lost data during the readLine statement.

您应该做的是使用字节读取文件.然后,您可以写入 CipherOutputStream .如果带有密文的文件需要是实际的文本,则可以使用新的 java.util.Base64 很好地提供的 Base64 流.

What you should do is to read in the file using bytes. You can then write to a CipherOutputStream. If the file with the ciphertext needs to be actual text you can use a Base64 stream which the new java.util.Base64 nicely provides.

只有正确设置了加密功能后,您才能尝试逆转该过程.只要数据丢失,解密显然就会失败(错误或垃圾输出,具体取决于模式和运气).

Only once you programmed the encryption correctly you can try and reverse the process. As long as data is lost obviously the decryption will fail (with an error or garbage output, depending on the mode and your luck).

如果您不走运,您将获得在99%的时间内都能正常工作的代码.祝您好运,并注意以下评论:不要在不了解自己正在执行的操作的情况下尝试执行加密.它以眼泪或结实的键盘结尾.

If you're unlucky you will end up with code that works 99% of the time. So good luck and heed the comments: don't try and perform encryption without understanding what you're doing. It will end with tears - or a smashed keyboard.

这篇关于java-使用base64解密文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆