我想SharedPreferences
使用 gson 存储一个加密的 Profile 对象。
这是我的代码:
public void saveProfile(Profile newProfile) {
try {
Log.i(C.TAG, newProfile.toString());
SharedPreferences.Editor editor = prefs.edit();
String profileJSONfied = new Gson().toJson(newProfile);
Log.i(C.TAG, profileJSONfied);
byte[] cleartext = profileJSONfied.getBytes(HTTP.UTF_8);
Log.i(C.TAG, cleartext.toString());
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
String encrypedProfile = Base64.encodeToString(cipher.doFinal(cleartext), Base64.DEFAULT);
Log.i(C.TAG, encrypedProfile);
editor.putString(PROFILE, encrypedProfile);
editor.commit();
profile = newProfile;
} catch (Exception e) {
Log.i(C.TAG, e.getMessage());
}
}
public Profile loadProfile() {
try {
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key);
Log.i(C.TAG, prefs.getString(PROFILE, null));
// byte[] plainTextProfileBytes = Base64.decode(cipher.doFinal(prefs.getString(PROFILE, null).getBytes(HTTP.UTF_8)), Base64.DEFAULT);
byte[] plainTextProfileBytes = Base64.decode(prefs.getString(PROFILE, null).getBytes(HTTP.UTF_8), Base64.DEFAULT);
Log.i(C.TAG, new String(plainTextProfileBytes, HTTP.UTF_8));
profile = new Gson().fromJson(new String(plainTextProfileBytes, HTTP.UTF_8), PROFILE_TYPE);
Log.i(C.TAG, profile.toString());
} catch (Exception e) {
Log.i(C.TAG, e.getMessage());
}
return profile;
}
这是一个输出示例(按 Log 的顺序排列):
saveProfile:
Profile@4146a1d8
{"email":"aaa","firstName":"aaa","lastName":"aaa","postal":"aaa" 等...}
[B@414819b0
+nLS7XhRoIFPBeC11 /h6mMz6hFfc8js03QJ8VwVZH+dPBeC11/h6mJ448CLGPNzz+bU669XpAI8VXchYQJr7mgDwHpeoSrP4BMACydjKpC8Q9atbk9xz6HNqDpNOiqaa75hFM+r9pzm55/E2E2tdjz4s5OzNNppAPzmtS69tZAZLPuYt1kvnJehHa6fDt2o5UCv6VukCwvVgt+UDcCqCKvF22Iv6vdMXWTcm
At this point I think everything went as expected. 问题出在下面,破译操作
loadProfile:
�r��xQ��O���z����W��;4�|WY�O���z��8�"�<��:������]�X @��������J�����ʤ/�[��s�sj�N����E3��9���6k]�>,���6�@?9� K�mdK>�-�K�%�Gk�÷j9P+�V���`��p*�*�v؋��Y7&���-A
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 21
如果我不是:
byte[] plainTextProfileBytes = Base64.decode(prefs.getString(PROFILE,null).getBytes(HTTP.UTF_8), Base64.DEFAULT);
我用:
byte[] plainTextProfileBytes = Base64.decode(cipher.doFinal(prefs.getString(PROFILE, null).getBytes(HTTP.UTF_8)), Base64.DEFAULT);
错误将是:
pad block corrupted
我在这里想念什么?
谢谢你的时间。