java传输json数据用md5加密过程
1.加密过程:客户端传输数据,包含两部分,一部分原始数据,一部分签名。签名就是对原始数据MD5加密后的字节序列。而原始数据就是普通的string字符串。
2.服务器端呢:将收到的原始数据,进行MD5加密后得到字节序列,将这个字节序列与传输过来的sign的value,进行对比。如果俩sign值一样,则数据没有被破坏。认证加密成功。
3.进行操作MD5,java sdk已经内置支持了,有java.security包,其中的MessageDiggest类。
客户端加密代码如下:
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
APPMain appMain = new APPMain();
URL url = new URL(urlString);
JSONObject returnJson;
try {
returnJson = appMain.getResponse(url);
System.out.println(JSONObject.toJSONString(returnJson));
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public JSONObject getResponse(URL url) throws IOException, NoSuchAlgorithmException {
//��������
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestProperty("Content-type", "application/json");
httpURLConnection.connect();
//post��������
OutputStream outStrm = httpURLConnection.getOutputStream();
DataOutputStream objOutputStrm = new DataOutputStream(outStrm);
JSONObject obj = new JSONObject();
JSONObject commentJson = new JSONObject();
commentJson.put("phone", "13823135363");
obj.put("param", commentJson);
obj.put("ts", "abc");
obj.put("mn", "abc");
obj.put("imei", "abc");
obj.put("version", "abc");
obj.put("token", "abc");
StringBuilder sBuilder = new StringBuilder();
createBeforeEncryptString(sBuilder,"ts","abc","&");
createBeforeEncryptString(sBuilder,"mn","abc","&");
createBeforeEncryptString(sBuilder,"imei","abc","&");
createBeforeEncryptString(sBuilder,"version","abc","&");
createBeforeEncryptString(sBuilder,"token","abc","&");
createBeforeEncryptString(sBuilder,"param",commentJson.toJSONString(),"");
String encrapted = sBuilder.toString();
obj.put("sign", md5Encrypt(encrapted));
objOutputStrm.writeBytes(obj.toString());
objOutputStrm.flush();
objOutputStrm.close();
//input
BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String lines =reader.readLine();//��ȡ������
JSONObject inputJson=JSONObject.parseObject(lines);
reader.close();
System.out.println(md5Encrypt(encrapted));
return inputJson;
}
public String md5Encrypt(String content) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update( content.getBytes() );
return getHashString( md );
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public String getHashString( MessageDigest digest )
{
StringBuilder builder = new StringBuilder();
for ( byte b : digest.digest() )
{
builder.append( Integer.toHexString( (b >> 4) & 0xf ) );
builder.append( Integer.toHexString( b & 0xf ) );
}
return builder.toString();
}
public void createBeforeEncryptString(StringBuilder sb,String key,String value,String gap) {
sb.append(key).append("=").append(value).append(gap);
}
}
服务器端代码如下:
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { BodyReaderHttpServletRequestWrapper requestWrapper = null; if (request instanceof HttpServletRequest) { requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request); } String body = requestWrapper.getBody(); if(!StringUtils.isEmpty(body)){ ParamIn param = JSONObject.parseObject(body, ParamIn.class); StringBuilder _sb = new StringBuilder(); _sb.append("ts").append("=").append(param.getTs()).append("&"); _sb.append("mn").append("=").append(param.getMn()).append("&"); _sb.append("imei").append("=").append(param.getImei()).append("&"); _sb.append("version").append("=").append(param.getVersion()).append("&"); _sb.append("token").append("=").append(param.getToken()); if(!StringUtils.isEmpty(param.getParam())){ _sb.append("&").append("param").append("=").append(param.getParam()); } logger.info("to be encrypted: " + _sb.toString()); String md5Encrypted = HashEncoder.encode(HashAlgorithm.MD5, _sb.toString()); logger.info("encrypted: " + md5Encrypted); if(!md5Encrypted.equalsIgnoreCase(param.getSign())){ logger.info("sign invalid"); this.response(response, JSONObject.toJSONString(new ResultObject(ResultCode.SIGN_INVALID))); return; }else{ logger.info("valid sign success"); } }else{ this.response(response, JSONObject.toJSONString(new ResultObject(ResultCode.NULL_PARAM))); return; } //签名验证成功 chain.doFilter(requestWrapper, response); }