登录接口的密码进行RSA加密Java脚本
做接口/性能测试,也不知道原公司是哪个D毛起的头,说只要是涉及“测试”两个字的事情就是测试的职责范围,自己问题自己解决,于是负责登录模块的某些开发人员不配合,不给接口文档/SwaggerUI也不给加密的脚本,说是网络传输不安全之类的,反正各种理由搪塞,只能通过接口抓包自己判断是什么加密方式,自己写脚本。我就共享出来怎么滴?
1.创建UrlInfo实例
public class UrlInfo {# 协议private String prototype;# 主机private String host;# 端口private String post;# 链接后缀private String uri;@Overridepublic String toString() {return prototype + "://" + host + ":" + post + uri;}public String getPrototype() {return prototype;}public void setPrototype(String prototype) {this.prototype = prototype;}public String getHost() {return host;}public void setHost(String host) {this.host = host;}public String getPost() {return post;}public void setPost(String post) {this.post = post;}public String getUri() {return uri;}public void setUri(String uri) {this.uri = uri;}
}
2.获取公钥、密码加密
import io.restassured.response.Response;import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;import static io.restassured.RestAssured.given;public class RSAPwd {/*** urlInfo基本信息* */public static String getUrl(String prototype,String host,String port,String uri){UrlInfo urlInfo = new UrlInfo();urlInfo.setPrototype(prototype);urlInfo.setHost(host);urlInfo.setPost(port);urlInfo.setUri(uri);return urlInfo.toString();}/*** 获取公钥* @account: 用户名* @url: 请求地址* */public static String getResponsePublicKey(String account,String url){String JsonData = "{\"account\": \"" + account + "\"}";# 发起请求,获取响应结果对象ResponseResponse response = given().contentType("application/json;charset=UTF-8").body(JsonData).when().post(url).then().extract().response();# jsonPath获取公钥参数名data的valuereturn response.jsonPath().get("data").toString();}/*** 密码加密* @pwdStr:待加密密码* @publicKeyBase64:公钥文本* */public static String encryptPassword(String pwdStr,String publicKeyBase64){String result = "";try{PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyBase64)));Cipher encryptCipher = Cipher.getInstance("RSA");encryptCipher.init(Cipher.ENCRYPT_MODE,publicKey);byte[] encryptedByte = encryptCipher.doFinal(pwdStr.getBytes());result = Base64.getEncoder().encodeToString(encryptedByte);}catch (Exception e){e.printStackTrace();}return result;}
}