网络请求是数据的传递使用了【RSA】和【AES】加密
需要使用用户信息的请求使用AES加密(需要秘钥进行加密)
与用户无关联的请求使用RSA加密
rsa加密
/**
进行rsa加密
@param data 加密数据
-
@return 加密结果
*/
public static String encryptByPublicKey(String data) {try {
// 加密
byte[] encryptByte = RSAJava.encryptByPublicKey(data.getBytes());
String afterencrypt = Base64.encodeToString(encryptByte,
Base64.DEFAULT);
return afterencrypt;
} catch (Exception e) {
return "";
}
}
使用:
1、将需要传递的数据转换拼接成json字符串,jb.put("phoneNum", phoneNum);
2、然后将json字符串转换成byte数组,data.getBytes()
3、将byte数组进行rsa加密,RSAJava.encryptByPublicKey(data.getBytes())
4、加密后的byte数组进行Base64转码并转成字符串形式,Base64.encodeToString(encryptByte,Base64.DEFAULT)
5、将得到的字符串放入hashmap中key为data,value为加密处理后的字符串,mapList.put("data", encryptByPublicKey(jb.toString()));
6、将加密后的map遍历,使用stringBuffer.append("&" + str + "=" + value)
7、post请求
// 实例化 StringRequest类
StringRequest stringRequest = new StringRequest(Request.Method.POST,
httpData.getUrl(), new Listener<String>() {.........
// 设置请求时间
VolleyUtil.setTimeOutRequest(stringRequest, mCurrentTimeoutMs);
// 发送请求
VolleyUtil.addRequest(stringRequest, httpData.getUrlTag());
8、get请求
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(conUrl,
null, new Response.Listener<JSONObject>() {
// 设置请求时间
VolleyUtil.setTimeOutRequest(jsonObjectRequest, mCurrentTimeoutMs);
// 发送请求
VolleyUtil.addRequest(jsonObjectRequest, httpData.getUrlTag());
/**
获取验证码
@return map集合
-
sendType 1注册 2充值
*/
public static HashMap<String, String> getPhoneCodeParams(String phoneNum, String sendType) {
HashMap<String, String> mapList = new HashMap<String, String>();try {
JSONObject jb = new JSONObject();
jb.put("phoneNum", phoneNum);
jb.put("sendType", sendType);
mapList.put("data", encryptByPublicKey(jb.toString()));
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}return mapList;
}
/**
- 添加url tag 以便销毁时 取消请求的url
*/
private String getTag(HashMap<String, String> map, String url,
String action) {
// 请求url集合
long currentTimeMillis = System.currentTimeMillis();
StringBuffer stringBuffer = new StringBuffer();
for (String str : map.keySet()) {
final String value = map.get(str);
stringBuffer.append("&" + str + "=" + value);
}
String tag = action + currentTimeMillis + stringBuffer.toString();
return tag;
}
--------------------------------------------------------分割线-------------------------------------------------------------------
aes加密
使用:
1、将需要传递的数据转换拼接成json字符串,jb.put("addressBook", addressBook);
2、将json转换成字符串jb.toString()
3、根据用户的加密串(用户登录成功之后才会有加密串,即秘钥SecretKey),将data字符串进行AES加密
4、将加密之后的byte数组使用Base64编码进行转码,得到字符串
/**
- 进行aes加密
- @param data 加密数据
- @return 加密结果
*/
public static String encryptByAES(String data) {
byte[] encryptByte = AESUtils.encrypt(UserManagerImpl.getInstance().getJKUser()
.getSecretKey(), data);
String afterencrypt = Base64.encodeToString(encryptByte,
Base64.DEFAULT);
return afterencrypt;
}
/**
上传联系人接口
-
@param addressBook
*/
public static HashMap<String, String> getAddressBook(String addressBook) {
HashMap<String, String> mapList = new HashMap<String, String>();try {
JSONObject jb = new JSONObject();
jb.put("addressBook", addressBook);
LogUtils.e(jb.toString());
mapList.put("data", encryptByAES(jb.toString()));} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}return mapList;
}
--------------------------------------------------------分割线-------------------------------------------------------------------
接口返回结果时,
1、先对data数据进行Base64转码,
2、然后再Rsa解码RSAJava.decryptByPublicKey
@Override
public synchronized void onResponse(String response) {
LogUtils.e("TAG", response.toString());
httpData.disposeResult(response.toString());
httpData.getListener().onSuccess(httpData);
}
/**
获取是否请求成功 并提示信息
@param str
-
@return
*/
public void disposeResult(String str) {
try {
setResponse(str);
JSONObject jsonObject = new JSONObject(str);if (jsonObject.optString("result").equals("103")) { if (jsonObject.optString("errorInfo").equals("无效token")) { ToastManager.getInstance(VApplication.getApplication()).show("登录失败,请重新登录"); VApplication.getApplication().isInvalidToken(); setSuccess(false); } } if (!jsonObject.optString("result").equals("0")) { String msg = jsonObject.optString("msg"); if (TextUtils.isEmpty(msg)) { if (jsonObject.optString("errorInfo").equals("无效token")) { //不显示无效token } else { msg = jsonObject.optString("errorInfo"); ToastManager.getInstance(VApplication.getApplication()).show(msg); } } else { ToastManager.getInstance(VApplication.getApplication()).show(msg); } setSuccess(false); } else { setSuccess(true); } setJsonData(VYSystemUtils.parsingResultData(jsonObject .optString("data"))); LogUtils.e("返回解密结果" + getAction(), getJsonData());
} catch (Exception e) {
LogUtils.e(e.toString());
ToastManager.getInstance(VApplication.getApplication()).show("请求失败");
setSuccess(false);
}
}
/**
解析接口返回的data数据
@param data
-
@return
*/
public static String parsingResultData(String data) {
try {
// RSA解密返回的 data数据
byte[] decryptByPublicKey = RSAJava.decryptByPublicKey(Base64Utils
.decode(data));return new String(decryptByPublicKey);
} catch (Exception e) {
return "";
}
}
--------------------------------------------------------分割线-------------------------------------------------------------------
用户登录(使用AES时需要的加密串,登陆成功后会返回)
1、在activity中获得用户输入的用户名和密码调用登录方法,userManager.doLogin(this, sPhone, sPassword);
2、设置登录参数user = JKUser.createInstance(userName, userPassword);
3、用户名和密码转换成json串,然后转换成Byte数组
4、将Byte数组用RSA加密,给加密byte串赋值
5、将加密byte串进行Base64编码转换成字符串,给加密String串赋值
6、将加密后的String串放入hashMap数组中,key为data,值为加密string串
7、然后post请求登录接口
VYHttpData httpData = new VYHttpData(URL_AUTH, mapList, LOGIN_ACTION, this);
mVYHttpUtils.postHttpResult(httpData);
8、post请求
// 实例化 StringRequest类
StringRequest stringRequest = new StringRequest(Request.Method.POST,
httpData.getUrl(), new Listener<String>() {.........
// 设置请求时间
VolleyUtil.setTimeOutRequest(stringRequest, mCurrentTimeoutMs);
// 发送请求
VolleyUtil.addRequest(stringRequest, httpData.getUrlTag());
9、得到RSA解密后的data json对象,得到秘钥secretKey,登录的token
10、token字符串先进行Base64转码
11、再使用secretKey将token进行aes解码得到字符串decrypt
String decrypt = AESUtils.decrypt(secretKey,Base64.decode(token, Base64.DEFAULT));
12、再将解密后的字符串decrypt进行base64转码得到字符串token(解密之后的token)
13、将token,secretKey,username,password存到本地做用户的数据缓存
14、给用户Token和secretKey进行赋值,
user.setToken(sToken);
user.setSecretKey(secretKey);
15、登录成功EventBus发送已登录事件
public static JKUser createInstance(String userName, String userPassword) {
JKUser user = null;
try {
user = new JKUser();
user.setUserName(userName);
user.setUserPassword(userPassword);
JSONObject jb = new JSONObject();
jb.put("userName", userName);
jb.put("userPassword", userPassword);
user.setEncryptByte(RSAJava.encryptByPublicKey(jb.toString()
.getBytes()));
user.setAfterencrypt(Base64.encodeToString(user.getEncryptByte(),
Base64.DEFAULT));
} catch (Exception e) {
LogUtils.e("log", e.toString());
}
return user;
}
@Override
public boolean doLogin(BaseActivity activity, String userName, String userPassword) {
//设置登录参数
user = JKUser.createInstance(userName, userPassword);
if (user == null) {
return false;
} else {
//弹出进度框
baseActivity = null;
baseActivity = activity;
if (baseActivity != null) {
baseActivity.showXProgressDialog();
}
HashMap<String, String> mapList = new HashMap<String, String>();
mapList.put("data", user.getAfterencrypt());
//请求登录接口
VYHttpData httpData = new VYHttpData(URL_AUTH, mapList, LOGIN_ACTION, this);
mVYHttpUtils.postHttpResult(httpData);
return true;
}
}
/**
登录成功
-
@param httpData 请求接口封装类
*/
@Override
public void onSuccess(VYHttpData httpData) {if (httpData.getAction().equals(LOGIN_ACTION)) {
//登录成功,进度圈消失
if (baseActivity != null) {
baseActivity.dismissXProgressDialog();
baseActivity = null;
}
try {
if (httpData.isSuccess()) {
JSONObject jsonData = new JSONObject(httpData.getJsonData());
String secretKey = jsonData.getString("secretKey");
String token = jsonData.getString("token");
//AES 解密
String decrypt = AESUtils.decrypt(secretKey,
Base64.decode(token, Base64.DEFAULT));// 解密之后获取的token数据 String sToken = new String(Base64Utils.decode(decrypt)); // 做用户数据的缓存 token secretkey username if (!TextUtils.isEmpty(sToken)) { PreferencesUtils.putSharePre(JiuKeApplication.getApplication(), PreferencesUtils.USER_TOKEN, sToken); PreferencesUtils.putSharePre(JiuKeApplication.getApplication(), PreferencesUtils.USER_KEY, secretKey); PreferencesUtils.putSharePre(JiuKeApplication.getApplication(), PreferencesUtils.USER_PHONE, user.getUserName()); } user.setToken(sToken); user.setSecretKey(secretKey); //登录成功EventBus发送已登录事件 EventBus.getDefault().post(new UserLoginEvent().setUser(user)); ToastManager.getInstance(JiuKeApplication.getApplication()).show("登录成功"); } } catch (Exception e) { ToastManager.getInstance(JiuKeApplication.getApplication()).show("登录异常"); }
}
}