从文件读取存储的SecretKey

时间:2018-11-14 13:32:15

标签: android

使用以下代码,我可以将SecretKey存储到文件中

public static SecretKey generateKey() throws NoSuchAlgorithmException {
    // Generate a 256-bit key
    final int outputKeyLength = 256;
    SecureRandom secureRandom = new SecureRandom();
    // Do *not* seed secureRandom! Automatically seeded from system entropy.
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(outputKeyLength, secureRandom);
    yourKey = keyGenerator.generateKey();
    return yourKey;
}

yourKey = generateKey();
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "encrypt" + File.separator, "config.xml");

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] filesBytes = yourKey.getEncoded();
bos.write(filesBytes);
bos.flush();
bos.close();

现在如何读取此文件并将bytes []传递给SecretKey变量?例如:

File file = new File(Environment.getExternalStorageDirectory() + File.separator + "convert" + File.separator, "config.xml");

BufferedInputStream buf = new BufferedInputStream(
        new FileInputStream(file));


int length = (int) file.length();
byte[] audio_data = new byte[length];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = buf.read(audio_data)) != -1) {
    output.write(audio_data, 0, bytesRead);
}
byte[] inarry = output.toByteArray();
yourKey=inarry;

问题是yourKey=inarry;,并将字节传递到yourKey变量中,我该如何解决呢?

1 个答案:

答案 0 :(得分:0)

即使我自己从来没有做过此事,但是如果您想将SecretKey写入文件并在以后读取,则可以使用ObjectOutputStreamObjectInputStream

SecretKeySerializable,因此您可以使用这两个功能。

这样写:

FileOutputStream fout = new FileOutputStream("G:\\address.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(yourKey);
oos.close();
fout.close(); 

阅读方式:

FileInputStream fin = new FileInputStream("G:\\address.ser");
ObjectInputStream ois = new ObjectInputStream(fin);
SecretKey yourKey = (SecretKey) ois.readObject();
ois.close();
fin.close(); 

但是,正如我所说的那样,您通常不应该这样做。如果您只想存储密钥,则需要使用KeyStore。如果需要保存以进行发送,则需要将其加密保存。密钥是加密算法中最重要的部分,因此您永远不要像这样将其保存在文件中。