基于HTTP在互联网传输敏感数据的消息摘要、签名与加密方案(2)
- UID
- 1029342
- 性别
- 男
|
基于HTTP在互联网传输敏感数据的消息摘要、签名与加密方案(2)
2.数字签名工具类:
Java代码 [url=][/url]
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
- import org.apache.commons.lang.StringUtils;
- import org.apache.log4j.Logger;
- /**
- * @author lixuanbin
- * @creation 2013-1-30
- */
- public
class SignatureUtil { - protected
static Logger log = Logger.getLogger(SignatureUtil.class);
- private
static
final
char[] hexArray = "0123456789ABCDEF".toCharArray();
- private String encryptionAlgorithm = "SHA-1";
- public String bytesToHexString(byte[] bytes) {
- char[] hexChars = new
char[bytes.length * 2]; - for (int j = 0; j < bytes.length; j++) {
- int v = bytes[j] & 0xFF;
- hexChars[j * 2] = hexArray[v >>> 4];
- hexChars[j * 2 + 1] = hexArray[v & 0x0F];
- }
- return
new String(hexChars); - }
- public
byte[] hexStringToBytes(String s) { - int len = s.length();
- byte[] data = new
byte[len / 2]; - for (int i = 0; i < len; i += 2) {
- data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character
- .digit(s.charAt(i + 1), 16));
- }
- return data;
- }
- /**
- * 使用指定算法生成消息摘要,默认是md5
- *
- * @param strSrc
- * , a string will be encrypted; <br/>
- * @param encName
- * , the algorithm name will be used, dafault to "MD5"; <br/>
- * @return
- */
- public String digest(String strSrc, String encName) {
- MessageDigest md = null;
- String strDes = null;
- byte[] bt = strSrc.getBytes();
- try {
- if (encName == null || encName.equals("")) {
- encName = "MD5";
- }
- md = MessageDigest.getInstance(encName);
- md.update(bt);
- strDes = bytesToHexString(md.digest()); // to HexString
- } catch (NoSuchAlgorithmException e) {
- log.error("Invalid algorithm: " + encName);
- return
null; - }
- return strDes;
- }
- /**
- * 根据appid、token、lol以及时间戳来生成签名
- *
- * @param appid
- * @param token
- * @param lol
- * @param millis
- * @return
- */
- public String generateSignature(String appid, String token, String lol,
- long millis) {
- String timestamp = String.valueOf(millis);
- String signature = null;
- if (StringUtils.isNotBlank(token) && StringUtils.isNotBlank(timestamp)
- && StringUtils.isNotBlank(appid)) {
- List<String> srcList = new ArrayList<String>();
- srcList.add(timestamp);
- srcList.add(appid);
- srcList.add(token);
- srcList.add(lol);
- // 按照字典序逆序拼接参数
- Collections.sort(srcList);
- Collections.reverse(srcList);
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < srcList.size(); i++) {
- sb.append(srcList.get(i));
- }
- signature = digest(sb.toString(), encryptionAlgorithm);
- srcList.clear();
- srcList = null;
- }
- return signature;
- }
- /**
- * 验证签名: <br/>
- * 1.根据appid获取该渠道的token;<br/>
- * 2.根据appid、token、lol以及时间戳计算一次签名;<br/>
- * 3.比较传过来的签名以及计算出的签名是否一致;
- * @param signature
- * @param appid
- * @param lol
- * @param millis
- * @return
- */
- public
boolean isValid(String signature, String appid, String lol, - long millis) {
- String token = findTokenById(appid);
- String calculatedSignature = generateSignature(appid, token, lol,
- millis);
- log.info("calculated signature: \n" + calculatedSignature);
- if (StringUtils.equals(calculatedSignature, signature)) {
- return
true; - } else {
- return
false; - }
- }
- /**
- * FIXME For demo only, should be a different string in production.
- * @param appid
- * @return
- */
- public String findTokenById(String appid) {
- String token = "#@!1234567890!@#";
- return token;
- }
- public
static
void main(String[] args) { - SignatureUtil generator = new SignatureUtil();
- String xmlString = "<root><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name><name>test</name></root>";
- System.out.println(xmlString.getBytes().length);
- String digest = generator.digest(xmlString, "MD5");
- System.out.println(digest);
- System.out.println(digest.getBytes().length);
- String appid = "canairport001";
- String token = generator.findTokenById(appid);
- long millis = System.currentTimeMillis();
- String signature = generator.generateSignature(appid, token, digest,
- millis);
- System.out.println(signature);
- boolean isValid = generator.isValid(signature, appid, digest, millis);
- System.out.println(isValid);
- }
- }
3.发送方代码:
Java代码 [url=][/url]
- import java.io.IOException;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Map.Entry;
- import org.apache.commons.lang.StringUtils;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpHost;
- import org.apache.http.HttpResponse;
- import org.apache.http.HttpStatus;
- import org.apache.http.auth.AuthScope;
- import org.apache.http.auth.UsernamePasswordCredentials;
- import org.apache.http.client.ClientProtocolException;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.conn.params.ConnRoutePNames;
- import org.apache.http.entity.StringEntity;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.message.BasicHeader;
- import org.apache.http.protocol.HTTP;
- import org.apache.http.util.EntityUtils;
- import org.apache.log4j.Logger;
- /**
- * @author ben
- * @creation 2014年6月9日
- */
- public
class HttpclientUtil { - protected
static
final Logger log = Logger.getLogger(HttpclientUtil.class);
- /**
- * 根据传入的uri和参数map拼接成实际uri
- *
- * @param uri
- * @param paraMap
- * @return
- */
- public String buildUri(String uri, Map<String, String> paraMap) {
- StringBuilder sb = new StringBuilder();
- uri = StringUtils.trim(uri);
- uri = StringUtils.removeEnd(uri, "/");
- uri = StringUtils.removeEnd(uri, "?");
- sb.append(uri);
- if (paraMap != null && !paraMap.isEmpty()) {
- sb.append("?");
- Iterator<Entry<String, String>> iterator = paraMap.entrySet()
- .iterator();
- while (iterator.hasNext()) {
- Map.Entry<String, String> pair = iterator.next();
- try {
- String keyString = pair.getKey();
- String valueString = pair.getValue();
- sb.append(keyString);
- sb.append("=");
- sb.append(valueString);
- sb.append("&");
- } catch (Exception e) {
- log.error(e, e);
- }
- }
- }
- return StringUtils.removeEnd(sb.toString(), "&");
- }
|
|
|
|
|
|