最佳公司产品登录需要进行一次rsa加密密码后再登录,vue端ios端都正常,唯独android不行,让后台打断点查看后,发现有时候okgo传递的rsa加密密码会丢失一些特殊字符,故写这个来记录解决方法
bug修复
我在试着将密码进行urldecode处理后,该bug修复,在看日志时加号没被urldecode掉,问题修复,这里水一下代码,吧rsa加密和加密密码urldecode后上传服务器的代码写一下
登录部分
fun login() {
showLoading()
val headers = HttpHeaders()
val credential = Credentials.basic("iwater", "iwater")
headers.put("Authorization", credential)
OkGo.getInstance().addCommonHeaders(headers)
var usrname = phone_et!!.text.toString() + ""
OkGo.post<String>(Api.rsaValue).tag(this)
.execute(object : MyStringCallback(getContext()) {
override fun onloadonSuccess(response: Response<String>?) {
try {
var rsaValue = JSONObject(response!!.body()).getString("object")
OkGo.post<String>(Api.login).tag(this)
.params("username", usrname)
.params(
"password",
URLEncoder.encode( EncryptionUtils.rsaEncode(password_et!!.text.toString(), rsaValue), "UTF-8")
)
.params("grant_type", "password")
.params("scope", "server")
.execute(object : MyStringCallback(getContext()) {
override fun onloadonSuccess(response: Response<String?>) {
var bean =
JSON.parseObject(response.body(), LoginBean::class.java)
if ("200".equals(bean.code) && bean.`object` != null) {
replaceUsrMessage(bean, usrname)
} else {
dismissLoading()
showToast(bean.message)
}
}
override fun onError(response: Response<String>?) {
super.onError(response)
dismissLoading()
}
})
} catch (e: Exception) {
showToast("网络异常")
}
}
override fun onError(response: Response<String>?) {
super.onError(response)
dismissLoading()
}
})
}
rsa加密部分
//公钥加密
public static String rsaEncode(String str, String publicKey) {
String outStr = "";
try {
// base64编码的公钥
byte[] decoded = Base64.decode(publicKey,Base64.DEFAULT);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
// RSA加密
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
outStr = Base64.encodeToString(cipher.doFinal(str.getBytes("UTF-8")), Base64.NO_WRAP);
} catch (Exception e) {
e.printStackTrace();
}
return outStr;
}