概述
packagecom.cmcc.common.util;importorg.apache.commons.httpclient.HttpClient;importorg.apache.commons.httpclient.HttpStatus;importorg.apache.commons.httpclient.methods.PostMethod;importorg.springframework.core.io.ClassPathResource;importsun.misc.BASE64Decoder;importsun.misc.BASE64Encoder;importjavax.crypto.Cipher;importjavax.crypto.SecretKey;importjavax.crypto.SecretKeyFactory;importjavax.crypto.spec.DESKeySpec;importjavax.crypto.spec.IvParameterSpec;importjavax.xml.bind.JAXBContext;importjavax.xml.bind.Marshaller;importjavax.xml.bind.Unmarshaller;importjavax.xml.bind.annotation.XmlRootElement;importjava.io.*;importjava.security.*;importjava.security.cert.Certificate;importjava.security.cert.CertificateFactory;importjava.util.Date;/*** User: fengxuesong
* Date: 11-3-29
* Time: 下午12:03*/publicclassSign {//Des初始化向量publicstaticfinalbyte[] IV=newbyte[]{-29,105,5,40,-94,-98,-113,-100};publicstaticfinalString prikey="00000000";publicstaticvoidmain(String args[])throwsException {
String keystorePath="F:\idea-projects\OSP\src\main\webapp\WEB-INF\classes\feinno.keystore";
String certPath="F:\idea-projects\OSP\src\main\webapp\WEB-INF\classes\feinno.cer";
File keystoreFile=newClassPathResource("feinno.keystore").getFile();
File certPathFile=newClassPathResource("feinno.cer").getFile();if(keystoreFile!=null){
keystorePath=keystoreFile.getPath();
}if(certPathFile!=null){
certPath=certPathFile.getPath();
}//初始化dataString loginName="1";
String loginTimeSpan=newDate().toString();
String password="111111";
StringBuffer data=newStringBuffer();
data.append(loginName).append("|").append(loginTimeSpan).append("|").append(password);//生成 data MD5加密byte[] headTextWithMD5=encryptWithMD5(data);//------------------私钥加密-----------------String storepass="feinno";//生成证书库时输入的密码String storeKeyName="feinno";//证书别名String headSigned=newBASE64Encoder().encode(sing(headTextWithMD5, storepass, storeKeyName,keystorePath));
String content=xml2String(encodeDesWithBase64(prikey, loginName), encodeDesWithBase64(prikey, loginTimeSpan), encodeDesWithBase64(prikey, password), headSigned);//---------------------发送http请求String url="http://localhost:8080/auth";
String backinfo=sendPost(content, url);
System.out.println("validate:"+backinfo);//-----------------模拟 收到http请求 收到的xml 生成 bean//Request request = xml2Bean(content);//String acceptHeadSigned = request.getHead().getSigned();//String acceptLoginName = decodeDesWithBase64(prikey, request.getBody().getLoginName());//String acceptLoginTimeSpan = decodeDesWithBase64(prikey, request.getBody().getLoginTimeSpan());//String acceptPassword = decodeDesWithBase64(prikey, request.getBody().getPassword());//StringBuffer acceptData = new StringBuffer();//acceptData.append(acceptLoginName).append("|").append(acceptLoginTimeSpan).append("|").append(acceptPassword);-----------------公钥验证//byte[] verifyText = encryptWithMD5(acceptData);//encryptWithMD5(acceptData);boolean verifyFlag = verify(verifyText, new BASE64Decoder().decodeBuffer(acceptHeadSigned),certPath);//if (verifyFlag)//System.out.println("verify success
");//else//System.out.println("verify faile
");}/***@paramplainText 需要验证的内容
*@paramheadSigned 私钥生成的签名
*@return*/publicstaticbooleanverify(byte[] plainText,byte[] headSigned,String certPath)throwsException {
InputStream streamCert=newFileInputStream(certPath);
CertificateFactory factory=CertificateFactory.getInstance("X.509");
Certificate cert=factory.generateCertificate(streamCert);
Signature rsa=Signature.getInstance("SHA1WithDSA");
PublicKey publicKey=cert.getPublicKey();
rsa.initVerify(publicKey);
rsa.update(plainText);if(rsa.verify(headSigned)) {returntrue;
}else{returnfalse;
}
}/***@paramplainText 签名的内容
*@paramstorepass 访问证书的密码
*@paramstoreKeyName 证书别名
*@return*/publicstaticbyte[] sing(byte[] plainText, String storepass, String storeKeyName , String keystorePath)throwsException {
FileInputStream in=newFileInputStream(keystorePath);
KeyStore ks=KeyStore.getInstance("JKS");
ks.load(in, storepass.toCharArray());//获取私钥PrivateKey priKey=(PrivateKey) ks.getKey(storeKeyName, storepass.toCharArray());//用私钥签名Signature sig=Signature.getInstance("SHA1WithDSA");
sig.initSign(priKey);
sig.update(plainText);returnsig.sign();
}/*** 数据MD5加密
*
*@paramdata
*@return*@throwsNoSuchAlgorithmException*/publicstaticbyte[] encryptWithMD5(StringBuffer data)throwsNoSuchAlgorithmException {
MessageDigest md5=MessageDigest.getInstance("MD5");
md5.update(data.toString().getBytes());returnmd5.digest();
}/*** 用 httpClient 发送 post请求
*
*@paramcontent 发送内容
*@paramurl
*@return返回 response
*@throwsIOException*/publicstaticString sendPost(String content, String url)throwsIOException {
String backinfo="";
HttpClient httpclient=newHttpClient();
httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(1000);
PostMethod post = new PostMethod(url);
post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,500);post.setParameter("sign", content);try{
httpclient.executeMethod(post);intcode=post.getStatusCode();if(code==HttpStatus.SC_OK) {
backinfo=newString(post.getResponseBodyAsString());
}
}finally{
post.releaseConnection();
}returnbackinfo;
}/*** xml转bean
*
*@paramxml
*@return*/publicstaticRequest xml2Bean(String xml)throwsException {
JAXBContext context=JAXBContext.newInstance(Request.class);
Unmarshaller um=context.createUnmarshaller();
InputStream inStream=newByteArrayInputStream(xml.getBytes());
Request request=(Request) um.unmarshal(inStream);returnrequest;
}/*** 生成xml对应的字符转
*
*@paramloginName 登录名
*@paramloginTimeSpan 时间戳
*@parampassword 密码
*@paramheadSigned 证书鉴权
*@return*@throwsException*/publicstaticString xml2String(String loginName, String loginTimeSpan, String password, String headSigned)throwsException {
JAXBContext context=JAXBContext.newInstance(Request.class);
Request request=newRequest();
Head head=newHead();
head.setSigned(headSigned);
Body body=newBody();
body.setLoginName(loginName);
body.setLoginTimeSpan(loginTimeSpan);
body.setPassword(password);
request.setHead(head);
request.setBody(body);
Marshaller m=context.createMarshaller();
OutputStream outStream=newByteArrayOutputStream();
m.marshal(request, outStream);returnoutStream.toString();
}/*** 数据 Des加密, 并Base64编码, 解决 des 加密数据必须是8个字节的倍数
*
*@parampriKey 密钥
*@paramdata 需要加密的数据
*@return已加密数据*/publicstaticString encodeDesWithBase64(String priKey, String data)throwsException {
DESKeySpec desKS=newDESKeySpec(priKey.getBytes());
SecretKeyFactory skf=SecretKeyFactory.getInstance("DES");
SecretKey sk=skf.generateSecret(desKS);
Cipher cip=Cipher.getInstance("DES/CBC/PKCS5Padding");
cip.init(Cipher.ENCRYPT_MODE, sk,newIvParameterSpec(IV));bytebb[]=cip.doFinal(data.getBytes());returnnewBASE64Encoder().encode(bb);
}/*** 数据 Des解密,
*
*@parampriKey 密钥
*@paramdata 以加密数据
*@return解密数据
*@throwsException*/publicstaticString decodeDesWithBase64(String priKey, String data)throwsException {
DESKeySpec desKS=newDESKeySpec(priKey.getBytes());
SecretKeyFactory skf=SecretKeyFactory.getInstance("DES");
SecretKey sk=skf.generateSecret(desKS);
Cipher cip=Cipher.getInstance("DES/CBC/PKCS5Padding");
cip.init(Cipher.DECRYPT_MODE, sk,newIvParameterSpec(IV));bytebb[]=cip.doFinal(newBASE64Decoder().decodeBuffer(data));returnnewString(bb);
}/*** 生成xml的bean*/@XmlRootElementpublicstaticclassRequest {publicRequest() {
}
Head head;
Body body;publicHead getHead() {returnhead;
}publicvoidsetHead(Head head) {this.head=head;
}publicBody getBody() {returnbody;
}publicvoidsetBody(Body body) {this.body=body;
}
}publicstaticclassHead {publicHead() {
}
String signed;publicString getSigned() {returnsigned;
}publicvoidsetSigned(String signed) {this.signed=signed;
}
}publicstaticclassBody {publicBody() {
}
String loginName;
String loginTimeSpan;
String password;publicString getLoginName() {returnloginName;
}publicvoidsetLoginName(String loginName) {this.loginName=loginName;
}publicString getLoginTimeSpan() {returnloginTimeSpan;
}publicvoidsetLoginTimeSpan(String loginTimeSpan) {this.loginTimeSpan=loginTimeSpan;
}publicString getPassword() {returnpassword;
}publicvoidsetPassword(String password) {this.password=password;
}
}
}
最后
以上就是兴奋夏天为你收集整理的java post xmll_java 证书 生成 xml httpClient post 提交的全部内容,希望文章能够帮你解决java post xmll_java 证书 生成 xml httpClient post 提交所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复