[英]String to Secret key conversion/Vice Versa
我正在生成一个如下所示的key = KeyGenerator.getInstance(ALGO_SECRET_KEY_GENERATOR).generateKey();
: key = KeyGenerator.getInstance(ALGO_SECRET_KEY_GENERATOR).generateKey();
我想将此密钥发送到另一个活动。 如果我使用意图,我认为这需要从密钥转换为字符串。 谁能告诉我密钥转换/副反...
只需按照以下步骤操作即可。
从键到字符串
`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");'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.