com.google.gson.Gson class 失败 javax.crypto.SecretKey?

com.google.gson.Gson class fails with javax.crypto.SecretKey?

我在一些加密操作中存储了SecretKey,我以后需要用到。存储时我将其转换为字符串:

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

但是由于以下代码检索失败:

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

此外,即使使用详细消息过滤器,我也没有在 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
}

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

SecretKey 的 json 结构如下:

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

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

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

更新

将 SecretKey 转换为 json 字符串,反之亦然功能如下:

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");
}

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

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

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