我正在生成一个秘密密钥,如下所示:
key = KeyGenerator.getInstance(ALGO_SECRET_KEY_GENERATOR).generateKey();
我想将此密钥发送给另一个活动。如果我使用意图,则需要将其从Secret key转换为String。谁能告诉我有关密钥转换/副词...
答案 0 :(得分:1)
只需执行以下步骤即可。
从键到字符串
`SecretKey secretKey = KeyGenerator.getInstance("ALGO_SECRET_KEY_GENERATOR").generateKey();
// Crate base64 string
String encodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded());`
从字符串到键
`// decode base64 string
byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
// rebuild key using SecretKeySpec
SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "ALGO_SECRET_KEY_GENERATOR"); `
可从api版本8中获得
`SecretKey secretKey = null;
try {
secretKey = KeyGenerator.getInstance("AES").generateKey();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
byte encoded[] = secretKey.getEncoded();
String str = android.util.Base64.encodeToString(encoded , 0);
byte decoded[] = android.util.Base64.decode(str , 0);
SecretKey originalKey = new SecretKeySpec(decoded, 0, decoded.length, "AES");'