IT月光

导航

登录与注册的加密

//Utils类

package com.bwei.utils;

import java.security.Key;
import java.security.MessageDigest;
import java.security.spec.AlgorithmParameterSpec;
import java.util.UUID;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
* DES加密和解密
* MD5加密
* @author wangfei
*/
public class DESMD5Utils {
    
    

    /**
     * MD5加密
     * @param str
     * @param isUp 
     * true是否大写
     * @return
     */
    public  String MD5(String str, boolean isUp) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        char[] charArray = str.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);

        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = (md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        if (isUp) {
            return (hexValue.toString()).toUpperCase();
        } else {
            return hexValue.toString();
        }
    }
    
    
    
    
    
    
    
    
    
    
    
    
    

   
    
    
    
    public String ALGORITHM_DES = "DES/CBC/PKCS5Padding";

    public String DESKEY = "QpOiUnYbVp3bB73Fsn7O12CX";


    /**
     * 默认加密方式
     * 
     * @param data
     * @return
     */
    public String encrypt(String data) {
        String str = encrypt(DESKEY, data);
        return str;
    }

    /**
     * 默认解密方式
     * @param data
     * @return
     */
    public String decrypt(String data) {

        String str = decrypt(DESKEY, data);
        return str;
    }

    /**
     * DES算法,加密
     * 
     * @param data
     *            待加密字符串
     * @param key
     *            加密私钥,长度不能够小于8位
     * @return 加密后的字节数组,一般结合Base64编码使用
     * @throws InvalidAlgorithmParameterException
     * @throws Exception
     */
    public  String encrypt(String key, String data) {
        if (data == null)
            return null;
        try {
            DESKeySpec dks = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            // key的长度不能够小于8位字节
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
            AlgorithmParameterSpec paramSpec = iv;
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
            byte[] bytes = cipher.doFinal(data.getBytes());
            return byte2hex(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            return data;
        }
    }

    /**
     * DES算法,解密
     * 
     * @param data
     *            待解密字符串
     * @param key
     *            解密私钥,长度不能够小于8位
     * @return 解密后的字节数组
     * @throws Exception
     *             异常
     */
    public String decrypt(String key, String data) {
        if (data == null)
            return null;
        try {
            DESKeySpec dks = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            // key的长度不能够小于8位字节
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
            AlgorithmParameterSpec paramSpec = iv;
            cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
            return new String(cipher.doFinal(hex2byte(data.getBytes())));
        } catch (Exception e) {
            e.printStackTrace();
            return data;
        }
    }

    /**
     * 二行制转字符串
     * 
     * @param b
     * @return
     */
    private static String byte2hex(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toUpperCase();
    }

    private static byte[] hex2byte(byte[] b) {
        if ((b.length % 2) != 0)
            throw new IllegalArgumentException();
        byte[] b2 = new byte[b.length / 2];
        for (int n = 0; n < b.length; n += 2) {
            String item = new String(b, n, 2);
            b2[n / 2] = (byte) Integer.parseInt(item, 16);
        }
        return b2;
    }
    
    
    
    
    
    
    
    
    
    
    
    

}

//加密的主类

package com.bwei.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class HttpUtils {

    private DESMD5Utils utils;

    public HttpUtils() {
        super();
        utils = new DESMD5Utils();
    }

    public String registerUser(String nick_name, String phone_num,
            String user_password) {
        String uri = "http://169.254.109.73:8080/MyPaoT/register";
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(uri);
        BasicNameValuePair basicNameValuePair = null;
        List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();

        try {
            String string = URLEncoder.encode(nick_name,"utf-8");
            String encrypt = utils.encrypt(string);
            basicNameValuePair = new BasicNameValuePair("nick_name", encrypt);
            parameters.add(basicNameValuePair);
        } catch (UnsupportedEncodingException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
        
//encrypt加密
        String encrypt2 = utils.encrypt(phone_num);
        basicNameValuePair = new BasicNameValuePair("phone_num", encrypt2);
        parameters.add(basicNameValuePair);

        String md5 = utils.MD5(user_password, false);
        String encrypt3 = utils.encrypt(md5);
        basicNameValuePair = new BasicNameValuePair("user_password", encrypt3);
        parameters.add(basicNameValuePair);

        HttpEntity entity = null;
        try {
            entity = new UrlEncodedFormEntity(parameters, HTTP.UTF_8);
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        post.setEntity(entity);
        try {
            HttpResponse response = client.execute(post);

            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity2 = response.getEntity();
                return EntityUtils.toString(entity2);
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public String loginUser(String phone_num, String user_password) {
        String uri = "http://169.254.109.73:8080/MyPaoT/login";
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(uri);
        BasicNameValuePair basicNameValuePair = null;
        List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();

        String encrypt2 = utils.encrypt(phone_num);
        basicNameValuePair = new BasicNameValuePair("phone_num", encrypt2);
        parameters.add(basicNameValuePair);

        String md5 = utils.MD5(user_password, false);
        String encrypt3 = utils.encrypt(md5);
        basicNameValuePair = new BasicNameValuePair("user_password", encrypt3);
        parameters.add(basicNameValuePair);

        HttpEntity entity = null;
        try {
            entity = new UrlEncodedFormEntity(parameters, HTTP.UTF_8);
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        post.setEntity(entity);
        try {
            HttpResponse response = client.execute(post);

            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity2 = response.getEntity();
                return EntityUtils.toString(entity2);
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

 

posted on 2016-05-11 16:51  IT月光  阅读(258)  评论(0编辑  收藏  举报