安卓客户端与服务端对称加密传输demo

时间:2020-05-21
本文章向大家介绍安卓客户端与服务端对称加密传输demo,主要包括安卓客户端与服务端对称加密传输demo使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

APP端传输一些敏感到后台服务端的时候,我们一般都是需要加密传输的。至于使用对称加密还是非对称加密的话,就得看你对数据有多负责了。
下面是我在开发中用到的一个使用AES对称加密传输的demo(亲测有用),希望这个demo对你有一定参考价值。对称加密非对称加密的原理这里就不废话了,直接上代码

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * 对称加解密工具类
 * created by 一头小菜鸡 
 */
public class AesUtil {
    /*
     * 加密
     * 1.构造密钥生成器
     * 2.根据ecnodeRules规则初始化密钥生成器
     * 3.产生密钥
     * 4.创建和初始化密码器
     * 5.内容加密
     * 6.返回字符串
     */
    private static final String IV_STRING = "16-Bytes--String"; //这里限制了加密规则只能使16个字符长的字符串

    public  static String AESEncode(String encodeRules,String content) throws  InvalidAlgorithmParameterException {
        try {

            byte[] keyFormat = encodeRules.getBytes("UTF-8");
            byte[] contentFormat = content.getBytes("UTF-8");
            SecretKeySpec secretKeySpec = new SecretKeySpec(keyFormat,"AES");
            byte[] initParam = IV_STRING.getBytes("UTF-8");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);

            Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding");
            //7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec,ivParameterSpec);

            byte [] byte_AES=cipher.doFinal(contentFormat);

            return parseByte2HexStr(byte_AES);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //如果有错就返加nulll
        return null;
    }
    /*
     * 解密
     * 解密过程:
     * 1.同加密1-4步
     * 2.将加密后的字符串反纺成byte[]数组
     * 3.将加密内容解密
     */
    public static String AESDncode(String encodeRules,String content) throws InvalidAlgorithmParameterException {
        try {
            byte[] keyFormat = encodeRules.getBytes("UTF-8");
            byte[] contentFormat = parseHexStr2Byte(content);
            SecretKeySpec secretKeySpec = new SecretKeySpec(keyFormat,"AES");
            byte[] initParam = IV_STRING.getBytes("UTF-8");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);

            Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding");
            //7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec,ivParameterSpec);
            byte [] byte_AES=cipher.doFinal(contentFormat);
            return new String(byte_AES);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }

        //如果有错就返加nulll
        return null;
    }


    /**
     * 将二进制转换成16进制
     * @method parseByte2HexStr
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]){
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < buf.length; i++){
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }


    /**
     * 将16进制转换为二进制
     * @method parseHexStr2Byte
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr){
        if(hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length()/2];
        for (int i = 0;i< hexStr.length()/2; i++) {
            int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
            int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    public static void main(String[] args) throws  InvalidAlgorithmParameterException {
        /*
         * 加密
         */
        String encodeRules="thisisencoderule";
        System.out.println("加密规则为:" + encodeRules);
        String content = "一头小菜鸡的账号和密码";
        System.out.println("加密的内容为:"+content);
        String keyContent = AesUtil.AESEncode(encodeRules,content);
        System.out.println("加密后的内容为:" + keyContent);

        System.out.println("解密后的明文为:"+ AesUtil.AESDncode(encodeRules,keyContent));

    }
}

非常感谢下面两篇博文,更感谢其博主大佬
[1] https://www.iteye.com/blog/songjianyong-1571029
[2] https://www.cnblogs.com/Dennis-mi/articles/6639644.html
[3] https://www.cnblogs.com/liunanjava/p/4297854.html

原文地址:https://www.cnblogs.com/kuangdw/p/12933449.html