Android中UDP发送报文

 实现代码 上面写了备注

 //随机的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 AES	instance;

    /**
     * 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;
    }



}

 

猜你喜欢

转载自blog.csdn.net/weixin_39706415/article/details/98939013