App安全登入之密碼、通訊加密方法(MD5,Base64,RSA,AES)
阿新 • • 發佈:2018-12-12
今天研究了一下關於登入密碼加密的問題,下面來說說實現。
一、RSA非對稱加密:
具體流程如下:擷取自http://blog.csdn.net/m372897500/article/details/50905017
- 客戶端向伺服器第一次發起登入請求(不傳輸使用者名稱和密碼)。
- 伺服器利用RSA演算法產生一對公鑰和私鑰。並保留私鑰, 將公鑰傳送給客戶端。
- 客戶端收到公鑰後, 加密使用者密碼, 向伺服器發起第二次登入請求(傳輸使用者名稱和加密後的密碼)。
- 伺服器利用保留的私鑰對密文進行解密,得到真正的密碼。
/** * 公鑰加密 * * @param data * @param publicKey * @return * @throws Exception */ public static String encryptByPublicKey(String data, RSAPublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); // 模長 int key_len = publicKey.getModulus().bitLength() / 8; // 加密資料長度 <= 模長-11 String[] datas = splitString(data, key_len - 11); String mi = ""; //如果明文長度大於模長-11則要分組加密 for (String s : datas) { mi += bcd2Str(cipher.doFinal(s.getBytes())); } return mi; } /** * 私鑰解密 * * @param data * @param privateKey * @return * @throws Exception */ public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); //模長 int key_len = privateKey.getModulus().bitLength() / 8; byte[] bytes = data.getBytes(); byte[] bcd = ASCII_To_BCD(bytes, bytes.length); System.err.println(bcd.length); //如果密文長度大於模長則要分組解密 String ming = ""; byte[][] arrays = splitArray(bcd, key_len); for(byte[] arr : arrays){ ming += new String(cipher.doFinal(arr)); } return ming; } public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) { byte[] bcd = new byte[asc_len / 2]; int j = 0; for (int i = 0; i < (asc_len + 1) / 2; i++) { bcd[i] = asc_to_bcd(ascii[j++]); bcd[i] = (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4)); } return bcd; } public static byte asc_to_bcd(byte asc) { byte bcd; if ((asc >= '0') && (asc <= '9')) bcd = (byte) (asc - '0'); else if ((asc >= 'A') && (asc <= 'F')) bcd = (byte) (asc - 'A' + 10); else if ((asc >= 'a') && (asc <= 'f')) bcd = (byte) (asc - 'a' + 10); else bcd = (byte) (asc - 48); return bcd; } /** * BCD轉字串 */ public static String bcd2Str(byte[] bytes) { char temp[] = new char[bytes.length * 2], val; for (int i = 0; i < bytes.length; i++) { val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f); temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0'); val = (char) (bytes[i] & 0x0f); temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0'); } return new String(temp); } /** * 拆分字串 */ public static String[] splitString(String string, int len) { int x = string.length() / len; int y = string.length() % len; int z = 0; if (y != 0) { z = 1; } String[] strings = new String[x + z]; String str = ""; for (int i=0; i<x+z; i++) { if (i==x+z-1 && y!=0) { str = string.substring(i*len, i*len+y); }else{ str = string.substring(i*len, i*len+len); } strings[i] = str; } return strings; } /** *拆分陣列 */ public static byte[][] splitArray(byte[] data,int len){ int x = data.length / len; int y = data.length % len; int z = 0; if(y!=0){ z = 1; } byte[][] arrays = new byte[x+z][]; byte[] arr; for(int i=0; i<x+z; i++){ arr = new byte[len]; if(i==x+z-1 && y!=0){ System.arraycopy(data, i*len, arr, 0, y); }else{ System.arraycopy(data, i*len, arr, 0, len); } arrays[i] = arr; } return arrays; }
還有就是關於密文的問題,如果你想要 每次生成不一樣的密文,生成祕鑰的時候使用:
RSA/None/PKCS1Padding
想要一樣的密文,生成祕鑰的時候使用:
RSA/NONE/NoPadding
參考文章:
http://blog.csdn.net/defonds/article/details/42775183
二、MD5加鹽加密:沒看錯,是加鹽,有興趣去度娘看看介紹,現在說說實現,例如密碼為123456,此處我們規定鹽值為其hashcode,即要加密的字串為
方法如下:password + password.hashCode()
/**
* 獲取十六進位制字串形式的MD5
*/
public static String toMD5Code(byte[] bytes) {
StringBuffer sb = new StringBuffer();
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset();
md5.update(bytes);
byte[] after = md5.digest();
for (int i = 0; i < after.length; i++) {
// int num = after[i] & 0xff;
String hex = Integer.toHexString(0xff & after[i]);
if (hex.length() == 1)
hex = "0" + hex;
sb.append(hex);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return sb.toString();
}
使用的時候注意,需要規範為UTF-8
String password = "123456";
String tempPwd = password + password.hashCode();
try {
passwordMD5 = toMD5Code(tempPwd.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
還是很簡單的,只要加密的密文和伺服器加密得到結果一致,驗證就會通過,注意兩邊一定要統一規則即可。注意MD5加密是不可逆的。
三、Base64加密:擷取自http://www.tuicool.com/articles/EBBBni
// 加密傳入的資料是byte型別的,並非使用decode方法將原始資料轉二進位制,String型別的資料 使用 str.getBytes()即可
String str = "Hello!";
// 在這裡使用的是encode方式,返回的是byte型別加密資料,可使用new String轉為String型別
String strBase64 = new String(Base64.encode(str.getBytes(), Base64.DEFAULT));
Log.i("Test", "encode >>>" + strBase64);
// 這裡 encodeToString 則直接將返回String型別的加密資料
String enToStr = Base64.encodeToString(str.getBytes(), Base64.DEFAULT);
Log.i("Test", "encodeToString >>> " + enToStr);
// 對base64加密後的資料進行解密
Log.i("Test", "decode >>>" + new String(Base64.decode(strBase64.getBytes(), Base64.DEFAULT)));
注意下base64的問題,如下連結 http://www.360doc.com/content/11/0602/14/1542811_121186311.shtml
4.AES256加密:這裡使用的是傳入16位的字串作為祕鑰。
public class AES256EncryptionUtil {
public static final String TAG = AES256EncryptionUtil.class.getSimpleName();
public static final String ALGORITHM = "AES/ECB/PKCS7Padding";
private static String mPassword = ""; //祕鑰字串
/**
* 一次性設定password,後面無需再次設定
* @param password
*/
public static void setPassword(String password){
mPassword = password;
}
/**
* 生成key
* @param password
* @return
* @throws Exception
*/
private static byte[] getKeyByte(String password) throws Exception {
byte[] seed = new byte[24];
if(!TextUtils.isEmpty(password)) {
seed = password.getBytes();
}
return seed;
}
/**
* 加密
* @param data
* @return
*/
public static String encrypt(String data) throws Exception{
String string = "";
byte[] keyByte = getKeyByte(mPassword);
SecretKeySpec keySpec = new SecretKeySpec(keyByte,"AES"); //生成加密解密需要的Key
byte[] byteContent = data.getBytes("utf-8");
Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] result = cipher.doFinal(byteContent);
string = parseByte2HexStr(result); //轉成String
return string;
}
/**
* 解密
* @param data
* @return
*/
public static String decrypt(String data) throws Exception{
String string = "";
byte[] keyByte = getKeyByte(mPassword);
byte[] byteContent = parseHexStr2Byte(data); //轉成byte
Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
SecretKeySpec keySpec = new SecretKeySpec(keyByte,"AES"); //生成加密解密需要的Key
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] decoded = cipher.doFinal(byteContent);
string = new String(decoded);
return string;
}
/**
* 轉化為String
* @param buf
* @return
*/
private 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進位制轉換為二進位制
* @param hexStr
* @return
*/
private 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;
}
AES上面的加密是根據定義的password生成的,要說為了安全起見,可以使用隨機源來生成,可以改成這樣:
/**
* 加密 - 隨機源
* @param content
* @return
*/
public static byte[] encrypt(String content) {
try {
//"AES":請求的金鑰演算法的標準名稱
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
sr.setSeed(tohash256Deal(mPassword));
//256:金鑰生成引數;securerandom:金鑰生成器的隨機源
SecureRandom securerandom = new SecureRandom(tohash256Deal(mPassword));
kgen.init(256, sr);
//生成祕密(對稱)金鑰
SecretKey secretKey = kgen.generateKey();
//返回基本編碼格式的金鑰
byte[] enCodeFormat = secretKey.getEncoded();
//根據給定的位元組陣列構造一個金鑰。enCodeFormat:金鑰內容;"AES":與給定的金鑰內容相關聯的金鑰演算法的名稱
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
//建立一個實現指定轉換的 Cipher物件,該轉換由指定的提供程式提供。
//"AES/ECB/PKCS7Padding":轉換的名稱;"BC":提供程式的名稱
Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] byteContent = content.getBytes("utf-8");
byte[] cryptograph = cipher.doFinal(byteContent);
return Base64.encode(cryptograph,Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
LogHelper.e("lenita","e en"+e.toString());
}
return null;
}
/**
* 解密 - 隨機源
* @param cryptograph
* @return
*/
public static String decrypt(byte[] cryptograph) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
sr.setSeed(tohash256Deal(mPassword));
// SecureRandom securerandom = new SecureRandom(tohash256Deal(mPassword));
kgen.init(256, sr);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] content = cipher.doFinal(Base64.decode(cryptograph,Base64.DEFAULT));
return new String(content);
} catch (Exception e) {
e.printStackTrace();
LogHelper.e("lenita","e de ="+e.toString());
}
return null;
}
上面是參考了很多資料得到的答案,最重要的就是隨機源函式,如果直接new會丟擲異常,所以我們要:
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto"); sr.setSeed(tohash256Deal(mPassword));