【问题标题】:AES decryption with bouncy castle使用充气城堡进行 AES 解密
【发布时间】:2015-04-26 14:35:34
【问题描述】:

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

到目前为止,我忽略了给定的 IV 和密钥,直到我启动并运行其余部分。我的代码成功地从文件中加密明文,并将密文写入文件,但解密不起作用。似乎解密模式读取的字节数多于加密写入的字节数,并且出现块对齐错误。

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

错误发生在

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);
        }
    }
}

【问题讨论】:

  • 确切的异常是什么,它在哪里抛出?请将此信息添加到您的问题中。
  • try{ ctLength += cipher.doFinal(cipherText, ctLength);}catch{IllegalBlockSizeException e) @Artjom B. 出现错误
  • 该加密示例非常基础,既不安全也不正确。 “示例”中已经存在将密文显示为字符串的错误。不要相信互联网上的随机代码样本,尤其是涉及加密时。
  • @MaartenBodewes 感谢您的建议,我会支持您,但我认为我在这里的排名太低,无法这样做。
  • 好的,谢谢。请注意,我什至不记得我为什么发表该评论。 ECB CTR 在 Java SE ("AES/CTR/NoPadding") 中很容易获得。您指出的示例出于某种原因使用了 Bouncy Castle。当然,这并不意味着尝试自己实现它不是一个好习惯。

标签: java encryption cryptography aes bouncycastle


【解决方案1】:

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

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

如果您需要将密文存储为文本,请使用 Base64 等二进制转文本编码对其进行编码。

具体来说,你应该用这样的东西替换你写的密文:

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

【讨论】:

  • 谢谢你解决了这个问题,这个例子是我的教授提供的,所以我不确定为什么它使用了不正确的方法。从一开始就注定了哈哈@erickson
  • @erickson 在加密为 UTF-8 编码之前从纯文本文件中读取是个好主意吗?并将解密后的文件也写为 UTF-8,或者也应该将它们视为字节文件
  • @CSjunkie 这取决于编写纯文本文件时使用的编码;他们应该匹配。如果您自己编写文件,则很可能使用了系统上的默认编码。在 linux 上,locale charmap 会告诉你。在 Windows 上,我认为是 chcp
猜你喜欢
  • 1970-01-01
  • 2014-09-19
  • 1970-01-01
  • 1970-01-01
  • 2013-04-20
  • 1970-01-01
  • 2016-08-10
  • 2013-05-25
  • 2011-06-12
相关资源
最近更新 更多