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;
}
出力例を次に示します (ログの順序で並べ替えます)。
saveProfile:
Profile@4146a1d8
{"email":"aaa","firstName":"aaa","lastName":"aaa","postal":"aaa", etc...}
[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
ここで何が欠けていますか?
御時間ありがとうございます。