android應(yīng)用中常用的加密方式有三種:MD5,AES,RSA。在進(jìn)行實(shí)際的開(kāi)發(fā)過(guò)程中,一般是幾種加密方式配合使用,這樣加密效果會(huì)更好,被破解的概率會(huì)越小。下面我們就分別講一下三種加密方式的實(shí)現(xiàn)過(guò)程。
一、MD5
MD5本質(zhì)是一種散列函數(shù),用以提供消息的完整性保護(hù)。
特點(diǎn):
1.壓縮性:任意長(zhǎng)度的數(shù)據(jù),算出的MD5值長(zhǎng)度都是固定的;
2.容易計(jì)算:從原數(shù)據(jù)計(jì)算出MD5值很容易;
3.抗修改性:對(duì)原數(shù)據(jù)進(jìn)行任何改動(dòng),哪怕只修改1個(gè)字節(jié),所得到的MD5值都有很大的區(qū)別;
4.強(qiáng)抗碰撞:已知原數(shù)據(jù)和其MD5值,想找到一個(gè)具有相同MD5值的數(shù)據(jù)(及偽造數(shù)據(jù))是非常困難的;
5.不可逆:MD5理論上是不可逆的(但是現(xiàn)在已經(jīng)可以暴力破解了)。
使用場(chǎng)景:
1.驗(yàn)證密碼:只要算法不變,就能和服務(wù)器上的MD5匹配;
2.文件完整性的校驗(yàn):當(dāng)下載一個(gè)文件時(shí),服務(wù)器返回的信息包括這個(gè)文件的md5,在本地下載完畢時(shí)進(jìn)行md5加密,將兩個(gè)md5值進(jìn)行比較,如果一致則說(shuō)明文件完整沒(méi)有丟包現(xiàn)象。
工具類(lèi)代碼:
package comvoice.example.zhangbin.md5codedemo.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
//MD5加密
public class MD5Utils {
//加密字符串
public String getMD5Code(String info){
try {
MessageDigest md5=MessageDigest.getInstance("MD5");
md5.update(info.getBytes("utf-8"));
byte[]encryption=md5.digest();
StringBuffer stringBuffer=new StringBuffer();
for(int i=0;i<encryption.length;i++){
if(Integer.toHexString(0xff &encryption[i]).length()==1){
stringBuffer.append("0").append(Integer.toHexString(0xff&encryption[i]));
}else {
stringBuffer.append(Integer.toHexString(0xff&encryption[i]));
}
}
return stringBuffer.toString();
} catch (Exception e) {
// e.printStackTrace();
return "";
}
}
//加密文件
public static String md5ForFile(File file){
int buffersize = 1024;
FileInputStream fis = null;
DigestInputStream dis = null;
try {
//創(chuàng)建MD5轉(zhuǎn)換器和文件流
MessageDigest messageDigest =MessageDigest.getInstance("MD5");
fis = new FileInputStream(file);
dis = new DigestInputStream(fis,messageDigest);
byte[] buffer = new byte[buffersize];
//DigestInputStream實(shí)際上在流處理文件時(shí)就在內(nèi)部就進(jìn)行了一定的處理
while (dis.read(buffer) > 0);
//通過(guò)DigestInputStream對(duì)象得到一個(gè)最終的MessageDigest對(duì)象。
messageDigest = dis.getMessageDigest();
// 通過(guò)messageDigest拿到結(jié)果,也是字節(jié)數(shù)組,包含16個(gè)元素
byte[] array = messageDigest.digest();
// 同樣,把字節(jié)數(shù)組轉(zhuǎn)換成字符串
StringBuilder hex = new StringBuilder(array.length * 2);
for (byte b : array) {
if ((b & 0xFF) < 0x10){
hex.append("0");
}
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
二、RSA加密
RSA加密算法是一種非對(duì)稱(chēng)加密算法,非對(duì)稱(chēng)加密算法需要兩個(gè)密鑰:公共密鑰和私有密鑰。公鑰和私鑰是配對(duì)的,用公鑰加密的數(shù)據(jù)只有配對(duì)的私鑰才能解密。
RSA對(duì)加密數(shù)據(jù)的長(zhǎng)度有限制,一般為密鑰的長(zhǎng)度值-11,要加密較長(zhǎng)的數(shù)據(jù),可以采用數(shù)據(jù)截取的方法,分段加密。
使用場(chǎng)景:
文件或數(shù)據(jù)在本地使用公鑰或私鑰加密,加密后的數(shù)據(jù)傳送到服務(wù)器,服務(wù)器使用同一套密鑰中的私鑰或者公鑰進(jìn)行解密。
package comvoice.example.zhangbin.md5codedemo.utils;
import android.util.Base64;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
public class RSAUtils {
//構(gòu)建Cipher實(shí)例時(shí)所傳入的的字符串,默認(rèn)為"RSA/NONE/PKCS1Padding"
private static String sTransform = "RSA/NONE/PKCS1Padding";
//進(jìn)行Base64轉(zhuǎn)碼時(shí)的flag設(shè)置,默認(rèn)為Base64.DEFAULT
private static int sBase64Mode = Base64.DEFAULT;
//初始化方法,設(shè)置參數(shù)
public static void init(String transform,int base64Mode){
sTransform = transform;
sBase64Mode = base64Mode;
}
//產(chǎn)生密鑰對(duì)
public static KeyPair generateRSAKeyPair(int keyLength){
KeyPair keyPair=null;
try {
KeyPairGenerator keyPairGenerator=KeyPairGenerator.getInstance("RSA");
//設(shè)置密鑰長(zhǎng)度
keyPairGenerator.initialize(keyLength);
//產(chǎn)生密鑰對(duì)
keyPair=keyPairGenerator.generateKeyPair();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return keyPair;
}
/**
* 加密或解密數(shù)據(jù)的通用的方法,srcData:待處理的數(shù)據(jù);key:公鑰或者私鑰,mode指
* 加密還是解密,值為Cipher.ENCRYPT_MODE或者Cipher.DECRYPT_MODE
*/
public static byte[]processDAta(byte[]srcData, Key key,int mode){
//用來(lái)保存處理的結(jié)果
byte[]resultBytes=null;
//構(gòu)建Cipher對(duì)象,需要傳入一個(gè)字符串,格式必須為"algorithm/mode/padding"或者"algorithm/",意為"算法/加密模式/填充方式"
try {
Cipher cipher=Cipher.getInstance("RSA/NONE/PKCS1Padding");
//初始化Cipher,mode指定是加密還是解密,key為公鑰或密鑰
cipher.init(mode,key);
//處理數(shù)據(jù)
resultBytes=cipher.doFinal(srcData);
} catch (Exception e) {
e.printStackTrace();
}
return resultBytes;
}
//使用公鑰加密數(shù)據(jù),結(jié)果用Base64轉(zhuǎn)碼
public static String encryptDataByPublicKey(byte[]srcData, PublicKey publicKey){
byte[]resultBytes=processDAta(srcData,publicKey,Cipher.ENCRYPT_MODE);
return Base64.encodeToString(resultBytes,sBase64Mode);
}
//使用私鑰解密,結(jié)果用Base64轉(zhuǎn)碼
public static byte[]decryptDataByPrivate(String encryptedData, PrivateKey privateKey){
byte[]bytes=Base64.decode(encryptedData,sBase64Mode);
return processDAta(bytes,privateKey,Cipher.DECRYPT_MODE);
}
//使用私鑰解密,返回解碼數(shù)據(jù)
public static String decryptToStrByPrivate(String encryptedData,PrivateKey privateKey){
return new String(decryptDataByPrivate(encryptedData,privateKey));
}
}
三、AES加密
AES加密是一種高級(jí)加密標(biāo)準(zhǔn),是一種區(qū)塊加密標(biāo)準(zhǔn)。它是一個(gè)對(duì)稱(chēng)密碼,就是說(shuō)加密和解密用相同的密鑰。WPA/WPA2經(jīng)常用的加密方式就是AES加密算法。
示意圖:

工具類(lèi)代碼:
package comvoice.example.zhangbin.md5codedemo.utils;
import java.io.UnsupportedEncodingException;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class AESUtils3 {
/* 算法/模式/填充 */
private static final String CipherMode = "AES/ECB/PKCS5Padding";
/* 創(chuàng)建密鑰 */
private static SecretKeySpec createKey(String password) {
byte[] data = null;
if (password == null) {
password = "";
}
StringBuffer sb = new StringBuffer(32);
sb.append(password);
while (sb.length() < 32) {
sb.append("0");
}
if (sb.length() > 32) {
sb.setLength(32);
}
try {
data = sb.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return new SecretKeySpec(data, "AES");
}
/* 加密字節(jié)數(shù)據(jù) */
public static byte[] encrypt(byte[] content, String password) {
try {
SecretKeySpec key = createKey(password);
System.out.println(key);
Cipher cipher = Cipher.getInstance(CipherMode);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/*加密(結(jié)果為16進(jìn)制字符串) */
public static String encrypt(String content, String password) {
byte[] data = null;
try {
data = content.getBytes("UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
data = encrypt(data, password);
String result = byte2hex(data);
return result;
}
/*解密字節(jié)數(shù)組*/
public static byte[] decrypt(byte[] content, String password) {
try {
SecretKeySpec key = createKey(password);
Cipher cipher = Cipher.getInstance(CipherMode);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/*解密16進(jìn)制的字符串為字符串 */
public static String decrypt(String content, String password) {
byte[] data = null;
try {
data = hex2byte(content);
} catch (Exception e) {
e.printStackTrace();
}
data = decrypt(data, password);
if (data == null) return null;
String result = null;
try {
result = new String(data, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
/*字節(jié)數(shù)組轉(zhuǎn)成16進(jìn)制字符串 */
public static String byte2hex(byte[] b) { // 一個(gè)字節(jié)的數(shù),
StringBuffer sb = new StringBuffer(b.length * 2);
String tmp = "";
for (int n = 0; n < b.length; n++) {
// 整數(shù)轉(zhuǎn)成十六進(jìn)制表示
tmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (tmp.length() == 1) {
sb.append("0");
}
sb.append(tmp);
}
return sb.toString().toUpperCase(); // 轉(zhuǎn)成大寫(xiě)
}
/*將hex字符串轉(zhuǎn)換成字節(jié)數(shù)組 */
private static byte[] hex2byte(String inputString) {
if (inputString == null || inputString.length() < 2) {
return new byte[0];
}
inputString = inputString.toLowerCase();
int l = inputString.length() / 2;
byte[] result = new byte[l];
for (int i = 0; i < l; ++i) {
String tmp = inputString.substring(2 * i, 2 * i + 2);
result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);
}
return result;
}
}