首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >文件解密失败: javax.crypto.BadPaddingException: pad块损坏

文件解密失败: javax.crypto.BadPaddingException: pad块损坏
EN

Stack Overflow用户
提问于 2015-09-24 00:58:52
回答 1查看 1.3K关注 0票数 1

我已经在我的pc上创建了一个ZIP文件(我用finder中的os x zipper压缩了它),然后我用我的java程序对它进行了加密:

代码语言:javascript
复制
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应用程序,我把加密的压缩文件放到了一个资产文件夹main/assets/pic.zip.encrypted中。

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

代码语言:javascript
复制
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文件时,我得到了以下错误:

代码语言:javascript
复制
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)

然而,当我在我的PC上应用相同的解密方法时,它工作得很好。

这是怎么回事?

EN

回答 1

Stack Overflow用户

发布于 2015-09-24 02:11:34

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

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

因此,您不应该像我上面所做的那样,从salt密钥中构造密钥。相反,您应该转到PC并从private byte[] getKey()获取key作为Base64字符串对象。在我的例子中,密钥类似于:n9dReP+BPwHWGCLpDQe+MQ==,然后将其复制粘贴到android方法中,该方法如下所示:

代码语言:javascript
复制
private byte[] getKey() {
            byte[] key = Base64.decode(new String("n9dReP+BPwHWGCLpDQe+MQ==").getBytes(), 0);
            return key;
    }

就这样。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32745324

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档