1.Android
2.servlet
3.MySQL(数据库的查找、更新)
4.Tomcat
5.加密算法(数据加密传输)
<?xml version="1.0" encoding="utf-8"?>
<!--
修改密码
-->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="修改密码"
android:textColor="@color/colorPrimary"
android:textSize="20sp"/>
<EditText
android:id="@+id/et_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="邮箱"/>
<EditText
android:id="@+id/et_now"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="旧密码"/>
<EditText
android:id="@+id/et_new"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="新密码"/>
<EditText
android:id="@+id/et_new_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="再次输入密码"/>
<Button
android:id="@+id/btn_update_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/lavender"
android:text="重置密码"
/>
<Button
android:id="@+id/update_forget_psw"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/lavender"
android:layout_marginTop="7dp"
android:text="忘记密码"/>
</LinearLayout>
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.administrator.loginclient.ActivityCollectors.ActivityCollector;
import com.example.administrator.loginclient.HttpsUtils.HTTPSTrustManager;
import com.example.administrator.loginclient.R;
import com.example.administrator.loginclient.RsaUtils.GenKeyFromString;
import com.example.administrator.loginclient.RsaUtils.MyConstant;
import com.example.administrator.loginclient.RsaUtils.RSAUtil;
import org.bouncycastle.util.encoders.Base64;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;
/**
* 修改密码
*/
public class AlterPSWActivity extends BaseActivity implements View.OnClickListener {
private EditText et_now,et_new,et_new2;
private EditText et_email;
private Button btn_update;
private Button btn_forget;
public static RequestQueue queue;
private static Context mContext;
@Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alter_psw);
queue = Volley.newRequestQueue(getApplicationContext());
mContext = this;
initView();//初始化UI
}
/**
* 初始化UI
*/
private void initView() {
et_now=(EditText)findViewById(R.id.et_now);
et_new=(EditText)findViewById(R.id.et_new);
et_new2=(EditText)findViewById(R.id.et_new_password);
et_now.setTransformationMethod(PasswordTransformationMethod.getInstance());//密码不可见
et_new.setTransformationMethod(PasswordTransformationMethod.getInstance());//密码不可见
et_new2.setTransformationMethod(PasswordTransformationMethod.getInstance());//密码不可见
et_email=(EditText)findViewById(R.id.et_email);
btn_forget=(Button)findViewById(R.id.update_forget_psw);
btn_update=(Button)findViewById(R.id.btn_update_password);
btn_update.setOnClickListener(this);
btn_forget.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_update_password:
//重置密码
String now=et_now.getText().toString().trim();
String pass1=et_new.getText().toString().trim();
String pass2=et_new2.getText().toString().trim();
final String psw_old = et_now.getText().toString().trim();
final String psw_new = et_new.getText().toString().trim();
final String email=et_email.getText().toString().trim();
// 获取Rsa 工具类对象
RSAUtil rsa = new RSAUtil();
// 获取公钥
RSAPublicKey pubKey = (RSAPublicKey) GenKeyFromString
.getPubKey(MyConstant.pubKey1);
// 使用公钥加密 数据
byte[] enRsaByte_psw_old = new byte[0];
byte[] enRsaBytes_psw_new = new byte[0];
byte[] enRsaBytes_psw_email = new byte[0];
try {
enRsaByte_psw_old = rsa.encrypt(pubKey, psw_old.getBytes());//旧密码加密
enRsaBytes_psw_new = rsa.encrypt(pubKey, psw_new.getBytes());//新密码加密
enRsaBytes_psw_email=rsa.encrypt(pubKey,email.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
/**
* base64对byte数组进行编码,进过编码后得到String传输到对服务端解码得出byte数组。
*/
String enRsaStr_psw_old = new String(Base64.encode(enRsaByte_psw_old));//旧密码byte数组转成字符串
String enRsaStr_psw_new = new String(Base64.encode(enRsaBytes_psw_new));//新密码byte数组转成字符串
String enRsaStr_psw_email=new String(Base64.encode(enRsaBytes_psw_email));//邮箱byte数组转成字符串
if(!TextUtils.isEmpty(now)&&!TextUtils.isEmpty(pass1)&&!TextUtils.isEmpty(pass2)){
//和原始密码一致
if(pass1.equals(now)||pass2.equals(now)){
Toast.makeText(AlterPSWActivity.this, "新旧密码不能一样,请再想个新密码!", Toast.LENGTH_SHORT).show();
}else if(pass1.equals(pass2)){
Toast.makeText(AlterPSWActivity.this, "密码校验成功", Toast.LENGTH_SHORT).show();
//此处做修改密码操作
UpdatePSWRequest(enRsaStr_psw_old,enRsaStr_psw_new,enRsaStr_psw_email);
}else{
Toast.makeText(AlterPSWActivity.this, "两次密码输入不一致!", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(AlterPSWActivity.this, "输入框不能为空!", Toast.LENGTH_SHORT).show();
}
break;
case R.id.update_forget_psw:
Intent intent = new Intent(AlterPSWActivity.this,ForgetPswActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//关掉所要到的界面中间的activity
AlterPSWActivity.this.startActivity(intent);
// ActivityCollector.finishAll();//关掉之前的所有活动
break;
}
}
public static void UpdatePSWRequest(final String password,final String updatePassword,final String email){
//请求地址
String url = "http://localhost:8083/MyFirstWebAPP/UpdatePasswordServlet"; //注①
String tag = "Alter"; //注②
//取得请求队列
RequestQueue requestQueue = queue;
//防止重复请求,所以先取消tag标识的请求队列
requestQueue.cancelAll(tag);
HTTPSTrustManager.allowAllSSL();//允许所有https请求
//创建StringRequest,定义字符串请求的请求方式为POST(省略第一个参数会默认为GET方式)
final StringRequest request = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = (JSONObject) new JSONObject(response).get("params"); //注③
String result = jsonObject.getString("Result"); //注④
if (result.equals("UpdateSuccess")) { //注⑤
Toast.makeText(mContext, "修改密码成功,请重新登录!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(mContext,MainActivity.class);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//关掉所要到的界面中间的activity
mContext.startActivity(intent);
ActivityCollector.finishAll();//关掉之前的所有活动
}
else if (result.equals("TheOldPasswordIsError")){
//做自己的登录失败操作,如Toast提示
Toast.makeText(mContext, "原始密码错误", Toast.LENGTH_LONG).show();
} else if (result.equals("TheEmailIsError")){
//做自己的登录失败操作,如Toast提示
Toast.makeText(mContext, "邮箱不存在", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
//做自己的请求异常操作,如Toast提示(“无网络连接”等)
Log.e("TAG", e.getMessage(), e);
Toast.makeText(mContext, "无网络连接", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//做自己的响应错误操作,如Toast提示(“请稍后重试”等)
Log.e("TAG", error.getMessage(), error);
Toast.makeText(mContext, "请稍后重试", Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Password", password);
params.put("UpdatePassword", updatePassword);
params.put("Email", email);
return params;
}
};
//设置Tag标签
request.setTag(tag);
//将请求添加到队列中
requestQueue.add(request);
}
}
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'androidx.core:core:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.android.volley:volley:1.1.1'
implementation files('libs/sun.misc.BASE64Decoder.jar')
implementation files('libs/bcprov-jdk15-1.45.jar')
//noinspection GradleDeprecated
implementation 'com.google.android.gms:play-services-appindexing:9.8.0'
androidTestImplementation('androidx.test.espresso:espresso-core:3.1.0', {
exclude group: 'com.android.support', module: 'support-annotations'
})
implementation 'com.google.android.material:material:1.3.0-alpha01'
外部包自行下载添加依赖,提取码:jd3v
<servlet>
<servlet-name>UpdatePasswordServlet</servlet-name>
<servlet-class>net.jw.MyFirstWebAPP.ServletPackage.UpdatePasswordServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UpdatePasswordServlet</servlet-name>
<url-pattern>/UpdatePasswordServlet</url-pattern>
</servlet-mapping>
import java.io.IOException;
import java.io.PrintWriter;
import java.security.interfaces.RSAPrivateKey;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.jw.MyFirstWebAPP.RSAutil.GenKeyFromString;
import net.jw.MyFirstWebAPP.RSAutil.MyConstant;
import net.jw.MyFirstWebAPP.RSAutil.RSAUtil;
import net.jw.MyFirstWebAPP.User;
import net.jw.MyFirstWebAPP.UserDAO;
import net.sf.json.JSONObject;
import org.bouncycastle.util.encoders.Base64;
/**
*更新密码
* @author Administrator
*/
public class UpdatePasswordServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应内容类型
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
try (PrintWriter out = response.getWriter()) {
//获得请求中传来的旧密码、新密码
String Old_Password = request.getParameter("Password").trim();
String password = request.getParameter("UpdatePassword").trim();
String email = request.getParameter("Email").trim();
//密码验证结果
byte[] byterepsw_old = Base64.decode(Old_Password);//旧密码解密BASE64
byte[] byterepsw = Base64.decode(password);//密码解密BASE64
byte[] bytere_email = Base64.decode(email);//密码解密BASE64
// System.out.println(byteres);
// System.out.println("字符串转成byte数组:"+new String(byteres));
// 获取私钥
RSAUtil rsa = new RSAUtil();
RSAPrivateKey priKey = (RSAPrivateKey) GenKeyFromString
.getPrivateKey(MyConstant.priKey1);
// 拿着私钥解旧密码
byte[] encRsaByte_old = rsa.decrypt(priKey,
byterepsw_old);
// 拿着私钥解 新密码
byte[] encRsaBytepsw = rsa.decrypt(priKey,
byterepsw);
// 拿着私钥解新密码
byte[] encRsaByte_email = rsa.decrypt(priKey,
bytere_email);
String NewPassword=new String(encRsaBytepsw);//新密码字符串
int verifyResult = verifyUpdate(new String(encRsaByte_old),new String(encRsaByte_email),NewPassword);
Map<String, String> params = new HashMap<>();
JSONObject jsonObject = new JSONObject();
if (verifyResult == 1) {
params.put("Result", "UpdateSuccess");//邮箱存在,原始密码正确,密码修改成功
}
else if (verifyResult == 0){
params.put("Result", "TheEmailIsError");//邮箱不存在
} else if (verifyResult == 2){
params.put("Result", "TheOldPasswordIsError");//原始密码错误
}
jsonObject.put("params", params);
out.write(jsonObject.toString());
} catch (Exception ex) {
Logger.getLogger(RegisterServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* 验证邮箱和密码是否正确
*
* @param OldPassword
* @param email
* @param password
*/
private int verifyUpdate(String OldPassword,String email,String password) {
User user=UserDAO.queryPasswordByEmail(email);
if(!UserDAO.checkEmail(email))
{
if(user.getPassword().equals(OldPassword))
{ //更新密码操作
if(UserDAO.updatePassword(password, email)){
return 1;//密码正确
}
}
else
{
return 2;//密码错误
}
}
return 0; //邮箱不存在
}
}
以上代码有导入包报错的以及数据库的操作等等,请先阅读这篇文章!