1

我已经SecretKey在一些加密操作期间存储了我以后需要使用的。在存储时,我将其转换为字符串:

String keyAsString = new Gson().toJson(key);

但是在检索以下代码时失败:

   SecretKey secKey =  new Gson().fromJson(keyAsString, SecretKey.class);

此外,即使使用 Verbose 消息过滤器,我也没有在 LogCat 中获得任何单一提示。我尝试在 try catch 中使用调试点包围代码(希望在调试时可以得到任何异常跟踪):

try {
SecretKey secKey =  new Gson().fromJson(keyAsString, SecretKey.class); // One debug point here
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e)); // And one debug point here
}

但是调试器不会在两个调试点停止,立即在设备应用程序崩溃并显示不幸的应用程序崩溃消息。

save for 的 json 结构SecretKey如下:

{
  "algorithm": "AES",
  "key": [
   integer1, integre2, ....
  ]
}

注意:integer1、integer2 ... 是出于安全目的的实际数字我没有发布原始结果数字。

可能出了什么问题?这样的存储SecretKey是不允许的吗?

更新

使用 Gson 将 SecretKey 转换为 json 字符串,反之亦然是一个坏主意,正如下面 jonathanrz 所回答的那样,我遵循了他的回答并在 android 中编写了两个实用函数来将 SecretKey 转换为字符串,反之亦然函数如下:

public static String secretKeyToString(SecretKey key) {
  return Base64.encodeToString(key.getEncoded(), Base64.DEFAULT);
}

public static SecretKey encodedStringToSecretKey(String encodedKey) {
  byte[] decodedKey = Base64.decode(encodedKey, Base64.DEFAULT);
  return new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
}
4

1 回答 1

1

您应该将密钥解析为字符串,然后使用SecretKeyFactory.translateKey解析密钥。

更新:在你编辑你的问题后,我看到你的输出不仅仅是一个字符串。所以你需要创建一个代表你的 json 的类,用它解析响应并用 translateKey 构造每个键。GSON 只能解析一个 json,如果该类具有与 json 中的 key 相同名称和相同类型的属性,而 SecretKey 则不是这样。

UPDATE2: translateKey 无法从字符串创建键。从字符串创建密钥的选项是这样的:Converting Secret Key into a String and Vice Versa

于 2017-06-03T16:04:00.320 回答