您好我在这篇文章5777105
中使用了密码但解密代码仍会阻塞,直到达到缓冲区大小。你知道另一种让它无阻塞的方法吗?请注意,解密部分正在Android上运行。
加密部分:
CipherInputStream cis;
String salt = "1234567890123456";
String password = "abcdEFGH";
password = password.concat(salt);
String validpassword = password.substring(0, 16);
SecretKeySpec secretKey = new SecretKeySpec(validpassword.getBytes(),"AES");
AlgorithmParameterSpec paramSpec = new IvParameterSpec(salt.getBytes());
try {
// Creation of Cipher objects
Cipher encrypt =
Cipher.getInstance("AES/CFB8/NoPadding");
encrypt.init(Cipher.ENCRYPT_MODE, secretKey,paramSpec);
// Open the file
try {
fis = new FileInputStream(file);
} catch(IOException err) {
System.out.println("Cannot open file!");
return null;
}
cis = new CipherInputStream(fis, encrypt);
// Write to the Encrypted file
fos = new FileOutputStream(desFile);
byte[] b = new byte[256];
int i = cis.read(b);
while (i != -1) {
fos.write(b, 0, i);
i = cis.read(b);
}
解密部分:
CipherInputStream cis;
String salt = "1234567890123456";
String password = "abcdEFGH";
password = password.concat(salt);
String validpassword = password.substring(0, 16);
SecretKeySpec secretKey =new SecretKeySpec(validpassword.getBytes(),"AES");
AlgorithmParameterSpec paramSpec = new IvParameterSpec(salt.getBytes());
try {
// Creation of Cipher objects
Cipher decrypt =
Cipher.getInstance("AES/CFB8/NoPadding");
decrypt.init(Cipher.DECRYPT_MODE, secretKey,paramSpec);
// Open the Encrypted file
cis = new CipherInputStream(is, decrypt);
int bytesRead;
int current = 0;
byte[] b = new byte[256];
bytesRead = cis.read(b,0,256);
答案 0 :(得分:0)
cis.read被阻止的原因很简单:Cipher流包裹套接字流(将套接字流传递给Cipher流构造函数)因此,无论何时调用Cipher流上的读取,它都会导致密码流中的代码从套接字读取数据,以便它可以解密数据。这是代码块的位置(从套接字流中读取)。
在UI线程中运行此代码时,阻塞unitll应该没有任何问题。您可以在另一个工作线程上运行此代码,以便您的UI不会冻结