解密时出现填充错误,但仍然有效

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解密时出现填充错误,但仍然有效相关的知识,希望对你有一定的参考价值。

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Program to encrypt and decrypt files using a key derived from a password by PBKDF2
 * and AES-128
 */

/**
 * @author les
 * @version $Revision: 1.1 $
 */
public class FileEncryptorSkeleton {

    private static final String progName = "FileEncryptor";
    private static final int bufSize = 128;

    /**
     * @param args
     */
    public static void main(String[] args) {

        BufferedInputStream in = null; // A buffered input stream to read from
        BufferedOutputStream out = null; // And a buffered output stream to write to
        SecretKeyFactory kf = null; // Something to create a key for us
        KeySpec ks = null; // This is how we specify what kind of key we want it to generate
        byte[] salt = new byte[20]; // Some salt for use with PBKDF2, only not very salty
        SecretKey key = null; // The key that it generates
        Cipher cipher = null; // The cipher that will do the real work
        SecretKeySpec keyspec = null; // How we pass the key to the Cipher
        int bytesRead = 0; // Number of bytes read into the input file buffer
        if (args.length != 4) {
            printUsageMessage();
            System.exit(1);
        }
        try {
            in = new BufferedInputStream(new FileInputStream(args[1]));
        } catch (FileNotFoundException e) {
            printErrorMessage("Unable to open input file: " + args[1], null);
            System.exit(1);
        }
        try {
            out = new BufferedOutputStream(new FileOutputStream(args[2]));
        } catch (FileNotFoundException e) {
            printErrorMessage("Unable to open output file: " + args[2], e);
            System.exit(1);
        }
        try {
            kf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        } catch (NoSuchAlgorithmException e2) {
            e2.printStackTrace();
        }
        String password = args[3];

        ks = new PBEKeySpec(password.toCharArray(), salt, 128, 128);
        try {
            key = kf.generateSecret(ks);
        } catch (InvalidKeySpecException e1) {
            e1.printStackTrace();
        }
        byte[] aeskey = key.getEncoded();
        try {

            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        } catch (NoSuchAlgorithmException e) {
            printErrorMessage("No Such Algorithm Exception when creating main cipher", e);
            System.exit(2);
        } catch (NoSuchPaddingException e) {
            printErrorMessage("No Such Padding Exception when creating main cipher", e);
            System.exit(2);
        }
        int cipherMode = -1;
        char mode = Character.toLowerCase(args[0].charAt(0));
        switch (mode) {
        case 'e':
            cipherMode = Cipher.ENCRYPT_MODE;
            break;
        case 'd':
            cipherMode = Cipher.DECRYPT_MODE;
            break;
        default:
            printUsageMessage();
            System.exit(1);
        }
        keyspec = new SecretKeySpec(aeskey, "AES");
        try {
            cipher.init(cipherMode, keyspec);
        } catch (InvalidKeyException e) {
            printErrorMessage("Invalid Key Spec", e);
            System.exit(2);
        }
        byte[] inputBuffer = new byte[bufSize];
        byte[] outputBuffer = null;
        try {
            bytesRead = in.read(inputBuffer);
        } catch (IOException e) {
            printErrorMessage("Error reading input file " + args[1], e);
            System.exit(1);
        }
        while (bytesRead > 0) {
            outputBuffer = cipher.update(inputBuffer);
            try {
                out.write(outputBuffer);
            } catch (IOException e) {
                printErrorMessage("Error writing to output file " + args[2], e);
                System.exit(1);
            }
            try {
                bytesRead = in.read(inputBuffer);
            } catch (IOException e) {
                printErrorMessage("Error reading input file " + args[1], e);
                System.exit(1);
            }
        }
        try {
            outputBuffer = cipher.doFinal(inputBuffer);
        } catch (IllegalBlockSizeException | BadPaddingException e1) {
            e1.printStackTrace();
        }
        try {
            out.write(outputBuffer);
        } catch (IOException e) {
            printErrorMessage("Error on final write to output file " + args[2], e);
            System.exit(1);
        }
        try {
            in.close();
            out.close();
        } catch (IOException e) {
            printErrorMessage("Error closing file", e);
        }
    }

    /**
     * Print an error message on stderr, optionally picking up additional detail
     * from a passed exception
     * 
     * @param errMsg
     * @param e
     */
    private static void printErrorMessage(String errMsg, Exception e) {
        System.err.println(errMsg);
        if (e != null)
            System.err.println(e.getMessage());
    }

    /**
     * Print a usage message
     */
    private static void printUsageMessage() {
        System.out.println(progName + " $Revision: 1.1 $: Usage: " + progName + " E/D infile outfile passphrase");
    }

}

我正在尝试编写一个使用密码对文本文档进行加密和解密的程序。它不会在加密时引发任何错误,但会在解密时引发严重的填充异常,但它仍会输出正确的文本,但最后还会有其他内容。我搜索了其他答案,但找不到解决方案。通过编译到可运行的jar并像java -jar filename e / d(加密/解密)inputFile.txt outputFile.txt密码那样运行它,来运行该程序。

预先感谢

编辑:

Exception:
javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
        at java.base/com.sun.crypto.provider.CipherCore.unpad(Unknown Source)
        at java.base/com.sun.crypto.provider.CipherCore.fillOutputBuffer(Unknown Source)
        at java.base/com.sun.crypto.provider.CipherCore.doFinal(Unknown Source)
        at java.base/com.sun.crypto.provider.AESCipher.engineDoFinal(Unknown Source)
        at java.base/javax.crypto.Cipher.doFinal(Unknown Source)
        at FileEncryptorSkeleton.main(FileEncryptorSkeleton.java:183)

这是我在其中添加outputBuffer = cipher.doFinal(inputBuffer);

样本输入:

aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz

样本输出:

aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazz
aaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzzaaaazzzz

output picture as invalid characters didnt show up in cod block

import java.io.BufferedInputStream;导入java.io.BufferedOutputStream;导入java.io.FileInputStream;导入java.io.FileNotFoundException;导入java.io.FileOutputStream;导入java.io ....

答案

您反复呼叫bytesRead = in.read(inputBuffer),然后再呼叫cipher.update(inputBuffer)。到达输入文件的末尾时,仅inputBuffer的一部分设置为新数据,其余部分为previous

以上是关于解密时出现填充错误,但仍然有效的主要内容,如果未能解决你的问题,请参考以下文章

解密 C# 中使用 RSA-OAEP 在 JavaScript 中加密的数据时出现 OAEP 填充错误

自动填充时出现错误 80010108

尝试填充占位符时出现Tensorflow错误

解密 Forms cookie 时出现“加密操作期间出错”

在片段java类中使用“this”和getLastSignedInAccount时出现错误[重复]

在 C# 中使用具有正确私钥和公钥对的 RSA 解密时出现错误数据异常