I am trying to encrypt username and password data in MySQL database using PHP and Android. I am keeping the data as a BLOB type in MySQL DB along with the public key in the Database. NOTE : Retrieval and Submission of done is done in JSON format using HTTP.
But : I am getting the wrong data(easily visible in log below that (sid,a) is used for (username,password) and (YzJsawo=,YzJsawo=) is obtained) after decryption despite using Base64encoding to retrieve the data.(I have already tried it with CHAR and VARCHAR but no success).
Please help I have my project submission tomorrow. Worried. If at all u think that u won't be able to read the code that i have written please provide me with an alternative for above problem or a link where similar problem is discussed(Although i couldn't find one).
Here is what I am trying to do.
Encryption Part
protected String doInBackground(String... args) {
runOnUiThread(new Runnable() {
public void run() {
userStr = inputUsername.getText().toString();
passStr = inputPassword.getText().toString();
confirmpass = inputConfirmPass.getText().toString();
if(userStr.equals("") || passStr.equals("") || confirmpass.equals(""))
{
Toast.makeText(getApplicationContext(),"Enter all the fields" ,Toast.LENGTH_SHORT).show();
}
else
{
if(passStr.equals(confirmpass))
{
//Encoding the string using RSA Algorithm
// Original text
valid=1;
// Generate key pair for 1024-bit RSA encryption and decryption
Key publicKey = null;
Key privateKey = null;
String publicKeyStr;
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp = kpg.genKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();
} catch (Exception e) {
Log.e("", "RSA key pair error");
}
byte[] encodedUser = null,encodedPassword = null;
//Changing public key to str to transfer it between activities
publicKeyStr = Base64.encodeToString(publicKey.getEncoded(), Base64.DEFAULT);
try {
//Encoding Username
// Encode the original data with RSA private key
Cipher c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
c.init(Cipher.ENCRYPT_MODE, privateKey);
encodedUser = c.doFinal(Base64.encode(userStr.getBytes("utf-8"),Base64.DEFAULT));
//Encoding Password
encodedPassword = c.doFinal(Base64.encode(passStr.getBytes("utf-8"),Base64.DEFAULT));
} catch (Exception e) {
Log.e("Error Type:", "RSA encryption error");
}
String UsernameStrEncod,PasswordStrEncod;
UsernameStrEncod = Base64.encodeToString(encodedUser, Base64.DEFAULT);
PasswordStrEncod = Base64.encodeToString(encodedPassword, Base64.DEFAULT);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", UsernameStrEncod));
params.add(new BasicNameValuePair("password", PasswordStrEncod));
params.add(new BasicNameValuePair("publickey", publicKeyStr));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_register_user,"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), LoginActivity.class);
//i.putExtra("encodedUser", encodedUser);
//i.putExtra("publicKey", publicKeyStr);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else
Toast.makeText(getApplicationContext(),"Both the passwords do not match" ,Toast.LENGTH_SHORT).show();
}
}
});
return null;
}
Decryption Part
protected String doInBackground(String... params)
{
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
int found=0;
try {
//EditText variable initialization
inputUsername = (EditText) findViewById(R.id.UsernameID);
inputPassword = (EditText) findViewById(R.id.PasswordID);
//Converting EditText to string
user = inputUsername.getText().toString();
password = inputPassword.getText().toString();
if(user.equals("") || (password.equals("")))
Toast.makeText(getApplicationContext(),"Enter Both the fields" ,Toast.LENGTH_SHORT).show();
// Building Parameters
else
{
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", user));
params.add(new BasicNameValuePair("password", password));
Log.d(user,password);
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(url_login_details, "GET", params);
// check your log for json response
Log.d("Login Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1)
{
// successfully received product details
JSONArray userArray = json.getJSONArray(TAG_USER); // JSON Array
for(int j=0; (j<userArray.length()) && (found==0); ++j)
{
// get first product object from JSON Array
JSONObject userObj = userArray.getJSONObject(j);
String u = userObj.getString(TAG_USERNAME);
String p = userObj.getString(TAG_PASSWORD);
String publicKey = userObj.getString(TAG_PUBLICKEY);
Log.d("usernameBlob:", u);
Log.d("passwordBlob:", p);
Log.d("publickeyBlob:", publicKey);
//Decoding the data obtained from DB
byte[] UsernameByteDecod = null, PasswordByteDecod = null;
String UsernameStrDecod = null,PasswordStrDecod = null;
try {
//Converting the string public key into key type
byte[] keyBytes = Base64.decode(publicKey.getBytes("utf-8"),Base64.DEFAULT);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publickey = keyFactory.generatePublic(spec);
Cipher c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
c.init(Cipher.DECRYPT_MODE, publickey);
//Decoding the data
UsernameByteDecod = c.doFinal(Base64.decode(u.getBytes("UTF-8"),Base64.DEFAULT));
PasswordByteDecod = c.doFinal(Base64.decode(u.getBytes("UTF-8"),Base64.DEFAULT));
UsernameStrDecod = Base64.encodeToString(UsernameByteDecod, Base64.DEFAULT);
PasswordStrDecod = Base64.encodeToString(PasswordByteDecod, Base64.DEFAULT);
Log.d("Username:",UsernameStrDecod);
Log.d("Password:",PasswordStrDecod);
} catch (Exception e) {
Log.e("RSA Error:", "RSA decryption error");
e.printStackTrace();
}
if((user.equals(UsernameStrDecod)) && (password.equals(PasswordStrDecod)))
{
found=1;
}
else if(user.equals(u))
{
Toast.makeText(getApplicationContext(),"Password is Incorrect" ,Toast.LENGTH_SHORT).show();
break;
}
else
{
}
// display product data in EditText
}
}
else
{
Toast.makeText(getApplicationContext(),"You are not registered, Register Here" ,Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(i);
}
if(found==1)
{
Toast.makeText(getApplicationContext(),"Welcome "+ user ,Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
//finish();
}
else if(found==0)
{
Toast.makeText(getApplicationContext(),"You are not registered, Register Here" ,Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(i);
//finish();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
PHP Script for Inserting data after Encryption
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['publickey']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$publickey = $_POST['publickey'];
// include db connect class
require_once __DIR__ . '/users_db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO user(username, password, publickey) VALUES('$username', '$password', '$publickey')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Successfull Registration.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
PHP Script for retrieving data and Decrypting it afterwards
<?php
/*
* Following code will list all the products
*
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/users_db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query("SELECT * FROM user") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["user"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["username"] = $row["username"];
$product["password"] = $row["password"];
$product["publickey"] = $row["publickey"];
// push single product into final response array
array_push($response["user"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No user found";
// echo no users JSON
echo json_encode($response);
}
?>
Logcat
05-03 23:58:53.584: D/sid(26226): a
05-03 23:58:53.640: D/Login Details(26226): {"user":[{"username":"oBYxmonY0wmJhVbCZ69S\/OJYiVt7socheDmRfJM1vUyw1ACBA9ZraePdFJsvbYSjce\/UhxemRE+x\nRyF4d2GYLxfw+s0sw6Xo0P7T5bJ2gDqw7Grn+aAolhS4xzPnZm\/tytTVHVgyqdx\/UbWn8txu8h5D\nVj8WmLa0IstgcmvHRtQ=\n","password":"j\/iLoIjK5a1vJulTE4Hv7ofMQF48krK3xiDiBwGOJBsK7eGGnRskwjV+xUyT+jT3IeWQHbLncdWD\neG9HrQKiM2kE+t5SQ6CkCXVTcfWg8\/axmQC+UQt\/Q3s81UC64AMVBB0J0\/cZrdGeAQ8bGGVDkwC2\nf9WTl8RoAiMmpl6Q7gs=\n","publickey":"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxZzks60BsVN6D\/2wJhXrURkzuDvljjEcN3hW6\n4JbjxK4UJb5T0uVtzULvyfceHcySlhqo2AcP0s+EybPuaZ+dwI1Mhd7VYg1Xeyz5EvLStAOreY3G\n3yweb4sryGvcty88Q4XkC\/KrcURGAT8QBzNVSc9cHJa+qPf1\/t+Eb9Yb3wIDAQAB\n"},{"username":"YjvJ6eNMNtU649ZgordslPURCNOt8ZgfkAm5WzNzlxxYZiYldAIg3PeOHjiOUsIunZuLlQ7\/uJG2\n9GBCTRDbQJeqOJ\/YaFePEjuydEHyN7CAay4ocUklVQkTdgSLkTEtU+RFifqGs3fM67fyQD3w8xq6\nyHb3vZMdJ3AS8cFS0fM=\n","password":"fr+vrqHzYBgvuHAnaRpNb+V9I0hn9crCuHNabF0v\/8PAY3a11fnE9v924sUTcgh4BDJVSzp\/sSxQ\nL1i7noh45buKPrZEz6BfGgiGqpwbjXTLKIyuNFjIyA3qbBFs9rxhYS00AsKmKO+zoB5AZ+I4amQQ\nwa3QKC\/wtHjPtV7BfwY=\n","publickey":"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDG9gggL32xWWArvV2FClklGPGUZPpsHUavy+l7\nGME2RwuI+nlARq9dM4TGyAY2A6APTj\/lD6\/uVfmvFvuo1MC2OSGBNNYNngoJ+J1Bg9kjwJUEktEF\nsO2L0iCTu0EQM+1SXlWe20k2sp4UmKdP0Rx3L8NqhbJLLoPLfA5qhCwNDQIDAQAB\n"}],"success":1}
05-03 23:58:53.640: D/usernameBlob:(26226): oBYxmonY0wmJhVbCZ69S/OJYiVt7socheDmRfJM1vUyw1ACBA9ZraePdFJsvbYSjce/UhxemRE+x
05-03 23:58:53.640: D/usernameBlob:(26226): RyF4d2GYLxfw+s0sw6Xo0P7T5bJ2gDqw7Grn+aAolhS4xzPnZm/tytTVHVgyqdx/UbWn8txu8h5D
05-03 23:58:53.640: D/usernameBlob:(26226): Vj8WmLa0IstgcmvHRtQ=
05-03 23:58:53.640: D/passwordBlob:(26226): j/iLoIjK5a1vJulTE4Hv7ofMQF48krK3xiDiBwGOJBsK7eGGnRskwjV+xUyT+jT3IeWQHbLncdWD
05-03 23:58:53.640: D/passwordBlob:(26226): eG9HrQKiM2kE+t5SQ6CkCXVTcfWg8/axmQC+UQt/Q3s81UC64AMVBB0J0/cZrdGeAQ8bGGVDkwC2
05-03 23:58:53.640: D/passwordBlob:(26226): f9WTl8RoAiMmpl6Q7gs=
05-03 23:58:53.640: D/publickeyBlob:(26226): MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxZzks60BsVN6D/2wJhXrURkzuDvljjEcN3hW6
05-03 23:58:53.640: D/publickeyBlob:(26226): 4JbjxK4UJb5T0uVtzULvyfceHcySlhqo2AcP0s+EybPuaZ+dwI1Mhd7VYg1Xeyz5EvLStAOreY3G
05-03 23:58:53.640: D/publickeyBlob:(26226): 3yweb4sryGvcty88Q4XkC/KrcURGAT8QBzNVSc9cHJa+qPf1/t+Eb9Yb3wIDAQAB
05-03 23:58:53.641: D/Username:(26226): YzJsawo=
05-03 23:58:53.641: D/Password:(26226): YzJsawo=
05-03 23:58:53.641: D/usernameBlob:(26226): YjvJ6eNMNtU649ZgordslPURCNOt8ZgfkAm5WzNzlxxYZiYldAIg3PeOHjiOUsIunZuLlQ7/uJG2
05-03 23:58:53.641: D/usernameBlob:(26226): 9GBCTRDbQJeqOJ/YaFePEjuydEHyN7CAay4ocUklVQkTdgSLkTEtU+RFifqGs3fM67fyQD3w8xq6
05-03 23:58:53.641: D/usernameBlob:(26226): yHb3vZMdJ3AS8cFS0fM=
05-03 23:58:53.641: D/passwordBlob:(26226): fr+vrqHzYBgvuHAnaRpNb+V9I0hn9crCuHNabF0v/8PAY3a11fnE9v924sUTcgh4BDJVSzp/sSxQ
05-03 23:58:53.641: D/passwordBlob:(26226): L1i7noh45buKPrZEz6BfGgiGqpwbjXTLKIyuNFjIyA3qbBFs9rxhYS00AsKmKO+zoB5AZ+I4amQQ
05-03 23:58:53.641: D/passwordBlob:(26226): wa3QKC/wtHjPtV7BfwY=
05-03 23:58:53.641: D/publickeyBlob:(26226): MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDG9gggL32xWWArvV2FClklGPGUZPpsHUavy+l7
05-03 23:58:53.641: D/publickeyBlob:(26226): GME2RwuI+nlARq9dM4TGyAY2A6APTj/lD6/uVfmvFvuo1MC2OSGBNNYNngoJ+J1Bg9kjwJUEktEF
05-03 23:58:53.641: D/publickeyBlob:(26226): sO2L0iCTu0EQM+1SXlWe20k2sp4UmKdP0Rx3L8NqhbJLLoPLfA5qhCwNDQIDAQAB
05-03 23:58:53.647: D/Username:(26226): YzJsawo=
05-03 23:58:53.647: D/Password:(26226): YzJsawo=