android和nodejs搭建一個應用


背景

爲什麼想寫這一篇文章呢?做android的開發也有兩年的時間了,就想把以前學到的一些東西記錄下來。於是首先就想在github.com上開一個項目MVPDemo,將一些自己認爲比較好的知識點都串聯起來。

主要目的:
1、初步認識和使用MVP、dagger2和rxJava2
2、使用對稱和非對稱加密加強前端與後臺的安全機制
3、前後臺的socket交互實現

其中3、中的socket實現,我專門建了一個github倉庫NodeTestDemo,這個倉庫不僅僅實現了前端的普通接口,還提供了一個socket服務。

android端實現

1、採用了MVP架構,使用dagger2對象依賴注入框架解耦MVP的各個組件
2、界面採用了autolayout進行兼容適配,UI尺寸標準是720*1080.頁面效果仿微信。
3、rxjava2、rxlifecycle2,rxbinding2等Rx系列的初級使用
4、與後臺服務器接口交互使用了retrofit2,交互的數據格式爲json
5、自定義retrofit2的ConverterFactory和Interceptor實現統一加解密交互的數據流程
6、事件總線eventbus3、控件注入框架butterknife、GreenDao3對象關係映射數據庫的使用
7、socket的前端簡單實現
8、PDF文檔庫android-pdf-viewer的使用
9、使用jsoup解析csdn網站的html頁面獲取博主的博客信息
10、接入bugly。可以使用budly跟蹤異常奔潰信息和bugly基於tinker的熱修復。
11、接入騰訊X5內核瀏覽器服務代替原生的webview
12、頁面路由Arouter的初步使用
13、app端出現異常,在殺死應用前,啓動異常頁面並允許用戶點擊重啓
14、Cmake的使用。可以將敏感或者需要保密的數據使用jni保護,如第三方開發者平臺的appid等

後臺安全數據安全交互機制

1、後臺服務器使用了leancloud和nodejs搭建。nodejs服務器源碼
2、android端的數據加密流程:

nodejs使用的是node-rsa模塊

(1)生成RSA加解密的公鑰和私鑰

var rsa = require('node-rsa');
//create RSA-key
var key = new rsa({b: 1024});

console.log("私:\n" +  key.exportKey('private'));
console.log("公:\n" +  key.exportKey('public'));

將服務器公鑰分發給前端,私鑰保存好放到服務器端。

(2)後臺爲一個前端生成一對AppId和AppScrect。前後端各保存一份,建議在android端將它們放到JNI中保護。

AppId用於在前端參與參數簽名,AppScrect用於服務器返回數據的AES加密密鑰。

(3)在Android端,應用每次啓動時生成用於參數AES加密的密鑰。這樣可以使AES加密密鑰是動態變化的。

(4)、將請求參數按照key的自然順序進行排序,構造源串。然後在源串追加AppId得到簽名字符串signString,用AES密鑰加密signString,得到簽名sign。

/** 按照key的自然順序進行排序,並返回 */
private Map<String, Object> getSortedMapByKey(Map<String, Object> map) {
    Comparator<String> comparator = new Comparator<String>() {
        @Override
        public int compare(String lhs, String rhs) {
            return lhs.compareTo(rhs);
        }
    };
    Map<String, Object> treeMap = new TreeMap<>(comparator);
    for (Map.Entry<String, Object> entry : map.entrySet()) {
        treeMap.put(entry.getKey(), entry.getValue());
    }
    return treeMap;
}

/** 構造源串 */    
public String getSignParamsString(Map<String, Object> map) {
    //map.put("nonce", getRndStr(6 + RANDOM.nextInt(8)));
    //map.put("timestamp", "" + (System.currentTimeMillis() / 1000L));
    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, Object> entry : getSortedMapByKey(map).entrySet()) {
        sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
    }
    return sb.toString();
}

/** 構造源串 */  
public String getSign(Map<String, Object> map) {
    String sign = getSignParamsString(map) + "appId=" + AppConfig.AppId;
    return sign;
}

說明:如果要求服務器只允許一定時間範圍內的請求,可以在getSignParamsString方法中添加時間戳作爲接口簽名的一部分,防止重放攻擊。

(4)將簽名sign和簽名的字符串signString進行AES加密,將AES加密密鑰用服務器公鑰加密,後傳給服務器.

RSAUtils.encryptByServerPublicKey(App.getApp().getAESKey());
AESUtils.encryptData(App.getApp().getAESKey(), signString);
AESUtils.encryptData(App.getApp().getAESKey(), sign);

signString爲什麼在前端生成呢?
爲了在服務器重新生成簽名字符串時,防止由於前後端開發語言的不同而產生不一致。

