java - 使用充气城堡进行 AES 解密

标签 java encryption cryptography aes bouncycastle

我正在尝试调整http://www.java2s.com/Code/Java/Security/Basicsymmetricencryptionexample.htm处的示例代码必须使用 3 个参数进行调用:模式(加密或解密)、IV 和 key 。它还读取和写入特定文件。

截至目前,我忽略给定的 IV 和 key ,直到我完成其余部分并运行。我的代码成功加密文件中的明文,并将密文写入文件,但解密不起作用。看来解密模式读取的字节数比加密写入的字节数多,并且出现 block 对齐错误。

我确信解密部分存在一些基本错误,但我不知道它是什么。如果有人可以识别该问题或发现任何可能导致该问题的明显错误,请告诉我。

错误发生在

try{ ctLength += cipher.doFinal(cipherText, ctLength);}catch{IllegalBlockSizeException e)

代码行:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.SecretKeySpec;



@SuppressWarnings("unused")
public class AESCTR {
    static String inputFile = "plain-in.txt";
    static String outputFile = "cipher-out.txt";
    static String cInputFile = "cipher-in.txt";
    static String cOutputFile = "plain-out.txt";
    static String mode;
    static String IV;
    static String key;
    public static void main(String[] args) {
        if (Security.getProvider("BC") == null){
            System.out.println("Bouncy Castle provider is NOT available");
            System.exit(-1);
        }
        else{
            System.out.println("Bouncy Castle provider is available");
        } 
        Security.addProvider(Security.getProvider("BC")); 
        // TODO Auto-generated method stub
        if (args.length != 3){
            System.out.println("Invalid number of arguments\n");
            System.exit(-1);
        }
        mode = args[0];
        IV = args[1];
        key = args[2];
        if ((!mode.equals("enc")) && (!mode.equals("dec"))){
            System.out.println("Invalid mode\n");
            System.exit(-1);
        }
        byte[] keyBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 
    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};
        System.out.println(keyBytes.length);
        SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
        System.out.println("Mode: " + mode + " IV: " + IV + " Key: " + key);
        if(mode.equals("enc")){
            int ctLength = 0;
            byte[] data = null;
            try {
                Path path = Paths.get(inputFile);
                data = Files.readAllBytes(path);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("Invalid Path\n");
                System.exit(-1);
             }
            while((data.length % 16) != 0){ //Padding
                byte[] dest = new byte[data.length + 1];
                byte[] pad = new byte[] {0x00};
                System.arraycopy(data, 0, dest, 0, data.length);
                System.arraycopy(pad, 0, dest, data.length, pad.length);    
                data = dest;
            }
            System.out.println(data.length);
            byte[] cipherText = new byte[data.length];

            Cipher cipher = null;
            try {
                cipher = Cipher.getInstance("AES/ECB/NoPadding", "BC");
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchProviderException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("input text : " + new String(data));

            try {
                cipher.init(Cipher.ENCRYPT_MODE, key);
            } catch (InvalidKeyException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                ctLength = cipher.update(data, 0, data.length, cipherText, 0);    
            } catch (ShortBufferException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                ctLength += cipher.doFinal(cipherText, ctLength);
            } catch (IllegalBlockSizeException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ShortBufferException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (BadPaddingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Writer writer = null;
            try{ writer = new BufferedWriter(new OutputStreamWriter(new     FileOutputStream(cInputFile), "utf-8"));
            writer.write(new String(cipherText));
            } catch (IOException ex){
                System.out.println("File Write Error\n");
                System.exit(-1);
            } finally{
                try{writer.close();}catch (Exception ex){}
            }

            byte[] c = null;
            try {
                Path path = Paths.get(cInputFile);
                c = Files.readAllBytes(path);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("Invalid Path\n");
                System.exit(-1);
            }
            System.out.println("cipher text: " + new String(c) + " bytes: " + ctLength);
        }
        else if (mode.equals("dec")){
            byte[] c = null;
            try {
                Path path = Paths.get(cInputFile);
                c = Files.readAllBytes(path);
                File f = new File(cInputFile);
                System.out.println("In Bytes: " + c.length);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("Invalid Path\n");
                System.exit(-1);
            }
            Cipher cipher = null;
            try {
                cipher = Cipher.getInstance("AES/ECB/NoPadding", "BC");
            } catch (NoSuchAlgorithmException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (NoSuchProviderException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (NoSuchPaddingException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            byte[] plainText = new byte[c.length];
            try {
                cipher.init(Cipher.DECRYPT_MODE, key);
            } catch (InvalidKeyException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int ptLength = 0;
            try {
                ptLength = cipher.update(c, 0, c.length, plainText, 0);
                System.out.println(ptLength);
            } catch (ShortBufferException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                ptLength += cipher.doFinal(plainText, ptLength);
            } catch (IllegalBlockSizeException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ShortBufferException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (BadPaddingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("plain text : " + new String(plainText) + " bytes: " + ptLength);
        }
    }
}

最佳答案

您正在尝试将大量随机字节解码为 UTF-8 编码文本。那是行不通的。您的密文会被损坏,因为任何不形成有效 UTF-8 字符编码的字节序列都将被替换字符 0+FFFD (�) 所替换。

密文实际上并不是文本。不要使用像 WriterReader 这样处理文本的 API。使用可处理字节数组的 API,例如 OutputStreamInputStream

如果您需要将密文存储为文本,请使用二进制到文本的编码(例如 Base64)对其进行编码。

具体来说,您应该将密文替换为如下内容:

try {
  Files.write(Paths.get(cInputFile), cipherText);
} catch (IOException ex) {
  System.out.println("File Write Error");
  System.exit(-1);
}

关于java - 使用充气城堡进行 AES 解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28704809/

相关文章:

language-agnostic - 加密方法未知时解密数据的最有效方法?

java - 如何使用hashmap将字符设置为等于不同的字符?

php - php 中的 AES 加密和 perl 中的解密

c# - System.Security.Cryptography.ProtectedData.Unprotect 在某些情况下抛出无效 key 错误

java - 通知无需遵循 AlarmManager 即可工作

java - 映射结构 : Ambiguous mapping methods found for mapping collection element

java - 保存上传时MongoDB异常

java - 从 JButton 获取鼠标单击事件的位置

java - 安卓数据库的安全 key

java - 我可以使用 4096 位作为带有 OAEP 填充的 Java RSA 的 key 长度吗?