我正在为自己做一个个人项目,尝试在手机上加密文件,这些文件可以是任何东西,比如文档、照片等。现在我正在努力使这个项目正常运行。每当我运行加密时,它似乎都能正常工作并加密文件。但是,当我运行解密时,有时它可以正常工作,而有时却无法正常工作。当它失败时,通常会出现“Error while finalizing cipher, pad block corrupted”错误。我也没有使用不同的测试文件,所以不像有些文件可用而其他文件不可用。每次我尝试的都是同样的两个文件。
public static void encryptfile(String path,String Pass) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
FileInputStream fis = new FileInputStream(path);
FileOutputStream fos = new FileOutputStream(path.concat(".crypt"));
byte[] key = (salt + Pass).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key,16);
SecretKeySpec sks = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sks);
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
int b;
byte[] d = new byte[8];
while((b = fis.read(d)) != -1) {
cos.write(d, 0, b);
}
cos.flush();
cos.close();
fis.close();
}
public static void decrypt(String path,String Pass) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
FileInputStream fis = new FileInputStream(path);
FileOutputStream fos = new FileOutputStream(path.replace(".crypt",""));
byte[] key = (salt + Pass).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key,16);
SecretKeySpec sks = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, sks);
CipherInputStream cis = new CipherInputStream(fis, cipher);
int b;
byte[] d = new byte[8];
while((b = cis.read(d)) != -1) {
fos.write(d, 0, b);
}
fos.flush();
fos.close();
cis.close();
}
目前Salt和Password是静态的,为了测试目的而不改变。但仍然有大约一半的时间会出现错误。
有人对此有何想法吗?我已经搜索了一些解决方案,但都没有奏效。我在以下问题中寻找解决方法:
使用CipherInputStream / CipherOutputStream时最后一个块不完整,即使使用填充AES / CBC / PKCS5Padding
非常感谢任何帮助!我想我只是缺少了一些简单的东西......
更新!
人们说得对,这是关于盐的问题。当我去掉盐时,问题得到了解决...再深入一点发现,问题出在盐+ Pass上,但因为盐是byte[]而Pass是字符串。我将salt更改为String,然后使用salt.concat(Pass),问题就解决了!