個(gè)人博客: http://zhangsunyucong.top
背景
為什么想寫(xiě)這一篇文章呢?做android的開(kāi)發(fā)也有兩年的時(shí)間了吞杭,就想把以前學(xué)到的一些東西記錄下來(lái)盏浇。于是首先就想在github.com上開(kāi)一個(gè)項(xiàng)目MVPDemo,將一些自己認(rèn)為比較好的知識(shí)點(diǎn)都串聯(lián)起來(lái)。
主要目的:
1芽狗、初步認(rèn)識(shí)和使用MVP绢掰、dagger2和rxJava2
2、使用對(duì)稱和非對(duì)稱加密加強(qiáng)前端與后臺(tái)的安全機(jī)制
3童擎、前后臺(tái)的socket交互實(shí)現(xiàn)
其中3滴劲、中的socket實(shí)現(xiàn),我專門(mén)建了一個(gè)github倉(cāng)庫(kù)NodeTestDemo顾复,這個(gè)倉(cāng)庫(kù)不僅僅實(shí)現(xiàn)了前端的普通接口班挖,還提供了一個(gè)socket服務(wù)。
android端實(shí)現(xiàn)
1芯砸、采用了MVP架構(gòu)萧芙,使用dagger2對(duì)象依賴注入框架解耦MVP的各個(gè)組件
2给梅、界面采用了autolayout進(jìn)行兼容適配,UI尺寸標(biāo)準(zhǔn)是720*1080.頁(yè)面效果仿微信双揪。
3动羽、rxjava2、rxlifecycle2渔期,rxbinding2等Rx系列的初級(jí)使用
4运吓、與后臺(tái)服務(wù)器接口交互使用了retrofit2,交互的數(shù)據(jù)格式為json
5擎场、自定義retrofit2的ConverterFactory和Interceptor實(shí)現(xiàn)統(tǒng)一加解密交互的數(shù)據(jù)流程
6羽德、事件總線eventbus3、控件注入框架butterknife迅办、GreenDao3對(duì)象關(guān)系映射數(shù)據(jù)庫(kù)的使用
7、socket的前端簡(jiǎn)單實(shí)現(xiàn)
8浴鸿、PDF文檔庫(kù)android-pdf-viewer的使用
9瞒滴、使用jsoup解析csdn網(wǎng)站的html頁(yè)面獲取博主的博客信息
10间螟、接入bugly》撸可以使用budly跟蹤異常奔潰信息和bugly基于tinker的熱修復(fù)。
11峭沦、接入騰訊X5內(nèi)核瀏覽器服務(wù)代替原生的webview
12贾虽、頁(yè)面路由Arouter的初步使用
13、app端出現(xiàn)異常吼鱼,在殺死應(yīng)用前蓬豁,啟動(dòng)異常頁(yè)面并允許用戶點(diǎn)擊重啟
14、Cmake的使用菇肃〉胤啵可以將敏感或者需要保密的數(shù)據(jù)使用jni保護(hù),如第三方開(kāi)發(fā)者平臺(tái)的appid等
后臺(tái)安全數(shù)據(jù)安全交互機(jī)制
1琐谤、后臺(tái)服務(wù)器使用了leancloud和nodejs搭建蟆技。nodejs服務(wù)器源碼
2、android端的數(shù)據(jù)加密流程:
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'));
將服務(wù)器公鑰分發(fā)給前端斗忌,私鑰保存好放到服務(wù)器端质礼。
(2)后臺(tái)為一個(gè)前端生成一對(duì)AppId和AppScrect。前后端各保存一份织阳,建議在android端將它們放到JNI中保護(hù)眶蕉。
AppId用于在前端參與參數(shù)簽名,AppScrect用于服務(wù)器返回?cái)?shù)據(jù)的AES加密密鑰陈哑。
(3)在Android端妻坝,應(yīng)用每次啟動(dòng)時(shí)生成用于參數(shù)AES加密的密鑰伸眶。這樣可以使AES加密密鑰是動(dòng)態(tài)變化的。
(4)刽宪、將請(qǐng)求參數(shù)按照key的自然順序進(jìn)行排序厘贼,構(gòu)造源串。然后在源串追加AppId得到簽名字符串signString圣拄,用AES密鑰加密signString嘴秸,得到簽名sign。
/** 按照key的自然順序進(jìn)行排序庇谆,并返回 */
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;
}
/** 構(gòu)造源串 */
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();
}
/** 構(gòu)造源串 */
public String getSign(Map<String, Object> map) {
String sign = getSignParamsString(map) + "appId=" + AppConfig.AppId;
return sign;
}
說(shuō)明:如果要求服務(wù)器只允許一定時(shí)間范圍內(nèi)的請(qǐng)求岳掐,可以在getSignParamsString方法中添加時(shí)間戳作為接口簽名的一部分,防止重放攻擊饭耳。
(4)將簽名sign和簽名的字符串signString進(jìn)行AES加密串述,將AES加密密鑰用服務(wù)器公鑰加密,后傳給服務(wù)器.
RSAUtils.encryptByServerPublicKey(App.getApp().getAESKey());
AESUtils.encryptData(App.getApp().getAESKey(), signString);
AESUtils.encryptData(App.getApp().getAESKey(), sign);
signString為什么在前端生成呢寞肖?
為了在服務(wù)器重新生成簽名字符串時(shí)纲酗,防止由于前后端開(kāi)發(fā)語(yǔ)言的不同而產(chǎn)生不一致。
(5)服務(wù)器解密
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吮螺、取出參數(shù),用服務(wù)器RSA私鑰解密AES密鑰
b帕翻、用AES密鑰解密簽名和簽名字符串
c鸠补、簽名字符串追加分發(fā)給前端的AppScrect后,用a熊咽、得到的AES加密重新生產(chǎn)簽名莫鸭。
d、對(duì)比前端傳來(lái)的簽名和重新生成的簽名是否一致横殴。
(5)根據(jù)AppId找到對(duì)應(yīng)的AppScrect被因,用AppScrect對(duì)服務(wù)器返回的結(jié)果進(jìn)行AES加密。
注意:確保前后端在不同開(kāi)發(fā)語(yǔ)言情況下衫仑,AES算法的結(jié)果是一樣的梨与。
后面會(huì)給出我用到的java和nodejs版本的RSA和AES加解密算法源碼。
(6)前端從JNI中取出AppScrect對(duì)響應(yīng)結(jié)果進(jìn)行解密即可文狱。
前后端加解密算法源碼
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 = "填寫(xiě)自己的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);
}
/**
* 使用模和指數(shù)生成RSA公鑰
* 注意:【此代碼用了默認(rèn)補(bǔ)位方式粥鞋,為RSA/None/PKCS1Padding,不同JDK默認(rèn)的補(bǔ)位方式可能不同瞄崇,如Android默認(rèn)是RSA
* /None/NoPadding】
*
* @param modulus
* 模
* @param exponent
* 公鑰指數(shù)
* @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;
}
}
/**
* 使用模和指數(shù)生成RSA私鑰
* 注意:【此代碼用了默認(rèn)補(bǔ)位方式呻粹,為RSA/None/PKCS1Padding壕曼,不同JDK默認(rèn)的補(bǔ)位方式可能不同,如Android默認(rèn)是RSA
* /None/NoPadding】
*
* @param modulus
* 模
* @param exponent
* 指數(shù)
* @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);
// 對(duì)數(shù)據(jù)加密
// 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;
// 對(duì)數(shù)據(jù)分段加密
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;
// 對(duì)數(shù)據(jù)分段解密
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);
}
/**
* 獲取模數(shù)和密鑰
*
* @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
* 公鑰數(shù)據(jù)字符串
* @throws Exception
* 加載公鑰時(shí)產(chǎn)生的異常
*/
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("無(wú)此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("公鑰非法");
} catch (NullPointerException e) {
throw new Exception("公鑰數(shù)據(jù)為空");
}
}
/**
* 從字符串中加載私鑰<br>
* 加載時(shí)使用的是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("無(wú)此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("私鑰非法");
} catch (NullPointerException e) {
throw new Exception("私鑰數(shù)據(jù)為空");
}
}
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";
/**
* 默認(rèn)的密鑰
*/
public static final String DEFAULT_KEY = "1bd83b249a414036";
/**
* 產(chǎn)生隨機(jī)密鑰(這里產(chǎn)生密鑰必須是16位)
*/
public static String generateKey() {
String key = UUID.randomUUID().toString();
key = key.replace("-", "").substring(0, 16);// 替換掉-號(hào)
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 統(tǒng)一
// 這里的 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);
// 同樣對(duì)加密后數(shù)據(jù)進(jìn)行 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.js
進(jìn)一步改進(jìn)过咬,關(guān)注:
JIN的簽名驗(yàn)證和