码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2020-05-21 21:05:07      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:ring   init   生成   uri   stack   ted   invalid   lin   adp   

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.构造密钥生成器
     * 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");
            //初始化密码器
            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();
        }
        //如果有错就大胆抛空
        return null;
    }
    /*
     * 解密
     * 过程和加密基本类似
     */
    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");
            //初始化密码器
            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();
        }

        //如果有错就大胆抛空
        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

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

标签:ring   init   生成   uri   stack   ted   invalid   lin   adp   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!