java httpServer端接受post请求数据并使用3DES+base64加密解密demo希望能够对您有帮助

来源:互联网 发布:阿里云设置二级域名 编辑:程序博客网 时间:2024/06/14 21:00
/***这是httpServer端的程序*/package com.caitong.httpserver;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.InetSocketAddress;import java.util.Iterator;import java.util.List;import java.util.Set;import javax.servlet.http.HttpServletRequest;import org.apache.commons.io.IOUtils;import org.apache.http.HttpRequest;import com.caitong.httpserver.util.Encrypt;import com.sun.net.httpserver.Headers;import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpHandler;import com.sun.net.httpserver.HttpServer;public class HttpServerTest {//主线程public static void main(String[] args) { try {              //允许最大连接数              int backLog = 10;             //绑定的端口            HttpServer httpServer = HttpServer.create(new InetSocketAddress("192.168.20.204", 8877), backLog);            //直接返回Hello.....              httpServer.createContext("/demo1", new DemoA());             //显示已经处理的请求数,采用线程池              httpServer.setExecutor(null);              httpServer.start();              System.out.println("HttpServer启动...!");          } catch (Exception e) {              e.printStackTrace();          }  }//获取请求数据并响应回去public static class DemoA implements HttpHandler{  private final byte[] keybyte="1A1FBDD13082FF4722F12783".getBytes();    public void handle(HttpExchange exchange) throws IOException {    System.out.println("ddd");      InputStream in = exchange.getRequestBody(); //获得输入流        BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));       //将BufferedReader转化为字符串      String text = IOUtils.toString(reader);//text是我获取的post提交的数据(现在是字符串的形式)      //转码解密      String tt = Encrypt.DataDecrypt(keybyte, text);      exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, tt.getBytes().length);      OutputStream out = exchange.getResponseBody();  //获得输出流            out.write(tt.getBytes());            out.flush();            exchange.close();                                     }        } }package com.caitong.httpserver.util;import java.io.IOException;import javax.crypto.Cipher;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;import java.io.UnsupportedEncodingException;import java.net.URLDecoder;import java.net.URLEncoder;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;/** * 加密解密工具类(3DES+Base64工具的集成类) * @author * @version  */public class Encrypt {    private static final Log log = LogFactory.getLog(Encrypt.class);        /***     * 加密密钥     */    private final byte[] keybyte="1A1FBDD13082FF4722F12783".getBytes(); //keybyte为加密密钥,长度为24字节    /**     * 加密方法提供3des加密,并且base64编码     * @param key 24字节的密钥     * @param str 明文     * @return     */    public static String DataEncrypt(byte[] key, String str ) {        String encrypt = null;        try {            byte[] ret = ThreeDes.encryptMode(key,str.getBytes("UTF-8"));            encrypt = new String(Base64Util.encode(ret));        } catch (Exception e) {            System.out.print(e);            encrypt = str;        }        return encrypt;    }    /***     * 解密方法,先解密base64,在按3des解密     * @param key 24字节的密钥     * @param str 密文     * @return     */    public static String DataDecrypt(byte[] key,String str ) {        String decrypt = null;        try {            byte[] ret = ThreeDes.decryptMode( key,Base64Util.decode(str));            decrypt = new String(ret, "UTF-8");        } catch (Exception e) {            System.out.print(e);            decrypt = str;        }        return decrypt;    }}/***3DES的加密解密类*/package com.caitong.httpserver.util;import java.security.*;import javax.crypto.*;import javax.crypto.spec.SecretKeySpec;/** * 字符串 DESede(3DES) 加密 * @author  * @version  */public class ThreeDes {    private static final String Algorithm = "DESede"; // 定义 加密算法,可用    // keybyte为加密密钥,长度为24字节    // src为被加密的数据缓冲区(源)    public static byte[] encryptMode(byte[] keybyte, byte[] src) {        try {            // 生成密钥            SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);            // 加密            Cipher c1 = Cipher.getInstance(Algorithm);            c1.init(Cipher.ENCRYPT_MODE, deskey);            return c1.doFinal(src);        } catch (java.security.NoSuchAlgorithmException e1) {            e1.printStackTrace();        } catch (javax.crypto.NoSuchPaddingException e2) {            e2.printStackTrace();        } catch (java.lang.Exception e3) {            e3.printStackTrace();        }        return null;    }    // keybyte为加密密钥,长度为24字节    // src为加密后的缓冲区    public static byte[] decryptMode(byte[] keybyte, byte[] src) {        try {            // 生成密钥            SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);            // 解密            Cipher c1 = Cipher.getInstance(Algorithm);            c1.init(Cipher.DECRYPT_MODE, deskey);            return c1.doFinal(src);        } catch (java.security.NoSuchAlgorithmException e1) {            e1.printStackTrace();        } catch (javax.crypto.NoSuchPaddingException e2) {            e2.printStackTrace();        } catch (java.lang.Exception e3) {            e3.printStackTrace();        }        return null;    }  }/***Base64工具类*/package com.caitong.httpserver.util;/** * base64编码工具类 * @author  * @version */public class Base64Util {    /**     *  将 s 进行 BASE64 编码     * @param s     * @return     */    public static String encode(byte[] s) {        if (s == null)            return null;        return (new sun.misc.BASE64Encoder()).encode(s);    }    /**     *  将 s 进行 BASE64 编码     * @param s     * @return     */    public static String encode(String s) {                if (s == null)            return null;        return encode(s.getBytes());    }    /**将 BASE64 编码的字符串 s 进行解码     *     * @param s     * @return     */    public static byte[] decode(String s) {        if (s == null)            return null;        sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();        try {            byte[] b = decoder.decodeBuffer(s);            return b;        } catch (Exception e) {            return null;        }    }    /**     * @param args     */    public static void main(String[] args) {      /*  String a = "asdfsfsd";        String b = encode(a);        System.out.println(b);        System.out.println(decode(b));*/    }}

0 0
原创粉丝点击