Cannot insert image into SQL Server database from android using PHP - php

Its been a lot of days i am trying to insert the biometric fingerprint scanned data into MS SQL Server database using android through PHP.
I am sharing my entire code this time , i have to complete it anyhow.
Please friends help me out solving this.
Android Code For Calling the Api:
public void registerFinger(Bitmap scannedImage) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
scannedImage.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] fingerByte = byteArrayOutputStream.toByteArray();
String encodedFingerData = Base64.encodeToString(fingerByte, Base64.DEFAULT);
try {
h = new JSONObject();
h.put("FingerPrint", encodedFingerData);
} catch (Exception e) {
e.printStackTrace();
}
Call<UniversalPojo> call = apiInterfaces.registerFingerPrint(String.valueOf(empId), getRequestBody(h.toString()));
call.enqueue(new Callback<UniversalPojo>() {
#Override
public void onResponse(Call<UniversalPojo> call, Response<UniversalPojo> response) {
if (response.isSuccessful()) {
if (response.body().getStatus().equalsIgnoreCase("true")) {
showDialog("Registration Done.");
} else {
showDialog("Registration Failed.");
}
} else {
showDialog("Registration Failed.");
}
}
#Override
public void onFailure(Call<UniversalPojo> call, Throwable t) {
t.printStackTrace();
showDialog("Registration Failed.");
}
});
}
public RequestBody getRequestBody(String rawString) {
return RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), rawString.toString());
}
RegisterFingerData.php
<?php
require_once 'db_functions.php';
$db = new db_functions();
$data = json_decode(file_get_contents('php://input'), true);
$FingerPrint = $data['FingerPrint'];
//decoding and converting the image into byte array
$a = base64_decode($FingerData);
$b = array();
foreach (str_split($a) as $c) {
$b[] = sprintf("%08b", ord($c));
}
$ifAlreadyExists = $db->registerFinger( $b );
?>
The column FingerData in EMPFINGERMASTER is of the varbinary(MAX) datatype.
registerFinger function
public function registerFinger($fingerPrint)
{
try {
$sqlString = "INSERT INTO EMPFINGERMASTER( FingerData ) values (?)";
$stmt = $this->conn->prepare($sqlString);
$params = array($fingerPrint);
$stmt->execute($params);
$row = $stmt->fetch();
if (!$stmt) {
$arr = $stmt->errorInfo();
print_r($arr);
}
if ($rows) {
echo true;
} else {
echo false;
}
} catch (Exception $e) {
echo 'Message: ' . $e->getMessage();
}
}
GetFingerPrintData() function
public function GetFingerPrintData($myId){
$sqlString = "SELECT FingerData from EMPFINGERMASTER WHERE MyId = 1";
$stmt = $this->conn->prepare($sqlString);
$params = array($myId);
$stmt->execute($params);
$row = $stmt->fetch();
if (!$stmt) {
$arr = $stmt->errorInfo();
print_r($arr);
}
if ($row) {
//reconverting the byte[] array to BASE64 String
$rawResult = $row['FingerData'];
$resim = substr($rawResult, 2);
$bin = hex2bin($rawResult);
$base64_image = base64_encode($bin);
echo $base64_image;
}
}
The data getting stored in the Database is exactly like this :
[B#623a5f2
but if i check in echo , it shows a big data before before converting it into byte[] in RegisterFingerData.php
And i am not be able to get the proper data at the time of retrieving.
My Question is , I want to store the data into DB and retrieve it for checking.
There are a lot of suggestions on other similar questions but after using them i have reached this final code , and still not be able to get the results.

Related

Cannot fetch the value from JsonArray

I am having problem fetching out the value from PHP coding to my android. The logcat shows that
:W/System.err: org.json.JSONException:
No value for posts.
This is my php code:
<?php
require("config1.php");
$query="SELECT commentName,comment FROM discussion_comment WHERE discussID = :discussID";
$query_params=array(':discussID'=> $_POST['discussID']);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
$rows = $stmt->fetchAll();
if ($rows){
$response["success"]=1;
$response["message"]="Post Available";
$response["posts"]= array();
foreach ($rows as $row){
$post = array();
$post["commentName"] = $row["commentName"];
$post["comment"] = $row["comment"];
array_push($response["posts"], $post);
}
echo json_encode($response);
}else {
$response["success"] = 0;
$response["message"] = "No post Available!";
die(json_encode($response));
?>
When is remove the 'WHERE discussID = :discussID"', I am able to fetch the data, but some is not necessary. What other way to write with Where condition.
My java:
private static final String COMMENT_NAME="commentName";
private static final String COMMENT="comment";
private static final String COMMENT_VIEW_URL="http://fysystem.com/show_comment.php";
#Override
protected String doInBackground(String... args) {
try {
json=jsonParser.getJSONFromUrl(COMMENT_VIEW_URL);
JSONArray jsonArray=json.getJSONArray("posts");
for(int i = 0; i<jsonArray.length();i++) {
json=jsonArray.getJSONObject(i);
commentName=json.getString(COMMENT_NAME);
comment=json.getString(COMMENT);
}
Appreciate your help.
PHP
<?php
require("config1.php");
// Default message
$response = array('success'=>0, 'message'=>'Error. Pass required parameters');
// Check discussID exists in POST params
if(isset($_POST['discussID']) && $_POST['discussID']!=""){
$sql = 'SELECT `commentName`, `comment` FROM `discussion_comment` WHERE `discussID` = :discussID';
try {
// Hope $db is defined in config1.php
$stmt = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute(array(':discussID'=> $_POST['discussID']));
$response = array("success"=>0, "message"=>"Discussion Not found");
// If data exists
if($stmt->rowCount()>0){
// Fetching rows with a scrollable cursor
// http://php.net/manual/en/pdostatement.fetch.php
$posts = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$posts[] = array('commentName'=>$row['commentName'], 'comment' => $row['comment']);
}
// Set the success status 1 and add the posts in return response
$response = array('success'=>1, 'message'=>'Discussion found', 'posts'=>$posts);
}
$stmt = null;
}
catch (PDOException $e) {
// print $e->getMessage();
$response = array('success'=>0, 'message'=>'DB Error');
}
}
// Finally return the response
echo json_encode($response);
?>
Andorid
try {
json=jsonParser.getJSONFromUrl(COMMENT_VIEW_URL);
int success = json.getInt('success');
// Check before access posts data
if(success==1){
JSONArray jsonArray=json.getJSONArray("posts");
for(int i = 0; i<jsonArray.length();i++) {
json=jsonArray.getJSONObject(i);
commentName=json.getString(COMMENT_NAME);
comment=json.getString(COMMENT);
}
}else{
// Handle it here if parameters not exist or db error or no discussion found
}
}
Hope this helps!

How to post a string using android-volley and returns json Array of objects for php web service

I'm trying to send a string and returns json array of objects in response like like this:
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.optString("fullname"));
movie.setThumbnailUrl(obj.optString("image"));
movie.setRating(obj.optString("location"));
movie.setYear(obj.getInt("id"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
// adapter.notifyDataSetChanged();
adapter.reloadData();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("fullname", "test"); // fullname is variable and test is value.
return params;
} };
In above code fullname is variable and test is value and using that variable I'm trying to send my variable data in my php variable and perform my query like this:
<?php
header("content-type:application/json");
require_once("dbConnect.php");
$fullname = $_REQUEST["fullname"];
//echo $fullname."11";
$sql = "SELECT id ,image,fullname,location from uploadfinding WHERE fullname like '%$fullname%'";
$res = mysqli_query($conn,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result, array(
"id"=>$row["id"],
"fullname"=>$row["fullname"],
"image"=>$row['image'],
"location"=>$row["location"]));
//echo " over";
}
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($result));
fclose($fp);
echo json_encode($result);
mysqli_close($conn);
?>
But my value test not transfer in php variable $fullname. So problem is how to transfer value test to php variable $fullname.
If you want to receive test data the in PHP script then use this code. You make sure your request method type.
<?php
header("content-type:application/json");
require_once("dbConnect.php");
if($_SERVER['REQUEST_METHOD']=='POST')
{
$fullname = $_POST["fullname"];
echo "Received fullname = ".$fullname;
}
else if($_SERVER['REQUEST_METHOD']=='GET')
{
$fullname = $_POST["fullname"];
echo "Received fullname = ".$fullname;
}
$sql = "SELECT id ,image,fullname,location from uploadfinding WHERE fullname like '%$fullname%'";
$res = mysqli_query($conn,$sql);
if($res)
{
$result = array();
$result["detial"] = array();
while($row = mysqli_fetch_array($res)){
// temporary array to create single category
$tmp = array();
$tmp["id"] = $row["id"];
$tmp["fullname"] = $row["fullname"];
$tmp["image"] = $row["image"];
$tmp["location"] = $row["location"];
$tmp["des"] = $row["ProductDescription"];
// push category to final json array
array_push($result["detial"], $tmp);
}
// keeping response header to json
header('Content-Type: application/json');
// echoing json result
echo json_encode($result);
}
else
{
echo "No date found ";
}
?>
For more detail please check this tutorial and read this and this documentation.
I hope this will help you and you get your answer.

