I encode a string, get bytes, convert to a string, and save it with SharedPreferences . In the future, decode the line does not work, how to get an array of bytes?

 private void main(String[] args) throws LoginException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException { String s = "ab"; Cipher cipher = Cipher.getInstance("AES"); KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); final SecretKey key = kgen.generateKey(); //SecretKeySpec key = new SecretKeySpec("bar12345Bar12345".getBytes(),"AES"); time.setText(String.valueOf(key)); cipher.init(Cipher.ENCRYPT_MODE,key); final byte[] bytes = cipher.doFinal(s.getBytes("UTF-8")); String s=new String(bytes, "UTF-8"); for (byte b : bytes) kkk+=(char) b; //time.setText(s); byte[] byteArray = kkk.getBytes(); // String str = new String(bytes, StandardCharsets.UTF_8); Cipher decript = Cipher.getInstance("AES"); decript.init(Cipher.DECRYPT_MODE,key); byte[] decriptedBytes = decript.doFinal(bytes); for (byte b : decriptedBytes) kk+=(char) b; time.setText(kk); reg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { sPref = getSharedPreferences("save",MODE_PRIVATE); SharedPreferences.Editor ed = sPref.edit(); ed.putString(SAVED_L, s); ed.commit(); Toast.makeText(RegActivity.this, kk+String.valueOf(key), Toast.LENGTH_SHORT).show(); } }); } 

    2 answers 2

    You use the wrong approach, strings are not intended to store arbitrary sets of bytes. Try encrypted bytes encoded in base64. When decrypting, decode the base64 string into bytes, and then decode them as usual.

    • String encoded = Base64.encodeToString (bytes, 4); what is the second parameter for - KTA
    • There is already java.util.Base64 , without any parameters: String x = Base64.getEncoder().encodeToString(bytes); - Zergatul

    The Base64 version is the most ideologically correct, but not the only one.

    You can use Charsets.ISO_8859_1 instead of UTF-8 to convert an arbitrary set of bytes to a string and back.

    But it’s worth remembering that this line is not for displaying in UI or sending in text form!