将密码输入流转换为字节数组?

时间:2016-04-17 16:52:10

标签: android encryption inputstream

简单地说,我有CipherInputStream,我想将其转换为字节数组。其他帖子没有帮助。如何实现这一目标?

FileInputStream fis = new FileInputStream("dataPath/data");
SecretKeySpec sks = new SecretKeySpec("password".getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, sks);
CipherInputStream cis = new CipherInputStream(fis, cipher);

那么如何从cis

中检索字节数组

1 个答案:

答案 0 :(得分:3)

CipherInputStream是标准InputStream的实现,因此您可以使用ByteArrayOutputStream将其读取为字节数组,例如:

CipherInputStream cis = ...
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[4096];
while ((len = cis.read(buffer, 0, buffer.length)) != -1) {
    baos.write(buffer, 0, len);
}
baos.flush();
byte[] cipherByteArray = baos.toByteArray(); // get the byte array