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