实现代码 上面写了备注

 //随机的uuid        String uuid = UUID.randomUUID().toString();        //定义传输的数据 userName是我接收的参数        final String s = "TEL=" + username + "&SEQ=" + uuid;        //key是我后端的协商秘钥        String key = "";        //aes加密 这里有个aes的工具类        final AES aes = new AES(key);        byte[] enContentSend = aes.encrypt(s, key);        assert enContentSend != null;        final ByteBuffer bf = ByteBuffer.allocate(4 + enContentSend.length);        bf.putInt(enContentSend.length);        bf.put(enContentSend);        bf.position(0);        logger.info("将字符串长度转换为byte" + Arrays.toString(bf.array()));        //设置ip地址        final String hostIP = "192.168.7.1";        //设置端口地址        final int port = 8080;        new Thread(new Runnable() {            @Override            public void run() {                DatagramSocket socket = null;                try {                    socket = new DatagramSocket();                    socket.setSoTimeout(3_000);                    // 2、创建host的地址包装实例                    SocketAddress socketAddr = new InetSocketAddress(hostIP, port);                    DatagramPacket out = new DatagramPacket(bf.array(), bf.capacity(), socketAddr);                    socket.send(out);                    byte[] buffer = new byte[1024];                    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);                    socket.receive(packet);                    enContentReceive = AES.byte2hex(packet.getData()).substring(0, 136);                    logger.error("收到加密密文(带数据长度):" + enContentReceive);                    String enContentRec = enContentReceive.substring(8);                    logger.error("收到加密密文(纯加密数据):" + enContentRec);                    enContentRec = enContentRec.substring(0, 32);                     //使用秘钥解密                    String deContent = aes.decrypt(enContentRec, "0123456789012345");                    logger.error("加密的数据" + enContentRec + "解密的数据" + deContent);                    //93119462813                    //成功和失败的结果处理 具体的按后台返回处理                    if (deContent != null && deContent.equals("RESULT=ERROR")) {                                            }                    if (deContent != null && deContent.equals("RESULT=SUCCESS")) {                                           }                } catch (IOException e) {                    e.printStackTrace();                    logger.error(e.getMessage());                } catch (Exception e) {                    logger.error(e.getMessage());                    e.printStackTrace();                } finally {                    if (null != socket) {                        socket.close();                    }                }            }        }).start();

 下面是AES加密解密的工具类

import javax.crypto.Cipher;import javax.crypto.spec.SecretKeySpec;/** * This program generates a AES key, retrieves its raw bytes, and then * reinstantiates a AES key from the key bytes. The reinstantiated key is used * to initialize a AES cipher for encryption and decryption. */public class AES {    private static final String AES = "AES";    private static String CRYPT_KEY = "xinli_zhejiang12";    private static AESinstance;    /**     * Instantiates a new Aes.     *     * @param key the key     */    public AES(String key)    {        CRYPT_KEY=key;    }    /**     * 加密     *     * @param src the src     * @param key the key     * @return byte [ ]     * @throws Exception the exception     */    public  byte[] encrypt(byte[] src, String key) throws Exception {        Cipher cipher = Cipher.getInstance(AES);        SecretKeySpec securekey = new SecretKeySpec(key.getBytes(), AES);        cipher.init(Cipher.ENCRYPT_MODE, securekey);//设置密钥和加密形式        return cipher.doFinal(src);    }    /**     * 加密     *     * @param data the data     * @param key  the key     * @return byte [ ]     * @throws Exception     */    public final  byte[] encrypt(String data,String key) {        try {            return encrypt(data.getBytes(), key);        } catch (Exception e) {        }        return null;    }    /**     * 解密     *     * @param src the src     * @param key the key     * @return byte [ ]     * @throws Exception the exception     */    public static byte[] decrypt(byte[] src, String key)  throws Exception  {        Cipher cipher = Cipher.getInstance(AES);        SecretKeySpec securekey = new SecretKeySpec(key.getBytes(), AES);//设置加密Key        cipher.init(Cipher.DECRYPT_MODE, securekey);//设置密钥和解密形式        return cipher.doFinal(src);    }    /**     * 解密     *     * @param data the data     * @param key  the key     * @return string     * @throws Exception     */    public final  String decrypt(String data,String key) {        try {            return new String(decrypt(hex2byte(data.getBytes()),                    key));        } catch (Exception e) {        }        return null;    }    /**     * 二行制转十六进制字符串     *     * @param b the b     * @return string     */    public static String byte2hex(byte[] b) {        String hs = "";        String stmp = "";        for (int n = 0; n < b.length; n++) {            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));            if (stmp.length() == 1)                hs = hs + "0" + stmp;            else                hs = hs + stmp;        }        return hs.toUpperCase();    }    /**     * Hex 2 byte byte [ ].     *     * @param b the b     * @return the byte [ ]     */    public 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;    }    /**     * 加密     *     * @param data the data     * @return string     * @throws Exception     */    public final  String encrypt(String data) {        try {            return byte2hex(encrypt(data.getBytes(), CRYPT_KEY));        } catch (Exception e) {        }        return null;    }    /**     * Int to byte array byte [ ].     *     * @param i the     * @return the byte [ ]     */    public  byte[] intToByteArray(int i) {        byte[] result = new byte[4];        //由高位到低位        result[0] = (byte)((i >> 24) & 0xFF);        result[1] = (byte)((i >> 16) & 0xFF);        result[2] = (byte)((i >> 8) & 0xFF);        result[3] = (byte)(i & 0xFF);        return result;    }}

 

更多相关文章

  1. Android日常知识收集与总结之EditText篇
  2. Android(安卓)library projects cannot be launched问题的解决
  3. android opengl 渲染的3D色子
  4. Android中文API (60) ―― DatePicker.OnDateChangedListener
  5. 关于Android(安卓)渐变动画 淡入效果的实现
  6. android 设置全屏方法1
  7. Android(安卓)背景虚化实现
  8. sysclktz 0
  9. android 图片放大缩小 多点缩放

随机推荐

  1. android弹出抉择对话框-仿某团购网androi
  2. 第一章 JAVA入门(Android 版本历史)
  3. Android(安卓)Reveal圆形Activity转场动
  4. 关于基本控件TextView属性大全详解
  5. Android IPC机制——Binder详解
  6. [置顶] android 自定义控件
  7. 关于EditText
  8. android xml解析之Pull
  9. Android沉浸式通知栏开源库SystemBarTint
  10. Android IPC机制(二):AIDL的基本使用方法