如何比较android中数据库的加密密码

时间:2016-08-22 07:23:21

标签: java php android mysql encryption

以下是我的Android和PHP代码。如果密码是普通字符串形式,我能够成功比较密码和登录。但是当我以加密格式输入密码时,我无法比较密码值。因此无法成功登录。

SignUpActivity.Java

package com.kezinking.nupur.kezinking;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static android.R.attr.id;

/**
 * Created by Nupur on 8/2/2016.
 */

public class SignupActivity extends AppCompatActivity {
    private static final String TAG ="" ;
    TextView link_login;
    Button btn_signup;
    EditText input_username;
    EditText input_email;
    EditText input_password;
     String username;
    String email;
    String password;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signup);
        link_login = (TextView) findViewById(R.id.link_login);
        btn_signup = (Button) findViewById(R.id.btn_signup);
        input_username=(EditText) findViewById(R.id.input_username);
        input_email=(EditText) findViewById(R.id.input_email);
        input_password=(EditText) findViewById(R.id.input_password);

        link_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SignupActivity.this, LoginActivity.class);
                startActivity(intent);
                SignupActivity.this.getIntent();
            }
        });

        btn_signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                username = input_username.getText().toString();
                email= input_email.getText().toString();
                password = input_password.getText().toString();

                SignUp();
            }
        });

    }

    public void SignUp() {
        if (!validate()) {
            onSignupFailed();
            return;
        }else{
            insert(username,email,password);
        }

    }
    public void insert(final String username, final String email,final String password){
        class SendPostReqAsynTask extends AsyncTask<String,Void,String> {

            @Override
            protected String doInBackground(String... params) {
                String paramUsername=params[0];
                String paramPassword=params[1];

                //String username = etUsername.getText().toString();
                //String password = etPassword.getText().toString();
                List<NameValuePair> nameValuePairs= new ArrayList<>();
                nameValuePairs.add(new BasicNameValuePair("username",username));
                nameValuePairs.add(new BasicNameValuePair("email",email));
                nameValuePairs.add(new BasicNameValuePair("password",password));

                try{
                    HttpClient httpClient = new DefaultHttpClient();
                    // HttpGet request = new HttpGet("http://www.example.com");
                    HttpPost httpPost = new HttpPost("http://kezinking.com/SignUpAndroid");
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response= httpClient.execute(httpPost);
                    HttpEntity entity= response.getEntity();
                    int i =response.getStatusLine().getStatusCode();

                    System.out.println(i);
                    onSignupSuccess();
                }catch(ClientProtocolException e){

                }catch (IOException e){

                }

                return "Success";
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
               // Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
                TextView textViewResult = (TextView) findViewById(R.id.txtResultCheck);
                textViewResult.setText("Successfully Registered");
            }
        }
        SendPostReqAsynTask sendPostReqAsynTask=new SendPostReqAsynTask();
        sendPostReqAsynTask.execute(username,password);

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    public void onSignupSuccess() {
        //btn_signup.setEnabled(true);
        Intent intent=new Intent(SignupActivity.this,MainActivity.class);
        startActivity(intent);
        SignupActivity.this.getIntent();
    }



    public void onSignupFailed() {
        Toast.makeText(getBaseContext(), "Failed to Register", Toast.LENGTH_LONG).show();

      //  btn_signup.setEnabled(true);
    }
    public boolean validate() {
        boolean valid = true;

        String username = input_username.getText().toString();
        String email = input_email.getText().toString();
        String password = input_password.getText().toString();

        if (username.isEmpty() || username.length() < 3) {
            input_username.setError("at least 3 characters");
            valid = false;
        } else {
            input_username.setError(null);
        }

        if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            input_email.setError("enter a valid email address");
            valid = false;
        } else {
            input_email.setError(null);
        }

        if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
            input_password.setError("between 4 and 10 alphanumeric characters");
            valid = false;
        } else {
            input_password.setError(null);
        }

        return valid;
    }


}

LoginActivity.Java

package com.kezinking.nupur.kezinking;

import android.animation.ObjectAnimator;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Space;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Nupur on 8/2/2016.
 */