Using volley to retrieve data(multiple rows) from mysql

I'm creating a quiz app and i have to retrive all the question to display.this is my php and java code.i'll store the data in another array.i'm not able to fetch any data from my sql table.
StringRequest stringRequest = new StringRequest(Request.Method.POST,insertUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
jsonArray=new JSONArray(response);
JSONObject jsonObject=jsonArray.getJSONObject(0);
for(int k=0;k<jsonArray.length();k++)
{
question[k]=jsonObject.getString("question");
opta[k]=jsonObject.getString("optionA");
optb[k]=jsonObject.getString("optionB");
optc[k]=jsonObject.getString("optionC");
optd[k]=jsonObject.getString("optionD");
ans[k]=jsonObject.getString("Answers");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Quiz.this,error.toString(),Toast.LENGTH_LONG ).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String,String>();
params.put(ITEM_COURSE,data);
return super.getParams();
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
This is my php code
<?php
require 'initquiz.php';
global $connect;
$response = array();
$course=$_POST["course"];
$query = "SELECT * FROM questions WHERE course='$course'";
$result= mysqli_query($connect,$query) or die(mysqli_error($connect));
$response= array();
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$question = $row[0];
$optionA = $row[2];
$optionB= $row[3];
$optionC = $row[4];
$optionD= $row[5];
$Answers= $row[6];
array_push($response,array("question"=>$question,"optionA"=>$optionA,"optionB"=>$optionB,"optionC"=>$optionC,"optionD"=>$optionD,"Answers"=>$Answers));
}
}
echo json_encode($response);
?>
Issues with your code:
You mixed mysql_* and mysqli_* extension
Your code is vulnerable to SQL injection, use prepared statements
Your fetch could be much simpler
Try to avoid SELECT *, instead select specific fields
Try this approach:
$response = [];
if(isset( $_POST["course"])){
$mysqli = new mysqli("host", "user", "password", "db");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM questions WHERE course = ?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("s", $_POST["course"]);
$stmt->execute();
while ($row = $stmt->fetch_assoc()) {
$response['data'][] = $row;
}
$response['success'] = true;
}
$mysqli->close();
}else{
$response['data'] = 'No Course Sent';
$response['success'] = false;
}
echo json_encode($response);

