AES數據加密傳輸


問題:當數據調用沒有使用https加密時,app被抓包,接口暴露,此時可能導致被刷等安全問題

解決:1. 使用https傳輸

   2. 在進行數據傳輸時進行手動加密(app端和后端定義統一的加密方式),這里采用普遍使用的AES+Base64加密

    (注:AES加密方式中,生成安全隨機數序列的加密方式,會導致java和安卓聯調時出現無法解密的問題,文末會說)

加密后預期結果:

  

新建工具類並測試:

package com.demo.utils;


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

public class AESUtil {

//    private static final String SECRET_KEY = "51f14cbda893c2bc13826c2c1a0c88aa";//32位小寫
    private static final String SECRET_KEY = "a893c2bc13826c2c";//目前jdk版本只支持16位秘鑰(32位的需添加jar包)前后端統一的秘鑰
    private static String ivParameter = "ceshiceshi111111";//偏移量    前后端統一的偏移量// 加密
    public static String encrypt(String content) {
        if (content == null || content.replaceAll(" ", "").equals("")) {
            return "";
        }
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// 創建密碼器
            byte[] raw = SECRET_KEY.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");// 轉換為AES專用密鑰
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// 使用CBC模式,需要一個向量iv,可增加加密算法的強度
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);// 初始化為加密模式的密碼器
            byte[] byteRresult = cipher.doFinal(content.getBytes("utf-8"));// 加密
            return new StringBuilder(Base64.encode(byteRresult)).reverse().toString();//進行base64編碼,並倒序轉換
        } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException
                | IllegalBlockSizeException | BadPaddingException e) {
            return "";
        } catch (UnsupportedEncodingException | InvalidAlgorithmParameterException e) {
            e.printStackTrace();
            return "";
        }
    }

    // 解密
    public static String decrypt(String content) {
        if (content == null || content.replaceAll(" ", "").equals("")) {
            return "";
        }
        try {
            byte[] byteRresult = Base64.decode(new StringBuilder(content).reverse().toString());//倒序轉換並base64解碼
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// 創建密碼器
            byte[] raw = SECRET_KEY.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");// 轉換為AES專用密鑰
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// 使用CBC模式,需要一個向量iv,可增加加密算法的強度
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);// 初始化為加密模式的密碼器
            byte[] result = cipher.doFinal(byteRresult);// 解密
            return new String(result);
        } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException
                | IllegalBlockSizeException | BadPaddingException e) {
            return "";
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
            return "";
        }
    }
    
    public static void main(String[] args) {
        String content = "程序默認沒有bug";
        System.out.println("加密之前:" + content);

        // 加密
        String jiami = AESUtil.encrypt(content);
        System.out.println("加密后的內容:" + jiami);

        // 解密
        String jiemi = AESUtil.decrypt(jiami);
        System.out.println("解密后的內容:" + jiemi);

    }

}

 

java中Base64的加密工具封裝:

package com.mobile.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

/**
 * Created by Administrator on 2017/10/25.
 */
public class Base64 {
    private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();

    public static String encode(byte[] data) {
        int start = 0;
        int len = data.length;
        StringBuffer buf = new StringBuffer(data.length * 3 / 2);

        int end = len - 3;
        int i = start;
        int n = 0;

        while (i <= end) {
            int d = ((((int) data[i]) & 0x0ff) << 16) | ((((int) data[i + 1]) & 0x0ff) << 8) | (((int) data[i + 2]) & 0x0ff);

            buf.append(legalChars[(d >> 18) & 63]);
            buf.append(legalChars[(d >> 12) & 63]);
            buf.append(legalChars[(d >> 6) & 63]);
            buf.append(legalChars[d & 63]);

            i += 3;

            if (n++ >= 14) {
                n = 0;
                buf.append(" ");
            }
        }

        if (i == start + len - 2) {
            int d = ((((int) data[i]) & 0x0ff) << 16) | ((((int) data[i + 1]) & 255) << 8);

            buf.append(legalChars[(d >> 18) & 63]);
            buf.append(legalChars[(d >> 12) & 63]);
            buf.append(legalChars[(d >> 6) & 63]);
            buf.append("=");
        } else if (i == start + len - 1) {
            int d = (((int) data[i]) & 0x0ff) << 16;

            buf.append(legalChars[(d >> 18) & 63]);
            buf.append(legalChars[(d >> 12) & 63]);
            buf.append("==");
        }

        return buf.toString();
    }

    private static int decode(char c) {
        if (c >= 'A' && c <= 'Z')
            return ((int) c) - 65;
        else if (c >= 'a' && c <= 'z')
            return ((int) c) - 97 + 26;
        else if (c >= '0' && c <= '9')
            return ((int) c) - 48 + 26 + 26;
        else
            switch (c) {
                case '+':
                    return 62;
                case '/':
                    return 63;
                case '=':
                    return 0;
                default:
                    throw new RuntimeException("unexpected code: " + c);
            }
    }

    /**
     * Decodes the given Base64 encoded String to a new byte array. The byte array holding the decoded data is returned.
     */

