解密文件失败:javax.crypto.BadPaddingException:pad block corrupted

时间:2015-09-23 16:58:52

标签: java android encryption

我在我的电脑上创建了一个ZIP文件(我在查找程序中用os x zipper压缩它)然后用我的java程序加密它:

public class ResourceEncrypter {

    static byte[] salt = { (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
                               (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99 };

    public static void main(String[] args) {
        new ResourceEncrypter().encryptAllFiles();
        System.out.println("Okay, done");
    }



    private byte[] getKey() {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
            sr.setSeed(salt);
            kgen.init(128, sr); 
            SecretKey skey = kgen.generateKey();
            byte[] key = skey.getEncoded();
            return key;
        } catch(Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private void encryptAllFiles() {
        try {
            byte[] key = getKey();

            //Take a list of files and encrypt each file...
            String srcFilesPath = System.getProperty("user.dir") + "/srcFiles";
            String encryptedSrcFilesPath = System.getProperty("user.dir") + "/encryptedSrcFiles";
            File[] listOfFiles = new File(srcFilesPath).listFiles();
            for(int i = 0; i < listOfFiles.length; ++i) {
                if(listOfFiles[i].getAbsolutePath().contains(".zip")) {
                    //Encrypt this file!
                    byte[] data = Files.readAllBytes(Paths.get(listOfFiles[i].getAbsolutePath()));
                    byte[] encryptedData = ResourceEncrypter.encrypt(key, data);

                    String filename = listOfFiles[i].getName();
                    System.out.println("Write result to " + encryptedSrcFilesPath + "/" + filename);
                    FileOutputStream output = new FileOutputStream(encryptedSrcFilesPath + "/" + filename);
                    output.write(encryptedData);
                    output.close();
                }
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }



    private static byte[] encrypt(byte[] key, byte[] data) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encryptedData = cipher.doFinal(data);
        return encryptedData;
    }

因此,这会将任何zip文件加密并将结果保存到另一个文件夹。

现在,我有一个Android应用程序,我将加密的zip文件放入资产文件夹main/assets/pic.zip.encrypted

在我的Android应用程序中,我执行以下操作:

public class MainActivity extends AppCompatActivity {

static byte[] salt = {  (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
                                (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99 };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        decryptZipFile();
    }


    private byte[] getKey() {
        try {
            //Create the key for the encryption/decryption
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
            sr.setSeed(salt);
            kgen.init(128, sr); // 192 and 256 bits may not be available
            SecretKey skey = kgen.generateKey();
            byte[] key = skey.getEncoded();
            return key;
        } catch(Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private static byte[] decrypt(byte[] key, byte[] encryptedData) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(key,"AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decrypted = cipher.doFinal(encryptedData);
        return decrypted;
    }


    public void decryptZipFile() {
        // First decrypt the zip file
        try {
            InputStream is = getResources().getAssets().open("pics.zip.encrypted");
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int count;
            while ((count = is.read(buffer)) != -1)
                baos.write(buffer, 0, count);
            byte[] encryptedData = baos.toByteArray();

            byte[] decryptedData = decrypt(getKey(), encryptedData);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

当我现在尝试使用此代码解密我的zip文件时,我收到以下错误:

09-23 18:41:21.117  30799-30799/demo.zip.app.zipapp W/System.err﹕ javax.crypto.BadPaddingException: pad block corrupted
09-23 18:41:21.117  30799-30799/demo.zip.app.zipapp W/System.err﹕ at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(BaseBlockCipher.java:854)
09-23 18:41:21.117  30799-30799/demo.zip.app.zipapp W/System.err﹕ at javax.crypto.Cipher.doFinal(Cipher.java:1340)
09-23 18:41:21.117  30799-30799/demo.zip.app.zipapp W/System.err﹕ at demo.zip.app.zipapp.MainActivity.decrypt(MainActivity.java:63)

但是,当我在我的电脑上应用相同的解密方法时,它可以正常工作。

这里发生了什么?

1 个答案:

答案 0 :(得分:0)

好的,我找到了解决方案。

问题是SecureRandom,特别是setSeed方法在Android上的工作方式与普通Java不同。

所以,相反,你不应该像上面那样用盐键构造一个键。相反,您应该转到PC并从key获取private byte[] getKey()作为Base64字符串对象。然后在我的情况下,键看起来像这样:n9dReP+BPwHWGCLpDQe+MQ==然后将其粘贴到android方法中,这将成为:

private byte[] getKey() {
            byte[] key = Base64.decode(new String("n9dReP+BPwHWGCLpDQe+MQ==").getBytes(), 0);
            return key;
    }

那就是它。