鉴于最终块没有正确填充错误

时间:2015-05-06 15:02:54

标签: java encryption io cryptography

我想将加密的字符串存储在文件中,稍后再解密。

public class Main 
{
    public static void main(String[] argv)
    {
        try
        {
            writeStringAsBytes();
            readStringAsBytes();
        }
        catch(Exception error)
        {
            System.out.println(error.toString());
        }
    }

    public static void readStringAsBytes() throws Exception
    {
        File file = new File("pathname");

        FileInputStream fis=new FileInputStream("pathname");

        byte[] by=new byte[(int)file.length()];
        int i;
        fis.read(by);
        fis.close();

        Encrypter encrypter = new Encrypter();

        System.out.println("decoded:\n" + encrypter.decrypt(by));
    }


    public static void writeStringAsBytes() throws Exception
    {
        String toEncrypt = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\nSed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur.";

        Encrypter encrypter = new Encrypter();

        byte[] encryptedByteArray = encrypter.encrypt(toEncrypt);
        System.out.println("encryptedByteArray:" + encryptedByteArray);

        FileOutputStream fos = new FileOutputStream(new File("pathname"));
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bos.write(encryptedByteArray);
        bos.close();
    }
}

class Encrypter
{
    String alg = "AES";
    Key key;
    Cipher cipher;

    public Encrypter() throws Exception
    {
         key = KeyGenerator.getInstance(alg).generateKey();
         cipher = Cipher.getInstance(alg);
    }

    public byte[] encrypt(String str) throws Exception
    {
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] inBytes = str.getBytes("UTF-16");

        return cipher.doFinal(inBytes);
    }

    public String decrypt(byte[] enBytes) throws Exception
    {
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] bytes = cipher.doFinal(enBytes);
        String rData = new String(bytes, "UTF-16");

        return rData;
    }
}

看起来加密效果很好,但是当我尝试读取和解密字符串时,我得到了这个。

javax.crypto.BadPaddingException: Given final block not properly padded

这个错误是什么意思?如果我不将加密数据存储在文件中并使用相同的实例进行加密和解密,则它可以正常工作。

Encrypter encrypter = new Encrypter();
byte[] b=encrypter.encrypt("hello world");
encrypter = new Encrypter();
System.out.println(encrypter.decrypt(b));

1 个答案:

答案 0 :(得分:0)

您应该为每个Encrypter实例使用相同的密钥。

    import javax.crypto.spec.SecretKeySpec;

    class Encrypter
{
    String alg = "AES";
    Key key;
    Cipher cipher;

    public Encrypter() throws Exception
    {
         //key = KeyGenerator.getInstance(alg).generateKey();
key = new SecretKeySpec("C@ThA$rpma#EsP!!".getBytes(), "AES");
         cipher = Cipher.getInstance(alg);
    }

    public byte[] encrypt(String str) throws Exception
    {
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] inBytes = str.getBytes("UTF-16");

        return cipher.doFinal(inBytes);
    }

    public String decrypt(byte[] enBytes) throws Exception
    {
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] bytes = cipher.doFinal(enBytes);
        String rData = new String(bytes, "UTF-16");

        return rData;
    }
}