(5)服務器解密

function valideReqSign(req) {

    var sourceSign = req.body.sign;
    var signString = req.body.signString;
    var key = req.body.aesKey;


    if(paramUtility.isEnpty(key)
        || paramUtility.isEnpty(sourceSign)
        || paramUtility.isEnpty(signString)) {
        return false;
    }

    //a、步驟
    key = serverPrivateKey.decrypt(key,  'utf-8');
    //b、步驟
    signString = aesUtils.AESDec(key, signString);
     //c、步驟
    signString = signString + "appId=" + decAndEncConfig.getAppId();
    var localSign = aesUtils.AESEnc(key, signString);
    //d、步驟
    if(sourceSign !== localSign) {
        var resJson = {
            "data": {},
            "msg": "簽名不正確",
            "status": 205
        };
        if(!paramUtility.isNULL(res)) {
            res.end(jsonUtil.josnObj2JsonString(resJson));
        }
        return false;
    }
    return true;
}

a、取出參數,用服務器RSA私鑰解密AES密鑰
b、用AES密鑰解密簽名和簽名字符串
c、簽名字符串追加分發給前端的AppScrect後,用a、得到的AES加密重新生產簽名。
d、對比前端傳來的簽名和重新生成的簽名是否一致。

(5)根據AppId找到對應的AppScrect,用AppScrect對服務器返回的結果進行AES加密。

注意:確保前後端在不同開發語言情況下,AES算法的結果是一樣的。

後面會給出我用到的java和nodejs版本的RSA和AES加解密算法源碼。

(6)前端從JNI中取出AppScrect對響應結果進行解密即可。

前後端加解密算法源碼

java的RSA加解密算法

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.crypto.Cipher;

public class RSAUtils {

    public static final String PRIVATE_KEY = "填寫自己的private ky";
    private static final String PUBLIC_KEY = AppConfig.RSA_SERVER_PUBLIC_KEY_STR;

    /** RSA最大加密明文大小 */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /** RSA最大解密密文大小 */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /** 加密算法RSA */
    private static final String KEY_ALGORITHM = "RSA";

    /**
     * 生成公鑰和私鑰
     * 
     * @throws Exception
     * 
     */
    public static void getKeys() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        String publicKeyStr = getPublicKeyStr(publicKey);
        String privateKeyStr = getPrivateKeyStr(privateKey);

