Reputation: 505
Hi I want to encrypt a string in android inorder to store and later for showing I have to decrypt it. Is it possible to do md5 hashing or any other hashing in android. Please provide me an example.
Upvotes: 7
Views: 36977
Reputation: 1408
Sample:
For encryption
MAHEncryptor mahEncryptor = MAHEncryptor.newInstance("This is sample SecretKeyPhrase");
String encrypted = mahEncryptor.encode("This is MAHEncryptorLib java sample");
For decryption
MAHEncryptor mahEncryptor = MAHEncryptor.newInstance("This is sample SecretKeyPhrase");
String decrypted = mahEncryptor.decode("4Vi86K/JL9gKclQahacrKLrEZL6/0vOpS4yPVm1hSLhhDsCMJTyd4A==");
Upvotes: 0
Reputation: 10623
When You want to encrypt a string on one side and decrypt it on other side the use this code its working good.Just copy this code and run in you eclipse, it will solve your problem
Encryption Method for String
final int shift_key = 4; //it is the shift key to move charcter, like if i have 'a' then a=97+4=101 which =e and thus it changes
String plainText = "adhami piran";
char character;
char ch[]=new char[plainText.length()];//for storing encrypt char
for (int iteration = 0; iteration < plainText.length(); iteration++)
{
character = plainText.charAt(iteration); //get characters
character = (char) (character + shift_key); //perform shift
} ch[iteration]=character;//assign char to char array
String encryptstr = String.valueOf(ch);//converting char array to string
Toast.makeText(this, "Encrypt string is "+ encryptstr Toast.LENGTH_LONG).show();
Decrypting Method for String
for(int i=0;i<encryptstr.length();i++)
{
character=str.charAt(i);
character = (char) (character -shift_key); //perform shift
ch[i]=character;
}
Stirng decryptstr = String.valueOf(ch);
Toast.makeText(this, "Decrypted String is "+decryptstr, Toast.LENGTH_LONG).show();
Upvotes: -1
Reputation: 15612
android.util.Base64
encoding is good enough if you want to store something e.g. in a share preferences file:
Here is what I do:
Storing:
public void saveSomeText (String text) {
SharedPreferences.Editor editor = prefs.edit();
if (Utils.isEmpty( text ))
text = null;
else
text = Base64.encodeToString( text.getBytes(), Base64.DEFAULT );
editor.putString( "some_text", text );
editor.commit();
}
Retrieval:
public String getSomeText () {
String text = prefs.getString( "some_text", null );
if (!Utils.isEmpty( passwd )) {
text = new String( Base64.decode( text, Base64.DEFAULT ) );
}
return text;
}
Upvotes: 3
Reputation: 4883
Read this article here->(How_to_encrypt_and_decrypt_strings.rhtml). It is pretty much what you want. The technique there uses .getInstance("AES");
If you want MD5 just replaces the AES with MD5.
Upvotes: -4
Reputation: 135
The javax.crypto package does everything you need
http://developer.android.com/reference/javax/crypto/package-summary.html
Upvotes: 3