将密钥转换为字符串,反之亦然 [英] Converting Secret Key into a String and Vice Versa

查看:46
本文介绍了将密钥转换为字符串,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在生成一个密钥并需要将其存储在数据库中,因此我将其转换为字符串,但要从字符串中取回密钥.实现这一目标的可能方法是什么?

I am generating a key and need to store it in DB, so I convert it into a String, but to get back the key from the String. What are the possible ways of accomplishing this?

我的代码是,

SecretKey key = KeyGenerator.getInstance("AES").generateKey();
String stringKey=key.toString();
System.out.println(stringKey);

如何从字符串中取回密钥?

How can I get the key back from the String?

推荐答案

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

You can convert the SecretKey to a byte array (byte[]), then Base64 encode that to a String. To convert back to a SecretKey, Base64 decode the String and use it in a SecretKeySpec to rebuild your original SecretKey.

SecretKey 到字符串:

// create new key
SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
// get base64 encoded version of the key
String encodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded());

SecretKey 的字符串:

// decode the base64 encoded string
byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
// rebuild key using SecretKeySpec
SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES"); 

<小时>

对于 Java 7 及之前版本(包括 Android):

注意我:您可以跳过 Base64 编码/解码部分,只将 byte[] 存储在 SQLite 中.也就是说,执行 Base64 编码/解码不是一项昂贵的操作,您可以将字符串存储在几乎任何数据库中而不会出现问题.


For Java 7 and before (including Android):

NOTE I: you can skip the Base64 encoding/decoding part and just store the byte[] in SQLite. That said, performing Base64 encoding/decoding is not an expensive operation and you can store strings in almost any DB without issues.

注意二:较早的 Java 版本在 java.langjava.util 包之一中不包含 Base64.然而,可以使用来自 Apache Commons Codec 的编解码器,充气城堡Guava.

NOTE II: Earlier Java versions do not include a Base64 in one of the java.lang or java.util packages. It is however possible to use codecs from Apache Commons Codec, Bouncy Castle or 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) {/* LOG YOUR EXCEPTION */}

    if (secretKey != null) {stringKey = Base64.encodeToString(secretKey.getEncoded(), Base64.DEFAULT)}

SecretKey 的字符串:

// DECODE YOUR BASE64 STRING
// REBUILD KEY USING SecretKeySpec

    byte[] encodedKey     = Base64.decode(stringKey, Base64.DEFAULT);
    SecretKey originalKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");

这篇关于将密钥转换为字符串,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