        System.out.println("公鑰\r\n" + publicKeyStr);
        System.out.println("私鑰\r\n" + privateKeyStr);
    }

    /**
     * 使用模和指數生成RSA公鑰
     * 注意:【此代碼用了默認補位方式,爲RSA/None/PKCS1Padding,不同JDK默認的補位方式可能不同,如Android默認是RSA
     * /None/NoPadding】
     * 
     * @param modulus
     *            模
     * @param exponent
     *            公鑰指數
     * @return
     */
    public static RSAPublicKey getPublicKey(String modulus, String exponent) {
        try {
            BigInteger b1 = new BigInteger(modulus);
            BigInteger b2 = new BigInteger(exponent);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 使用模和指數生成RSA私鑰
     * 注意:【此代碼用了默認補位方式,爲RSA/None/PKCS1Padding,不同JDK默認的補位方式可能不同,如Android默認是RSA
     * /None/NoPadding】
     * 
     * @param modulus
     *            模
     * @param exponent
     *            指數
     * @return
     */
    public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {
        try {
            BigInteger b1 = new BigInteger(modulus);
            BigInteger b2 = new BigInteger(exponent);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
            return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String encryptByServerPublicKey(String data) {
        try {
            return RSAUtils.encryptByPublicKey(data);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String decryptByClentPrivateKey(String data) {
        try {
            return RSAUtils.decryptByPrivateKey(data);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
//
    private String schel = "RSA/ECB/OAEPWithSHA1AndMGF1Padding";
    /**
     * 公鑰加密
     *"RSA/ECB/PKCS1Padding"
     * @param data
     * @return
     * @throws Exception
     */
    private static String encryptByPublicKey(String data) throws Exception {
        byte[] dataByte = data.getBytes();
        byte[] keyBytes = Base64Utils.decode(PUBLIC_KEY);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        // 對數據加密
        // Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicK);
        int inputLen = dataByte.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 對數據分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(dataByte, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(dataByte, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return Base64Utils.encode(encryptedData);
    }

    /**
     * 私鑰解密
     * 
     * @param data
     * @return*
     * @throws Exception
     */
    private static String decryptByPrivateKey(String data) throws Exception {
        byte[] encryptedData = Base64Utils.decode(data);
        byte[] keyBytes = Base64Utils.decode(PRIVATE_KEY);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM, "BC");
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        // Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

        cipher.init(Cipher.DECRYPT_MODE, privateK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 對數據分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher
                        .doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher
                        .doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return new String(decryptedData);
    }

    /**
     * 獲取模數和密鑰
     * 
     * @return
     */
    public static Map<String, String> getModulusAndKeys() {

        Map<String, String> map = new HashMap<String, String>();

        try {
            InputStream in = RSAUtils.class
                    .getResourceAsStream("/rsa.properties");
            Properties prop = new Properties();
            prop.load(in);

            String modulus = prop.getProperty("modulus");
            String publicKey = prop.getProperty("publicKey");
            String privateKey = prop.getProperty("privateKey");

            in.close();

            map.put("modulus", modulus);
            map.put("publicKey", publicKey);
            map.put("privateKey", privateKey);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return map;
    }

    /**
     * 從字符串中加載公鑰
     * 
     * @param publicKeyStr
     *            公鑰數據字符串
     * @throws Exception
     *             加載公鑰時產生的異常
     */
    public static PublicKey loadPublicKey(String publicKeyStr) throws Exception {
        try {
            byte[] buffer = Base64Utils.decode(publicKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("無此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("公鑰非法");
        } catch (NullPointerException e) {
            throw new Exception("公鑰數據爲空");
        }
    }

    /**
     * 從字符串中加載私鑰<br>
     * 加載時使用的是PKCS8EncodedKeySpec(PKCS#8編碼的Key指令)。
     * 
     * @param privateKeyStr
     * @return
     * @throws Exception
     */
    public static PrivateKey loadPrivateKey(String privateKeyStr)
            throws Exception {
        try {
            byte[] buffer = Base64Utils.decode(privateKeyStr);
            // X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("無此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("私鑰非法");
        } catch (NullPointerException e) {
            throw new Exception("私鑰數據爲空");
        }
    }

    public static String getPrivateKeyStr(PrivateKey privateKey)
            throws Exception {
        return new String(Base64Utils.encode(privateKey.getEncoded()));
    }

    public static String getPublicKeyStr(PublicKey publicKey) throws Exception {
        return new String(Base64Utils.encode(publicKey.getEncoded()));
    }

    public static void main(String[] args) throws Exception {
        getKeys();
    }
}

java的AES加解密算法

import java.util.UUID;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES工具類,密鑰必須是16位字符串
 */
public class AESUtils {

    /**偏移量,必須是16位字符串*/
    private static final String IV_STRING = "16-Bytes--String";

    /**
     * 默認的密鑰
     */
    public static final String DEFAULT_KEY = "1bd83b249a414036";

    /**
     * 產生隨機密鑰(這裏產生密鑰必須是16位)
     */
    public static String generateKey() {
        String key = UUID.randomUUID().toString();
        key = key.replace("-", "").substring(0, 16);// 替換掉-號
        return key;
    }

    /**
     * 加密
     * @param key
     * @param content
     * @return
     */
    public static String encryptData(String key, String content) {
        byte[] encryptedBytes = new byte[0];
        try {
            byte[] byteContent = content.getBytes("UTF-8");
            // 注意,爲了能與 iOS 統一
            // 這裏的 key 不可以使用 KeyGenerator、SecureRandom、SecretKey 生成
            byte[] enCodeFormat = key.getBytes();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
            byte[] initParam = IV_STRING.getBytes();
            IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
            // 指定加密的算法、工作模式和填充方式
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
            encryptedBytes = cipher.doFinal(byteContent);
            // 同樣對加密後數據進行 base64 編碼
            return Base64Utils.encode(encryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     * @param key
     * @param content
     * @return
     */
    public static String decryptData(String key, String content) {
        try {
            // base64 解碼
            byte[] encryptedBytes = Base64Utils.decode(content);
            byte[] enCodeFormat = key.getBytes();
            SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, "AES");
            byte[] initParam = IV_STRING.getBytes();
            IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
            byte[] result = cipher.doFinal(encryptedBytes);
            return new String(result, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String plainText = AESUtils.decryptData("F431E6FF9051DA07", "q8jHYk6LSbwC2K4zmr/wRZo8mlH0VdMzPEcAzQadTCpSrPQ/ZnTmuIvQxiLOnUXu");
        System.out.println("aes加密後: " + plainText);
    }

}

node.js的RSA加解密算法

使用”node-rsa”: “^0.4.2”,模塊

node.js的AES加解密算法 ####AES

AES算法:aes.js

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章