お世話になります。
前提・実現したいこと
平文自体をキーにして暗号化するプログラムを書いたのですが、なぜか失敗します。
発生している問題・エラーメッセージ
暗号文を復号化した時、先頭と末尾に、平文に無い妙な文字が紛れています。
それ以外は正常に復号化されています。
該当のソースコード
暗号化は下記の通りです。
暗号文はシェアードプレファレンスに保存しています。
java
1 2private void angouka(String hirabun) 3{ 4 byte[] hirabunBytes=null; 5 try { 6 hirabunBytes = hirabun.getBytes("UTF-8"); 7 }catch (Exception e) 8 { 9 10 } 11 int num0; 12 for(int num=0;num<3;num++) 13 { 14 for(num0=1;num0<hirabunBytes.length-1;num0++) 15 { 16 hirabunBytes[num0]=(byte)(hirabunBytes[num0]^ hirabunBytes[num0-1]); 17 } 18 hirabunBytes[0]=(byte)( hirabunBytes[0] ^ hirabunBytes[hirabunBytes.length-1] ); 19 20 } 21 SharedPreferences sharedPreferences=getSharedPreferences("data",MODE_PRIVATE); 22 23 SharedPreferences.Editor editor= sharedPreferences.edit(); 24 25 editor.putString("data", Base64.encodeToString(hirabunBytes,Base64.NO_WRAP)).apply(); 26}
復号化は下記の通りです。暗号文はシェアードプレファレンスから引っ張り出してきます。
java
1 SharedPreferences sharedPreferences=getSharedPreferences("data",MODE_PRIVATE); 2 String saveddata=sharedPreferences.getString("data",""); 3 4 if(!saveddata.equals("")) 5 { 6 int counter0; 7 byte[] textbytes=Base64.decode(saveddata,Base64.NO_WRAP); 8 int textbytelen=textbytes.length; 9 String ret=""; 10 for(int counter=0;counter<3;counter++) 11 { 12 textbytes[0]=((byte)(textbytes[textbytelen-1] ^ textbytes[0])); 13 for(counter0=textbytelen-1;counter0>=1 ;counter0--) 14 { 15 textbytes[counter0]=(byte)(textbytes[counter0] ^(textbytes[counter0-1])); 16 } 17 } 18 try{ 19 ret=new String(textbytes,"UTF-8");//このretに復号化された平文が入る、はず。 20 } 21 catch (Exception ex) 22 { 23 24 } 25}
これらのコードで
hogehuga
を暗号化すると、
CWYIY2V7GmE=
となり、これを復号化したところ、
}ehuge
と出ました。中括弧は元の文字にはありませんし、
そこから左側は化け文字になっています。
最後の文字も、平文ではaですが、復号化するとe
になりました。
補足情報(FW/ツールのバージョンなど)
android studio 3.1使用
宜しくお願い致します。
回答1件
あなたの回答
tips
プレビュー