java傳輸json數據用md5加密過程

1.加密過程:客戶端傳輸數據,包含兩部分,一部分原始數據,一部分簽名。簽名就是對原始數據MD5加密後的字節序列。而原始數據就是普通的string字符串。java

2.服務器端呢:將收到的原始數據,進行MD5加密後獲得字節序列,將這個字節序列與傳輸過來的sign的value,進行對比。若是倆sign值同樣,則數據沒有被破壞。認證加密成功。json

3.進行操做MD5,java sdk已經內置支持了,有java.security包,其中的MessageDiggest類。服務器

客戶端加密代碼以下:app

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;
}ide

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);
}
}post

 

服務器端代碼以下:ui

@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);
    }
相關文章
相關標籤/搜索