Posting JSON file on a PHP file from Android Application, and decoding JSON to local variables on PHP

I have been researching this for a while now and not getting anywhere.
What I'm trying to do is to create a registrion/login activities, which will store all access details on a remote SQL database.
My outline of the code was to create the "Registrar" object, convert it to JSON object, and convert that JSON object to a string, and then send that string over httpclient as a post to the PHP page ( which is located on my XAMPP ), kindly take note that I'm using Android Studio Emulator.
My problem:
I don't know if the JSON file is received by the PHP server or not.
Here is my code:
Submit function:
public void goSubmit(View view) throws IOException {
EditText nameEdit = (EditText) findViewById(R.id.nameEdit);
EditText idEdit = (EditText) findViewById(R.id.idEdit);
String name = nameEdit.getText().toString();
String ID = idEdit.getText().toString();
//Creating Student (Registrar) Object
Student registrar = new Student();
registrar.setMajor(majorEdit);
registrar.setName(name);
registrar.setId(ID);
//Creating JSON String
String registrarJSON = null;
try {
registrarJSON = ObjInJSON(registrar);
Toast.makeText(this, registrarJSON, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//Posting JSON String on Remote PHP
String PHPresponse = sendToRegistrationPHP(registrarJSON);
Toast.makeText(this, PHPresponse, Toast.LENGTH_LONG).show();
//Receive PIN from PHP as JSON String
//Parsing JSON string to integer (pin)
//Set PIN in registrar.getpin()
//Passing the object to setPassword Activity condition registrar.pin =! null
}
Student class:
public class Student {
String Id = "NULL" ;
String Major = "NULL";
String Name = "NULL";
String Password = "NULL";
String Pin = "NULL";
public String getPin() {
return Pin;
}
public void setPin(String pin) {
Pin = pin;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getId() {
return Id;
}
public String setId(String id) {
Id = id;
return id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getMajor() {
return Major;
}
public void setMajor(String major) {
Major = major;
}
}
Creating JSON object in string format:
protected String ObjInJSON(Student studentC) throws JSONException, UnsupportedEncodingException {
String ID = studentC.getId();
String Pin = studentC.getPin();
String Major = studentC.getMajor();
String Password = studentC.getPassword();
String Name = studentC.getName();
JSONObject json_obj = new JSONObject();
json_obj.put("id", ID);
json_obj.put("password", Password);
json_obj.put("pin", Pin);
json_obj.put("major", Major);
json_obj.put("name", Name);
return json_obj.toString();
}
Sending to PHP server:
public static String sendToRegistrationPHP(String jarr) throws IOException {
StringBuffer response = null;
try {
String myurl = "10.0.2.2:8070/StudentaccistancePHP/MySqlTEST.php";
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(jarr);
writer.close();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response in universal: " + response.toString());
} catch (Exception exception) {
System.out.println("Exception: " + exception);
}
if (response != null) {
return response.toString();
}
else return "Not WORKING !";
}
PHP server:
<?php
$json = file_get_contents('php://input');
$data = json_decode($json, true);
$ID = $data['id'];
$password = $data['password'];
$pin = "323232";
$major = $data['major'];
$name = $data['name'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "studentassictance";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "INSERT INTO students (id, major, name, password, pin)
VALUES ('$ID', '$major', '$name', '$password', '$pin')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully <br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
However, nothing is inserted to the database.
First, you need to check what arrives as JSON into PHP side. You can
var_dump($json,$data);
after json_encode() call and watch it to be a valid JSON. You can validate it here
Second, show you SHOW CREATE TABLE students
And third, rewrite everything to PDO as it supports named parameters and it would be theoretically easier for you to migrate to another DB engine later if needed. So it would be something like:
<?php
define('DSN','mysql:dbname=test;host=localhost');
define('DB_USERNAME','testuser');
define('DB_PASSWORD','testpassword');
$connect = new PDO(DSN, DB_USERNAME, DB_PASSWORD);
$json = file_get_contents('php://input');
/*$json = '{
"id": "111",
"password": "sfsdfsdf",
"major": "Math",
"name": "Test User"
}';*/
$data = json_decode($json, true);
$ID = $data['id'];
$password = $data['password'];
$pin = "323232";
$major = $data['major'];
$name = $data['name'];
$sql = "INSERT INTO `students`(`id`,`major`, `name`, `password`, `pin`) VALUES(:id, :major, :name, :password, :pin)";
$result = $connect->prepare($sql);
//bind parameter(s) to variable(s)
$result->bindParam( ':id', $ID, PDO::PARAM_INT );
$result->bindParam( ':major', $major, PDO::PARAM_STR );
$result->bindParam( ':name', $name, PDO::PARAM_STR );
$result->bindParam( ':password', $password, PDO::PARAM_STR );
$result->bindParam( ':pin', $pin, PDO::PARAM_STR );
$status = $result->execute();
if ($status)
{
echo "New record created successfully <br>";
} else
{
echo "Error: <br>" .
var_dump($connect->errorInfo(),$status);
}
$connect = null;

Android Device Decryption of PHP RSA encrypted string fails with incorrect decrypted result

The code that encrypts a string PHP-serverside.
I use the PKCS8 and not PKCS1 so that I can unencrypt on Android side.
The code for the Encryption follows:
I use the phpseclib.
include('libs/PHPSecLib/Crypt/RSA.php');
...code to lookup public and private keys stored in database omitted...
$rsa = new Crypt_RSA();
$rsa->loadKey($row['pref_pub_key']); // public key stored in MySQL BLOB.
$plaintext = 'Testing 123';
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS8); //USE PKCS8
$ciphertext = $rsa->encrypt($plaintext);
echo $ciphertext;
$rsa->loadKey($row['pref_priv_key']); // private key stored in MySQL BLOB
echo $rsa->decrypt($ciphertext);
$query = "UPDATE preferences SET pref_license = ?;
//execute query to store the encrypted text in pref_license BLOB field.
try {
$stmt = $db->prepare($query);
$stmt->bindParam(1,$ciphertext);
$stmt->bindParam(2,$ref);
$db->errorInfo();
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error. Couldn't update Pref post with License!" . $ex->getMessage();
echo $response["message"];
die(json_encode($response));
}
I basically encrypt the string, and store it in a BLOB field, for later reference.
I generate the Private Public KEYPAIR and store in BLOB in the following manner, and send the privatekey to the Android device:
include('libs/PHPSecLib/Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS8);
$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS8);
extract($rsa->createKey());
//echo $privatekey . '<br/><br/>' . $publickey; //I can see that it worked!
if (!empty($_POST)) {
//initial update query to store the keys in BLOBS on SERVER MYSQL
$query = "UPDATE preferences SET pref_priv_key = ?, pref_pub_key = ?
WHERE pref_device_serial = ?";
//execute query
try {
$stmt = $db->prepare($query);
$stmt->bindParam(1,$privatekey);
$stmt->bindParam(2,$publickey);
$stmt->bindParam(3,$_POST['p_device_serial']);
$db->errorInfo();
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error. Couldn't update Pref post!" . $ex->getMessage();
die(json_encode($response));
}
}
//then I send the $privatekey to the Android device and save it there.
//to then later decrypt the serverside encrypted string.
$response["success"] = 1;
$response["pk"] = $privatekey;
$response["message"] = "Key Pair successfully generated.";
echo json_encode($response);
On the Android device, I use ans AsyncTask to request the Encrypted String and then read the PrivateKey from the local sqlite blob field, and try and decrypt the string:
class GetLicense extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LicenseActivity.this);
pDialog.setMessage("Retrieving License Data...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
int success;
String elicense;
try {
getPref = LicenseActivity.this.openOrCreateDatabase("aaa.db", Context.MODE_PRIVATE, null);
Cursor c = getPref.rawQuery("SELECT * FROM preferences", null);
Log.d("request!", "starting");
if (c != null) {
if (c.moveToFirst()) {
do {
String Preferences_Id = c.getString(c.getColumnIndex(SupaAttendDb.KEY_ROWID));
String Preferences_UUID = c.getString(c.getColumnIndex(SupaAttendDb.KEY_Preferences_PREFUUID));
String Preferences_Device_Serial = c.getString(c.getColumnIndex(SupaAttendDb.KEY_Preferences_PREFDEVICESERIAL));
sPK = c.getString(c.getColumnIndex(SupaAttendDb.KEY_Preferences_PREFPK));
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("p_uuid", Preferences_UUID));
try {
//Get Encrypted License from server
JSONObject json = jsonParser.makeHttpRequest(
GET_LICENSE_URL, "POST", params);
// full json response
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
sData = json.getString(TAG_LICENSE);
..then I save the the license to Android SQLite. code not required ...
In the onPostExecute, I format the PrivateKey and then try to decrypt the sData, but get the incorrect data back, and not 'Testing 123'.
protected void onPostExecute(String file_url) {
pDialog.dismiss();
String privKeyPEM = sPK.replace("-----BEGIN PRIVATE KEY-----\r\n", "");
privKeyPEM = privKeyPEM.replace("-----END PRIVATE KEY-----", "");
byte[] b = Base64.decode(privKeyPEM,Base64.DEFAULT);
KeyFactory keyFactory = null;
try {
keyFactory = KeyFactory.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(b); //This decodes properly without any exceptions.
PrivateKey privateKey2 = null;
try {
privateKey2 = keyFactory.generatePrivate(privateKeySpec);
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
byte[] decryptedData = null;
Cipher cipher = null;
try {
cipher = Cipher.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
try {
cipher.init(Cipher.DECRYPT_MODE,privateKey2);
} catch (InvalidKeyException e) {
e.printStackTrace();
}
byte[] sD = Base64.decode(sData, Base64.DEFAULT);// Here I try to get the encrypted string retrieved from server into a byte[].
try {
decryptedData = cipher.doFinal(sD); // no errors, but I get the incorrect unencrypted string.
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
if (decryptedData != null){
String decrypted = new String(decryptedData);
//decryptedData = Base64.encode(decryptedData,Base64.DEFAULT);
Toast.makeText(LicenseActivity.this, decrypted, Toast.LENGTH_LONG).show();
}
}
}
I realise I'm just doing something stupid in this last bit of code where I try and decode the Encrypted string, and then decrypt it.
Hope you can point me in the correct direction, and sorry for being long winded.
Oh and yes, before you ask, I retrieve the license from the server with the following PHP:
require("config.inc.php");
if (!empty($_POST)) {
//initial query
$query = "SELECT pref_uuid, pref_license, pref_device_serial FROM preferences WHERE pref_uuid = :p_uuid";
$query_params = array(':p_uuid' => $_POST['p_uuid']);
//execute query
try {
$stmt = $db->prepare($query);
$db->errorInfo();
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error. Couldn't retrieve License details!" . $ex->getMessage();
die(json_encode($response));
}
if(!$result) {
$response["success"] = 0;
$response["message"] = "Database Error. Couldn't return Licenses!" . $ex->getMessage();
die(json_encode($response));
}
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$response["license"] = base64_encode($row['pref_license']); // I encode it here before I send the encrypted string off to android device.
$response["message"] = "License Record successfully retrieved";
$response["success"] = 1;
echo json_encode($response);
}
OK so thanks to Maarten Bodewes , I went back to PKCS#1 on the serverside, then couldn't work with it on Android side as expected. I discovered SpongyCastle library, and was able to extract the Modulus and privateExponent from the PrivateKey, then I was able to successfully unencrypt the encrypted string. THANKS MAARTEN!!!!

Categories