MD5 Encryption in Android
Lets start the tutorial for md5 encryption in android.
MD5 is the best practice to handle the secured data like password etc.
In android we can able to achieve this using few simple code.
Create new android project and copy and paste the below java code.
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class DataEncryptionActivity extends Activity {
String strNormalValue, strEncrytedValue;
EditText edtValue;
Button btnEncrypt;
TextView tvEncrypt;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edtValue = (EditText) this.findViewById(R.id.edt_to_encrypt);
tvEncrypt = (TextView) this.findViewById(R.id.txt_encrypt);
btnEncrypt = (Button) this.findViewById(R.id.btn_encrypt);
btnEncrypt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
strNormalValue = edtValue.getText().toString().trim();
strEncrytedValue = getMD5(strNormalValue);
tvEncrypt.setText(strEncrytedValue);
}
});
}
public String getMD5(String src) {
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest
.getInstance("MD5");
digest.update(src.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String h = Integer.toHexString(0xFF & messageDigest[i]);
while (h.length() < 2)
h = "0" + h;
hexString.append(h);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
}
Copy and paste it in main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/edt_to_encrypt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/btn_encrypt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Convert to MD5" />
<TextView
android:id="@+id/txt_encrypt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="false" />
</LinearLayout>
Full Source code for MD5 Encryption.
Comments
Post a Comment