1.RSA介紹
RSA是一種常用的非對稱加密算法民效,所謂非對稱加密是指使用一對密鑰(公鑰和私鑰)進(jìn)行加密和解密,公鑰人人都可以獲得涛救,用于加密數(shù)據(jù)畏邢,私鑰保存在服務(wù)器中,用于解密數(shù)據(jù)检吆。
2. 在Android中使用RSA
Java中已內(nèi)置RSA支持舒萎,示例代碼如下:
2.1 從字符串加載公鑰
public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
//通過X509編碼的Key指令獲得公鑰對象
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(android.util.Base64.decode(publicKey.getBytes(), android.util.Base64.URL_SAFE));
RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
return key;
}
這里是用安卓自帶的Base64加密解密。必須注意加密解密的第二個參數(shù)必須選成android.util.Base64.URL_SAFE蹭沛。Default會報(bào)錯 公鑰非法臂寝。
2.2 RSA加密數(shù)據(jù)
public static String publicEncrypt(String data, RSAPublicKey publicKey) {
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return android.util.Base64.encodeToString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength()), android.util.Base64.URL_SAFE);
} catch (Exception e) {
throw new RuntimeException("加密字符串[" + data + "]時(shí)遇到異常", e);
}
}
private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) {
int maxBlock = 0;
if (opmode == Cipher.DECRYPT_MODE) {
maxBlock = keySize / 8;
} else {
maxBlock = keySize / 8 - 11;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] buff;
int i = 0;
try {
while (datas.length > offSet) {
if (datas.length - offSet > maxBlock) {
buff = cipher.doFinal(datas, offSet, maxBlock);
} else {
buff = cipher.doFinal(datas, offSet, datas.length - offSet);
}
out.write(buff, 0, buff.length);
i++;
offSet = i * maxBlock;
}
} catch (Exception e) {
throw new RuntimeException("加解密閥值為[" + maxBlock + "]的數(shù)據(jù)時(shí)發(fā)生異常", e);
}
byte[] resultDatas = out.toByteArray();
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return resultDatas;
}
這里注意用于加密時(shí)的Cipher章鲤,創(chuàng)建的參數(shù)不要寫成只帶”RSA”的:
Cipher cipher = Cipher.getInstance("RSA");
應(yīng)為這種的
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
最后不要忘了將參數(shù)用Base64編碼
param = URLEncoder.encode((String)param,"utf-8");
3.發(fā)送數(shù)據(jù)到后臺
最后只需要講用戶名和加密的密碼通過okhttp傳到后臺即可。