    public static byte[] decode(String s) {

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            decode(s, bos);
        } catch (IOException e) {
            throw new RuntimeException();
        }
        byte[] decodedBytes = bos.toByteArray();
        try {
            bos.close();
            bos = null;
        } catch (IOException ex) {
            System.err.println("Error while decoding BASE64: " + ex.toString());
        }
        return decodedBytes;
    }

    private static void decode(String s, OutputStream os) throws IOException {
        int i = 0;

        int len = s.length();

        while (true) {
            while (i < len && s.charAt(i) <= ' ')
                i++;

            if (i == len)
                break;

            int tri = (decode(s.charAt(i)) << 18) + (decode(s.charAt(i + 1)) << 12) + (decode(s.charAt(i + 2)) << 6) + (decode(s.charAt(i + 3)));

            os.write((tri >> 16) & 255);
            if (s.charAt(i + 2) == '=')
                break;
            os.write((tri >> 8) & 255);
            if (s.charAt(i + 3) == '=')
                break;
            os.write(tri & 255);

            i += 4;
        }
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String content = "程序默認沒有bug";
        System.out.println("加密之前:" + content);

        // 加密
        String jiami = Base64.encode(content.getBytes("utf-8"));
        System.out.println("加密后的內容:" + jiami);

        // 解密
        String jiemi = new String(Base64.decode(jiami));
        System.out.println("解密后的內容:" + jiemi);
    }
}

 

運行結果如圖:

 

以下加密在進行與android聯調時會出現問題(單純java后台使用可以用)

剛開始時使用了AES的另一種加密方式:但是在與android聯調時出現問題,具體如下:

package com.mobile.utils;


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

public class AESUtil {

    private static final String SECRET_KEY = "51f14cbda893c2bc13826c2c1a0c88aa";//xinyongdashi MD5加密32位小寫//此方法會在安卓和java聯調時出現問題(默認隨機數序列不一致)解決:不要使用默認的創建方法。
    public static String encry(String content) {
        if (content == null || content.replaceAll(" ", "").equals("")) {
            return "";
        }
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");  // 創建AES的Key生產者
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");// 初始化出
            random.setSeed(SECRET_KEY.getBytes());//利用自定義SECRET_KEY作為隨機數
            kgen.init(128, random);// 128位的key生產者       //加密沒關系,SecureRandom是生成安全隨機數序列,SECRET_KEY.getBytes()是種子,只要種子相同,序列就一樣,所以解密只要有password就行
            SecretKey secretKey = kgen.generateKey();//根據用戶密碼,生成一個密鑰
            byte[] enCodeFormat = secretKey.getEncoded();// 返回基本編碼格式的密鑰,如果此密鑰不支持編碼,則返回null。
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");// 轉換為AES專用密鑰
            Cipher cipher = Cipher.getInstance("AES");// 創建密碼器
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);// 初始化為加密模式的密碼器
            byte[] byteRresult = cipher.doFinal(byteContent);// 加密
            /*StringBuilder sb = new StringBuilder();
            for (byte aByteRresult : byteRresult) {
                String hex = Integer.toHexString(aByteRresult & 0xFF);
                if (hex.length() == 1) {
                    hex = '0' + hex;
                }
                sb.append(hex.toUpperCase());
            }
            return sb.toString();*/
            return new StringBuilder(Base64.encode(byteRresult)).reverse().toString();//進行base64編碼
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
                | UnsupportedEncodingException | IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String unencry(String content) {
        if (content == null || content.replaceAll(" ", "").equals("")) {
            return "";
        }
        /*byte[] byteRresult = new byte[content.length() / 2];
        for (int i = 0; i < content.length() / 2; i++) {
            int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16);
            byteRresult[i] = (byte) (high * 16 + low);
        }*/
        try {
            byte[] byteRresult = Base64.decode(new StringBuilder(content).reverse().toString());//base64解碼
            KeyGenerator kgen = KeyGenerator.getInstance("AES");// 創建AES的Key生產者
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(SECRET_KEY.getBytes());//利用自定義SECRET_KEY作為隨機數
            kgen.init(128, random);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();//返回基本編碼格式的密鑰
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");// 轉換為AES專用密鑰
            Cipher cipher = Cipher.getInstance("AES");// 創建密碼器
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);// 初始化為解密模式的密碼器
            byte[] result = cipher.doFinal(byteRresult);
            return new String(result);
        } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException
                | IllegalBlockSizeException | BadPaddingException e) {
            return "";
        }
    }public static void main(String[] args) {
        String content = "程序默認沒有bug";
        System.out.println("加密之前:" + content);

        // 加密
        String jiami = AESUtil.encrypt(content);
        System.out.println("加密后的內容:" + jiami);

        // 解密
        String jiemi = AESUtil.decrypt(jiami);
        System.out.println("解密后的內容:" + jiemi);

    }

}

使用此方式加密的結果就是:android端的加密數據,后台解密不了;

 

所以應該使用AES中的cbc模式(秘鑰+偏移向量),即文章開始說的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM