How to encrypt a string in Android Using Base64?
package com.coderzheaven.encryptstring;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Base64;
@SuppressLint({ "WorldReadableFiles", "WorldWriteableFiles" })
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
saveText("CoderzHeaven");
System.out.println(getText());
}
public void saveText(String text) {
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs",
MODE_WORLD_READABLE);
SharedPreferences.Editor editor = myPrefs.edit();
text = Base64.encodeToString(text.getBytes(), Base64.DEFAULT);
editor.putString("some_text", text);
editor.commit();
}
public String getText() {
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs",
MODE_WORLD_WRITEABLE);
String text = myPrefs.getString("some_text", null);
text = new String(Base64.decode(text, Base64.DEFAULT));
return text;
}
}
Please check the LogCat for output.
Join the Forum discussion on this post
Link to this post!