public class LoginActivity extends AppCompatActivity {
    public static final String MY_JSON = "MY_JSON";
    private static final String JSON_URL = "http://kezinking.com/AndroidLogin";
    EditText input_email, input_password;
    Button btn_login, btnContactUs, btnWorkhr, btnDeltime, btnMoneyBack;
    TextView link_signup, textViewJSON, txtcheck;
    private static Boolean flag = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        btn_login = (Button) findViewById(R.id.btn_login);
        link_signup = (TextView) findViewById(R.id.link_signup);
        input_email = (EditText) findViewById(R.id.input_email);
        input_password = (EditText) findViewById(R.id.input_password);
        textViewJSON = (TextView) findViewById(R.id.textViewJSON);
        // value=(TextView)findViewById(R.id.value);
        txtcheck = (TextView) findViewById(R.id.txtcheck);

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                login();
            }
        });
        link_signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
                startActivity(intent);
                LoginActivity.this.getIntent();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void login() {
        if (!validate()) {
            onLoginFailed();
            return;
        } else {
            getJSON(JSON_URL);
        }
    }

    public void getJSON(String url) {
        class GetJSON extends AsyncTask<String, Void, String> {
            ProgressDialog loading;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(LoginActivity.this, "Please Wait...", null, true, true);
            }

            @Override
            protected String doInBackground(String... params) {

                String uri = params[0];

                BufferedReader bufferedReader = null;
                try {
                    URL url = new URL(uri);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();

                    bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    //String result=null;
                    String json;
                    while ((json = bufferedReader.readLine()) != null) {
                        sb.append(json + "\n");
                    }

                    return sb.toString().trim();

                } catch (Exception e) {
                    return null;
                }

            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                textViewJSON.setText(s);
                String jsonString = textViewJSON.getText().toString();
                //String jsonString = "{\"result\":[{\"Vendor_ID\":\"1\",\"username\":\"nupur\",\"password\":\"nupur\"},{\"Vendor_ID\":\"4\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"3\",\"username\":\"nupur\",\"password\":\"1234\"},{\"Vendor_ID\":\"5\",\"username\":\"RAJ\",\"password\":\"RAJ\"},{\"Vendor_ID\":\"6\",\"username\":\"RAJ\",\"password\":\"RAJ\"},{\"Vendor_ID\":\"7\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"8\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"9\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"10\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"11\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"12\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"13\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"14\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"15\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"16\",\"username\":\"Nupur\",\"password\":\"Nupur\"},{\"Vendor_ID\":\"17\",\"username\":\"Nupur\",\"password\":\"Nupur\"},{\"Vendor_ID\":\"18\",\"username\":\"Nupur\",\"password\":\"Nupur\"},{\"Vendor_ID\":\"19\",\"username\":\"Nupur\",\"password\":\"Nupur\"},{\"Vendor_ID\":\"20\",\"username\":\"Rohit\",\"password\":\"Rohit\"},{\"Vendor_ID\":\"21\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"22\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"23\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"24\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"35\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"34\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"33\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"32\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"31\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"36\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"37\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"38\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"39\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"40\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"41\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"73\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"43\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"44\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"45\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"46\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"47\",\"username\":\"username\",\"password\":\"password\"},{\"Vendor_ID\":\"74\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"75\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"72\",\"username\":\"Krishna\",\"password\":\"Krishna\"},{\"Vendor_ID\":\"68\",\"username\":\"Honey\",\"password\":\"Honey\"},{\"Vendor_ID\":\"69\",\"username\":\"Ram\",\"password\":\"Ram\"},{\"Vendor_ID\":\"70\",\"username\":\"Ram\",\"password\":\"Ram\"},{\"Vendor_ID\":\"71\",\"username\":\"Ram\",\"password\":\"Ram\"}]}";
                //String email = (input_email.getText().toString());
                //txtcheck.setText(jsonString);
                String email = input_email.getText().toString();
                String password = input_password.getText().toString();


                // final String myResult = (email) + (password);
                String value = (String.valueOf(email + password));

                System.out.println(value);
                // String value=(input_email.getText().toString()+input_password.getText().toString());
                //String input_email = "";
                //String input_password = "";
                try {
                    JSONObject jsonObject = new JSONObject(jsonString);
                    JSONArray result = jsonObject.getJSONArray("result");
                    //System.out.println("result " + result);
                    //iterate through json array and check if id is same with your search

                    //System.out.println("length " + result.length());
                    for (int i = 0; i < result.length(); i++) {
                        System.out.println(i);
                        JSONObject item = result.getJSONObject(i);
                        String Email = item.getString("email");
                        String Password = item.getString("password");
                        //System.out.println("Email from json "+ Email);
                        //System.out.println("Password from json " + Password);
                        if (Email.equals(email) && Password.equals(password)) {
                            System.out.println("Email from json"+ Email);
                            System.out.println("Password from json" + Password);
                            flag=true;
                            onLoginSuccess();

                            break;
                        }
                    }
                    if(!flag){
                        onLoginFailed();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

//here you can show the result
                Log.v(this.getClass().getSimpleName(), "email = " + email);
                Log.v(this.getClass().getSimpleName(), "password = " + password);
                //txtcheck.setText(email);
            }
        }
        GetJSON gj = new GetJSON();
        gj.execute(url);

    }

    @Override
    public void onBackPressed() {
        // disable going back to the MainActivity
        moveTaskToBack(true);
    }

    public void onLoginSuccess() {
        btn_login.setEnabled(true);
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        LoginActivity.this.getIntent();
        // finish();
    }


    public void onLoginFailed() {
        Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();

        // btn_login.setEnabled(true);
    }

    public boolean validate() {
        boolean valid = true;

        String email = input_email.getText().toString();
        String password = input_password.getText().toString();

        if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            input_email.setError("enter a valid email address");
            valid = false;
        } else {
            input_email.setError(null);
        }

        if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
            input_password.setError("between 4 and 10 alphanumeric characters");
            valid = false;
        } else {
            input_password.setError(null);
        }

        return valid;
    }

}

