我编写了以下代码来加密java服务器中的zip文件。
public byte[] encrypt(byte[] skey, byte[] data){
SecretKeySpec skeySpec = new SecretKeySpec(skey, "AES");
Cipher cipher;
byte[] encrypted=null;
try {
// Get Cipher instance for AES algorithm
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// Initialize cipher
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
// Encrypt the image byte data
encrypted = cipher.doFinal(data);
}catch(Exception e){
e.printStackTrace();
}
return encrypted;
}
此服务器将此加密的zip文件发送到Android。然后,android用以下代码解密它。
public byte[] decrypt(byte[] skey, FileInputStream fis) {
SecretKeySpec skeySpec = new SecretKeySpec(skey, "AES");
Cipher cipher;
byte[] decryptedData=null;
CipherInputStream cis=null;
try {
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
// Create CipherInputStream to read and decrypt the image data
cis = new CipherInputStream(fis, cipher);
// Write encrypted image data to ByteArrayOutputStream
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
byte[] data = new byte[2048];
while ((cis.read(data)) != -1) {
buffer.write(data);
}
buffer.flush();
decryptedData=buffer.toByteArray();
}catch(Exception e){
e.printStackTrace();
}
finally{
try {
fis.close();
cis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return decryptedData;
}
当我加密普通zip文件时,此文件为21 kb。然后,当我解密加密的zip文件时,zip文件是24 kb,它不能在Android手机中打开。我尝试了一些方法。我可以接受你的建议吗?
感谢。
编辑:已解决
我添加了iv参数cipher.init()方法:
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv.getBytes));
cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(iv.getBytes));
我用以下代码对其进行了修改:
int numRead = 0;
while (numRead = cis.read(data)) != -1) {
buffer.write(data, 0, numRead);
}