技术小结一

SHA1WithRSA算法

SHA1WithRSA即安全哈希算法,用于签名;RSA是目前最有影响力额公私钥算法。

SHA1WithRSA:用SHA算法进行签名,用RSA算法进行加密。sha1withrsa通过公钥加签,私钥解签。验证数据的合法性。

RSA依赖公私钥PEM进行对称加密。公钥证书CER,私钥PEM。PEM_密钥对生成与读取方法

Java RSA 加密 解密 签名 验签

提取PEM证书 —需要密码
openssl pkcs12 -in test-party-2.pfx -nodes -out xxxx.pem
提取私钥
openssl rsa -in bill99.pem -out bill99.key
提取Pkcs8格式的证书
openssl pkcs8 -topk8 -inform PEM -in private.key -outform pem -nocrypt -out pkcs8.pem

Java代码实现公私钥的加载以及加签验签

常量
private static final String ENCRYP_TYPE = "SHA1WithRSA";

private static final String RSA = "RSA";

private static final String CHARSET = "UTF-8";
公钥加载
FileInputStream input = null;
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
input = new FileInputStream(publicCertPath);
X509Certificate cer = (X509Certificate) cf.generateCertificate(input);

PublicKey pk = cer.getPublicKey();
this.publicKey = pk;
} catch (CertificateException e) {
//证书异常
} catch (FileNotFoundException e) {
//文件不存在
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException e) {
//关闭流异常
}
}
私钥加载
private String getPrivateKeyStream() {
BufferedReader br = null;
StringBuffer key = new StringBuffer();
try {
br = new BufferedReader(new FileReader(privateCertPath));
String s = br.readLine();
s = br.readLine();
while (!StringUtils.isEmpty(s) && s.charAt(0) != '-') {
key.append(s + "\r");
s = br.readLine();
}
} catch (FileNotFoundException e) {
//文件不存在
} catch (IOException e) {
//IO读取异常
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException e) {
//关闭流异常
}
}
return key.toString();
}

public void createPrivateKey() {
try {
byte[] b = Base64.decodeBase64(getPrivateKeyStream().getBytes(CHARSET));
// 生成私匙
KeyFactory kf = KeyFactory.getInstance(RSA);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(b);
PrivateKey privateKey = kf.generatePrivate(keySpec);
this.privateKey = privateKey;
} catch (UnsupportedEncodingException e) {
//编码异常
} catch (NoSuchAlgorithmException e) {
//算法异常
} catch (InvalidKeySpecException e) {
//验证证书格式异常
}
}
加签
//getSignField 根据TestVo生成指定的加签串

public void doSign(SignVO request) {
String signField = getSignField(request);
try {
Signature signature = Signature.getInstance(ENCRYP_TYPE);
signature.initSign(this.privateKey);
signature.update(signField.getBytes(CHARSET));
byte[] sign = signature.sign();
request.setSign(new String(Base64.encodeBase64(sign), CHARSET));
} catch (Exception e) {

}
}
解签
//getSignField 根据TestVo生成指定的加签串
public void verificate(TestVo response) {
String sign = response.getSign();//返回的验签标识
boolean pass = false;
try {
String signField = getRespSignField(response);
Signature sig = Signature.getInstance(ENCRYP_TYPE);
sig.initVerify(this.publicKey);
byte[] signFields = Base64.decodeBase64(sign.getBytes(CHARSET));
sig.update(signField.getBytes(CHARSET));
pass = sig.verify(signFields);
} catch (Exception e) {
//验签异常
}
}

HttpClient实现Https请求

初始化基础配置
private static PoolingHttpClientConnectionManager connManager;
private static RequestConfig requestConfig;

static{
try {
SSLContext sslcontext = createIgnoreVerifySSL();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext)).build();
connManager = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
// 连接池超时时间使用connect超时时间
requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(SdkConstants.DEFAULT_CONNECTION_TIMEOUT)
.setConnectTimeout(SdkConstants.DEFAULT_CONNECTION_TIMEOUT)
.setSocketTimeout(SdkConstants.DEFAULT_SOCKET_TIMEOUT).build();
} catch (Exception e) {
//初始化异常
}
}
实现Https请求
/**
* 绕过验证
*
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
private static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSLv3");
// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {}

@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {}

@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sc.init(null, new TrustManager[] { trustManager }, null);
return sc;
}

public static String doPostJsonRequestByHttps(String reqeustString, String url,
int connectTimeout, int socketTimeOut) {
long startTime = System.currentTimeMillis();
CloseableHttpResponse response = null;
String responseString;
try {

changeRequestConfig(connectTimeout,socketTimeOut);
CloseableHttpClient httpsClient = HttpClients.custom().setConnectionManager(connManager).build();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
httpPost.setConfig(requestConfig);
httpPost.setEntity(new StringEntity(reqeustString, ContentType.APPLICATION_JSON));
response = httpsClient.execute(httpPost);
// get http status code
int resStatu = response.getStatusLine().getStatusCode();
responseString = null;
if (resStatu == HttpStatus.SC_OK) {
responseString = EntityUtils.toString(response.getEntity());
} else {
throw new Exception(url + ",the statusCode is " + resStatu);
}
return responseString;
}catch (ConnectTimeoutException e) {

} catch (SocketTimeoutException e) {

}catch (Exception e) {

}finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
response.close();
} catch (Exception e) {

}
}
}
}
/**
* 修改默认超时时间
* @param connectionTime
* @param soTimeout
*/
private static void changeRequestConfig(int connectionTime,int soTimeout){
if(connectionTime != requestConfig.getConnectionRequestTimeout()
|| soTimeout != requestConfig.getSocketTimeout()){
requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(connectionTime)
.setConnectTimeout(connectionTime)
.setSocketTimeout(soTimeout).build();
}
}

JSON转换Map存在的问题

String json = "";
Map<String,Object> result = JSON.parseObject(json);

如果转换的Map中存在Map对象, toString()方法会返回JSON字符串。

需要下列方法在此转换:
JSON.parseObject(result.get("xxxx").toString(), HashMap.class)

结果:
{"aaa":"bbbb"} 不转之前的
{aaa=bbb} 转之后的
坚持原创技术分享,您的支持将鼓励我继续创作!
0%