PHP- AndroidLogin.php

<?php
$con=mysqli_connect("localhost","amodbina0106","Amodbina200","kezin_king");
if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
} 

?>

<?php



$sql=mysqli_query($con,"SELECT email,password FROM `users` WHERE 1");
$result=array();
while($row=mysqli_fetch_assoc($sql))
{
    $result[]=$row;
}
echo json_encode(array("result"=>$result));
?>

PHP-SignUpAndroid.php

<?php
$con=mysqli_connect("localhost","amodbina0106","Amodbina200","kezin_king");
if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
} 
echo "Connected successfully";
?>
<html>
<head>
        <meta charset="utf-8">

</head>
<body>
<table style="width: 100%">
<?php
        $username=($_POST['username']);
        $email=($_POST['email']);
    $password=($_POST['password']);
$encryptedpassword=md5($password);

$sql=mysqli_query($con,"INSERT INTO `kezin_king`.`users` (`user_id`, `username`, `name`, `shop-name`, `password`, `email`, `adr`, `con_no`, `type`, `profile`, `doj`, `banner`, `banner1`, `lat`, `lon`, `email_code`, `activation`) VALUES (NULL, '$username', '', '', '$encryptedpassword', '$email', '', '', '', '', '', '', '', '', '', '', '1')");

$sql=mysqli_query($con,"SELECT name,username,password,email FROM `user` WHERE 1");
while($row=mysqli_fetch_assoc($sql))
{
$username=$row['username'];
$email=$row['email'];
$password=$row['password'];
?>
    <tr>
    <th><?php echo $username; ?></th>
    <th><?php echo $email; ?></th>
    <th><?php echo $password; ?></th>
  </tr>
 <?php }?> 
</table>

请帮帮我。如果密码加密,我们可以登录吗? 在此先感谢

错误/输出: -

V/GetJSON: email = check@check.com
V/GetJSON: password = check1
I/ViewRootImpl: CPU Rendering VSync enable = true

“LoginFailed”

0 个答案:

没有答案