将密钥转换为字符串,反之亦然

将密钥转换为字符串,反之亦然,第1张

将密钥转换为字符串,反之亦然

您可以将转换

SecretKey
为字节数组(
byte[]
),然后base64将其编码
String
。要转换回a
SecretKey
,base64 会对String进行解码,并在a中使用它
SecretKeySpec
来重建您的原始字符串
SecretKey

对于Java 8

字符串的SecretKey:

// create new keySecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();// get base64 enpred version of the keyString enpredKey = base64.getEnprer().enpreToString(secretKey.getEnpred());

字符串到SecretKey:

// depre the base64 enpred stringbyte[] depredKey = base64.getDeprer().depre(enpredKey);// rebuild key using SecretKeySpecSecretKey originalKey = new SecretKeySpec(depredKey, 0, depredKey.length, "AES");

对于Java 7及更低版本(包括Android):

注意I:
您可以跳过base64编码/解码部分,而只将其存储

byte[]
在SQLite中。也就是说,执行base64编码/解码并不是一项昂贵的 *** 作,并且您可以将字符串存储在几乎任何数据库中而不会出现问题。

注意II: 较早的Java版本在

java.lang
java.util
软件包之一中不包括base64 。但是,可以使用Apache
Commons Codec
,Bouncy
Castle或Guava中的编解码器。

字符串的SecretKey:

// CREATE NEW KEY// GET ENCODED VERSION OF KEY (THIS CAN BE STORED IN A DB)    SecretKey secretKey;    String stringKey;    try {secretKey = KeyGenerator.getInstance("AES").generateKey();}    catch (NoSuchAlgorithmException e) {}    if (secretKey != null) {stringKey = base64.enpreToString(secretKey.getEnpred(), base64.DEFAULT)}

字符串到SecretKey:

// DECODE YOUR base64 STRING// REBUILD KEY USING SecretKeySpec    byte[] enpredKey     = base64.depre(stringKey, base64.DEFAULT);    SecretKey originalKey = new SecretKeySpec(enpredKey, 0, enpredKey.length, "AES");


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5477843.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-12
下一篇2022-12-12

发表评论

登录后才能评论

评论列表(0条)

    保存