最后一个块与CipherInputStream / CipherOutputStream不完整,即使使用填充AES / CBC / PKCS5Padding

时间:2012-10-09 12:10:09

标签: java android encryption aes padding

实际上,我为此搜索了很多来自互联网和stackoverflow的内容,

最初我在加密和解密中没有使用填充,

但最后我从这里得到了解决方案

https://stackoverflow.com/a/10775577/1115788

我用填充作为AES / CBC / PKCS5Padding更新了我的代码 并且同样的错误即将发生,最后一个块未被解密...

我在最近两天的工作,但没有找到解决方案

我的Crypter代码:

package mani.droid.browsedropbox;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Crypter {

    Cipher encipher;
    Cipher decipher;
CipherInputStream cis;
CipherOutputStream cos;
FileInputStream fis;
byte[] ivbytes = new byte[]{(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e',                                                                                          (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m',     (byte)'n', (byte)'o', (byte)'p'};
    IvParameterSpec iv = new IvParameterSpec(ivbytes);

public boolean enCrypt(String key, InputStream is, OutputStream os)
{
    try {
        byte[] encoded = new BigInteger(key, 16).toByteArray();
        SecretKey seckey = new SecretKeySpec(encoded, "AES");
        encipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        encipher.init(Cipher.ENCRYPT_MODE, seckey, iv);
        cis = new CipherInputStream(is, encipher);
        copyByte(cis, os);
        return true;
    } 
    catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

public boolean deCrypt(String key, InputStream is, OutputStream os)
{
    try {
        byte[] encoded = new BigInteger(key, 16).toByteArray();
        SecretKey seckey = new SecretKeySpec(encoded, "AES");
        encipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        encipher.init(Cipher.DECRYPT_MODE, seckey, iv);
        cos = new CipherOutputStream(os, encipher);
        copyByte(is, cos);
        //cos.close();
        return true;
    } 
    catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

public void copyByte(InputStream is, OutputStream os) throws IOException
{
    byte[] buf = new byte[8192];
    int numbytes;
    while((numbytes = is.read(buf)) != -1)
    {
        os.write(buf, 0, numbytes);
        os.flush();
    }
    os.close();
    is.close();
}
}

6 个答案:

答案 0 :(得分:13)

我遇到了完全相同的问题。 已接受的解决方案之所以有效,是因为您使用了不需要填充的密码模式,但这不是解决加密相关问题的方法。

根据CipherOutputStream documentation,您必须调用close()方法才能正确完成加密(即添加填充块)。

  

此方法调用封装密码的doFinal方法   object,它导致封装密码缓冲的任何字节   被处理。通过调用flush方法写出结果   这个输出流。

     

此方法将封装的密码对象重置为其初始状态   并调用底层输出流的close方法。

如果要在调用CipherOutputStream.close()方法后保持OutputStream保持打开状态,则可以将OutputStream包装到不关闭它的流中。例如:

public class NotClosingOutputStream extends OutputStream {
  private final OutputStream os;

  public NotClosingOutputStream(OutputStream os) {
    this.os = os;
  }

  @Override
  public void write(int b) throws IOException {
    os.write(b);
  }

  @Override
  public void close() throws IOException {
    // not closing the stream.
  }

  @Override
  public void flush() throws IOException {
    os.flush();
  }

  @Override
  public void write(byte[] buffer, int offset, int count) throws IOException {
    os.write(buffer, offset, count);
  }

  @Override
  public void write(byte[] buffer) throws IOException {
    os.write(buffer);
  }
}

然后你可以使用:

...
cos = new CipherOutputStream(new NotClosingOutputStream(os), encipher);
copyByte(is, cos);
cos.close();
...

请注意os流未关闭,您需要在适当的时候自行完成。

答案 1 :(得分:7)

最后,我通过反复试验回答了我自己的问题 实际上这里冲突是我在encipher = Cipher.getInstance("AES/CBC/PKCS7Padding");

中设置填充

和Set IV有一些值.....,

最后我得到的答案只是替换了算法

自:

  

AES / CBC / PKCS7Paddinng

要:

  

AES / CFB8 / NoPadding

它的功能就像魅力一样....所以我建议这个问题的答案对于那些努力解决这个问题的人,如果你解决了你的问题,请在这里为其他人提及......

答案 2 :(得分:0)

我见过CipherInputStream也因填充问题而失败。这种行为在不同版本的JVM中有所不同。例如7u55 32位我的代码工作正常,7u55 64位相同的代码失败...我也看到了后来32位JVM的失败。解决方法是使用字节数组方法并避免使用CipherInputStream。

答案 3 :(得分:0)

不确定这是否与OP的问题相关,但这可能有助于某人。

当您 反复获取java.io.IOException: last block incomplete in decryption 时,无论您更改了什么, 检查您是否仍在使用某些文件以前的运行。如果您的读/写测试代码附加到该文件,您将始终获得该异常 - 除非您删除您写入的损坏文件。

答案 4 :(得分:0)

使用带填充的CipherInputStream是可行的,切换到NoPadding是一种解决方法,但不是解决方案。

当CipherInputStream到达流的末尾时应用填充。重要的一点是,您必须至少调用CipherInputStream的read()方法两次才能获取所有数据。

以下示例演示如何使用填充读取CipherInputStream:

public static void test() throws Exception {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

    SecureRandom rnd = new SecureRandom();
    byte[] keyData = new byte[16];
    byte[] iv = new byte[16];
    rnd.nextBytes(keyData);
    rnd.nextBytes(iv);
    SecretKeySpec key = new SecretKeySpec(keyData, "AES");

    cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    CipherOutputStream out = new CipherOutputStream(buffer, cipher);

    byte[] plain = "Test1234567890_ABCDEFG".getBytes();
    out.write(plain);
    out.flush();
    out.close();
    byte[] encrypted = buffer.toByteArray();
    System.out.println("Plaintext length: " + plain.length);
    System.out.println("Padding length  : " + (cipher.getBlockSize() - (plain.length % cipher.getBlockSize())));
    System.out.println("Cipher length   : " + encrypted.length);

    cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
    CipherInputStream in = new CipherInputStream(new ByteArrayInputStream(encrypted), cipher);
    buffer = new ByteArrayOutputStream();
    byte[] b = new byte[100];
    int read;
    while ((read = in.read(b)) >= 0) {
        buffer.write(b, 0, read);
    }
    in.close();

    // prints Test1234567890_ABCDEFG
    System.out.println(new String(buffer.toByteArray()));
}

答案 5 :(得分:0)

对于那些正在努力使用图像文件进行AES加密/解密的人来说,这是我的示例,它的工作原理就像一种魅力。

public static String decrypt(String textToDecrypt)  {
    byte[] dataDecrypted = null;

    try {
        Cipher cipher = getCipher();
        SecretKey key = getKey();
        IvParameterSpec iv = getIV();
        if(cipher == null) {
            return null;
        }
        cipher.init(Cipher.DECRYPT_MODE, key, iv);

        byte[] dataToDecrypt = Base64.decode(textToDecrypt, Base64.NO_WRAP);
        ByteArrayInputStream bais = new ByteArrayInputStream(dataToDecrypt);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // Wrap the output stream
        CipherOutputStream cos = new CipherOutputStream(baos, cipher);

        // Read bytes
        int count = 0;
        byte[] buffer = new byte[DEFAULT_BYTE_READ_WRITE_BLOCK_BUFFER_SIZE];
        while ((count = bais.read(buffer)) != -1) {
            cos.write(buffer, 0, count);
        }
        cos.close();    // manually do close for the last bit

        dataDecrypted = baos.toByteArray();

        // Close streams.
        baos.close();
        bais.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return (dataDecrypted == null ? "" : Base64.encodeToString(dataDecrypted, Base64.NO_WRAP));
}

public static String encrypt(String textToEncrypt) {
    byte[] dataEncrypted = null;

    try {
        Cipher cipher = getCipher();
        SecretKey key = getKey();
        IvParameterSpec iv = getIV();
        if (cipher == null) {
            return null;
        }
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);

        byte[] dataToEncrypt = Base64.decode(textToEncrypt, Base64.NO_WRAP);
        ByteArrayInputStream bais = new ByteArrayInputStream(dataToEncrypt);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // Wrap the output stream
        CipherOutputStream cos = new CipherOutputStream(baos, cipher);

        // Read bytes
        int count = 0;
        byte[] buffer = new byte[DEFAULT_BYTE_READ_WRITE_BLOCK_BUFFER_SIZE];
        while ((count = bais.read(buffer)) != -1) {
            cos.write(buffer, 0, count);
        }
        cos.close();    // manually do close for the last bit

        dataEncrypted = baos.toByteArray();

        // Close streams.
        baos.close();
        bais.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return (dataEncrypted == null ? "" : Base64.encodeToString(dataEncrypted, Base64.NO_WRAP));
}