欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android常用的數(shù)據(jù)加密方式代碼詳解

 更新時間:2017年11月22日 11:33:09   作者:廢墟的樹  
這篇文章主要介紹了Android常用的數(shù)據(jù)加密方式代碼詳解,介紹了四種常見加密算法及代碼示例,具有一定參考價值,需要的朋友可以了解下。

前言

Android 很多場合需要使用到數(shù)據(jù)加密,比如:本地登錄密碼加密,網(wǎng)絡傳輸數(shù)據(jù)加密,等。在android 中一般的加密方式有如下:

亦或加密 
AES加密 
RSA非對稱加密 
MD5加密算法 

當然還有其他的方式,這里暫且介紹以上四種加密算法的使用方式。

亦或加密算法

什么是亦或加密?

亦或加密是對某個字節(jié)進行亦或運算,比如字節(jié) A^K = V,這是加密過程;
當你把 V^K得到的結(jié)果就是A,也就是 V^K = A,這是一個反向操作過程,解密過程。

亦或操作效率很高,當然亦或加密也是比較簡單的加密方式,且亦或操作不會增加空間,源數(shù)據(jù)多大亦或加密后數(shù)據(jù)依然是多大。

示例代碼如下:

/**
   * 亦或加解密,適合對整個文件的部分加密,比如文件頭部,和尾部
   * 對file文件頭部和尾部加密,適合zip壓縮包加密
   *
   * @param source 需要加密的文件
   * @param det  加密后保存文件名
   * @param key  加密key
   */
public static void encryptionFile(File source, File det, int key) {
	FileInputStream fis = null;
	FileOutputStream fos = null;
	try {
		fis = new FileInputStream(source);
		fos = new FileOutputStream(det);
		int size = 2048;
		byte buff[] = new byte[size];
		int count = fis.read(buff);
		/**zip包頭部加密*/
		for (int i = 0; i < count; i++) {
			fos.write(buff[i] ^ key);
		}
		while (true) {
			count = fis.read(buff);
			/**zip包結(jié)尾加密*/
			if (count < size) {
				for (int j = 0; j < count; j++) {
					fos.write(buff[j] ^ key);
				}
				break;
			}
			fos.write(buff, 0, count);
		}
		fos.flush();
	}
	catch (IOException e) {
		e.printStackTrace();
	}
	finally {
		try {
			if (fis != null) {
				fis.close();
			}
			if (fos != null) {
				fos.close();
			}
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
}
/**
   * 亦或加解密,適合對整個文件加密
   *
   * @param source 需要加密文件的路徑
   * @param det  加密后保存文件的路徑
   * @param key  加密秘鑰key
   */
private static void encryptionFile(String source, String det, int key) {
	FileInputStream fis = null;
	FileOutputStream fos = null;
	try {
		fis = new FileInputStream(source);
		fos = new FileOutputStream(det);
		int read;
		while ((read = fis.read()) != -1) {
			fos.write(read ^ key);
		}
		fos.flush();
	}
	catch (IOException e) {
		e.printStackTrace();
	}
	finally {
		try {
			if (fis != null) {
				fis.close();
			}
			if (fos != null) {
				fos.close();
			}
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
}

可以對文件的部分加密,比如zip壓縮包,就可以對頭部和尾部加密,因為zip頭部和尾部藏有文件壓縮相關(guān)的信息,所有,我們只對頭部和尾部采用亦或加密算法,即可對整個zip文件加密,當你不解密試圖加壓是會失敗的。
也可以對整個文件進行亦或加密算法,所以你解密的時候其實是一個逆向的過程,使用同樣的方法同樣的key即可對加密的文件解密。當然以后加密的安全性可想而知,不是很安全,所以,亦或加密算法一般使用在不太重要的場景。由于亦或算法很快,所以加密速度也很快。

AES加密加密算法

什么是AES 加密

AES 對稱加密

高級加密標準(英語:Advanced Encryption Standard,縮寫:AES),在密碼學中又稱Rijndael加密法,是美國聯(lián)邦政府采用的一種區(qū)塊加密標準。 這個標準用來替代原先的DES,已經(jīng)被多方分析且廣為全世界所使用。

Android 中的AES 加密 秘鑰 key 必須為16/24/32位字節(jié),否則拋異常

示例代碼:

private static final String TAG = "EncryptUtils";
private final static int MODE_ENCRYPTION = 1;
private final static int MODE_DECRYPTION = 2;
private final static String AES_KEY = "xjp_12345!^-=42#";
//AES 秘鑰key,必須為16位
private static byte[] encryption(int mode, byte[] content, String pwd) {
	try {
		Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
		//AES加密模式,CFB 加密模式
		SecretKeySpec keySpec = new SecretKeySpec(pwd.getBytes("UTF-8"), "AES");
		//AES加密方式
		IvParameterSpec ivSpec = new IvParameterSpec(pwd.getBytes("UTF-8"));
		cipher.init(mode == MODE_ENCRYPTION ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, keySpec, ivSpec);
		return cipher.doFinal(content);
	}
	catch (NoSuchAlgorithmException | NoSuchPaddingException |
	        InvalidKeyException | IllegalBlockSizeException |
	        BadPaddingException | InvalidAlgorithmParameterException e) {
		e.printStackTrace();
		Log.e(TAG, "encryption failed... err: " + e.getMessage());
	}
	catch (Exception e) {
		e.printStackTrace();
		Log.e(TAG, "encryption1 failed ...err: " + e.getMessage());
	}
	return null;
}
/**
   * AES 加密
   *
   * @param source 需要加密的文件路徑
   * @param dest  加密后的文件路徑
   */
public static void encryptByAES(String source, String dest) {
	encryptByAES(MODE_ENCRYPTION, source, dest);
}
public static void encryptByAES(int mode, String source, String dest) {
	Log.i(TAG, "start===encryptByAES");
	FileInputStream fis = null;
	FileOutputStream fos = null;
	try {
		fis = new FileInputStream(source);
		fos = new FileOutputStream(dest);
		int size = 2048;
		byte buff[] = new byte[size];
		byte buffResult[];
		while ((fis.read(buff)) != -1) {
			buffResult = encryption(mode, buff, AES_KEY);
			if (buffResult != null) {
				fos.write(buffResult);
			}
		}
		Log.i(TAG, "end===encryptByAES");
	}
	catch (IOException e) {
		e.printStackTrace();
		Log.e(TAG, "encryptByAES failed err: " + e.getMessage());
	}
	finally {
		try {
			if (fis != null) {
				fis.close();
			}
			if (fos != null) {
				fos.close();
			}
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
}
/**
   * AES 解密
   *
   * @param source 需要解密的文件路徑
   * @param dest  解密后保存的文件路徑
   */
public static void decryptByAES(String source, String dest) {
	encryptByAES(MODE_DECRYPTION, source, dest);
}

AES對稱加密,加解密相比于亦或加密還是有點復雜的,安全性也比亦或加密高,AES加密不是絕對的安全。

RSA非對稱加密

什么是Rsa加密?

RSA算法是最流行的公鑰密碼算法,使用長度可以變化的密鑰。RSA是第一個既能用于數(shù)據(jù)加密也能用于數(shù)字簽名的算法。

RSA的安全性依賴于大數(shù)分解,小于1024位的N已經(jīng)被證明是不安全的,而且由于RSA算法進行的都是大數(shù)計算,使得RSA最快的情況也比DES慢上倍,這是RSA最大的缺陷,因此通常只能用于加密少量數(shù)據(jù)或者加密密鑰,但RSA仍然不失為一種高強度的算法。

代碼示例:

/**************************************************
   * 1.什么是RSA 非對稱加密?
   * <p>
   * 2.
   *************************************************/
private final static String RSA = "RSA";
//加密方式 RSA
public final static int DEFAULT_KEY_SIZE = 1024;
private final static int DECRYPT_LEN = DEFAULT_KEY_SIZE / 8;
//解密長度
private final static int ENCRYPT_LEN = DECRYPT_LEN - 11;
//加密長度
private static final String DES_CBC_PKCS5PAD = "DES/CBC/PKCS5Padding";
//加密填充方式
private final static int MODE_PRIVATE = 1;
//私鑰加密
private final static int MODE_PUBLIC = 2;
//公鑰加密
/**
   * 隨機生成RSA密鑰對,包括PublicKey,PrivateKey
   *
   * @param keyLength 秘鑰長度,范圍是 512~2048,一般是1024
   * @return KeyPair
   */
public static KeyPair generateRSAKeyPair(int keyLength) {
	try {
		KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
		kpg.initialize(keyLength);
		return kpg.genKeyPair();
	}
	catch (NoSuchAlgorithmException e) {
		e.printStackTrace();
		return null;
	}
}
/**
   * 得到私鑰
   *
   * @return PrivateKey
   * @throws NoSuchAlgorithmException
   * @throws InvalidKeySpecException
   */
public static PrivateKey getPrivateKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
	byte[] privateKey = Base64.decode(key, Base64.URL_SAFE);
	PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
	KeyFactory kf = KeyFactory.getInstance(RSA);
	return kf.generatePrivate(keySpec);
}
/**
   * 得到公鑰
   *
   * @param key
   * @return PublicKey
   * @throws NoSuchAlgorithmException
   * @throws InvalidKeySpecException
   */
public static PublicKey getPublicKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
	byte[] publicKey = Base64.decode(key, Base64.URL_SAFE);
	X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
	KeyFactory kf = KeyFactory.getInstance(RSA);
	return kf.generatePublic(keySpec);
}
/**
   * 私鑰加密
   *
   * @param data
   * @param key
   * @return
   * @throws Exception
   */
public static byte[] encryptByRSA(byte[] data, Key key) throws Exception {
	// 數(shù)據(jù)加密
	Cipher cipher = Cipher.getInstance(RSA);
	cipher.init(Cipher.ENCRYPT_MODE, key);
	return cipher.doFinal(data);
}
/**
   * 公鑰解密
   *
   * @param data 待解密數(shù)據(jù)
   * @param key 密鑰
   * @return byte[] 解密數(shù)據(jù)
   */
public static byte[] decryptByRSA(byte[] data, Key key) throws Exception {
	// 數(shù)據(jù)解密
	Cipher cipher = Cipher.getInstance(RSA);
	cipher.init(Cipher.DECRYPT_MODE, key);
	return cipher.doFinal(data);
}
public static void encryptByRSA(String source, String dest, Key key) {
	rasEncrypt(MODE_ENCRYPTION, source, dest, key);
}
public static void decryptByRSA(String source, String dest, Key key) {
	rasEncrypt(MODE_DECRYPTION, source, dest, key);
}
public static void rasEncrypt(int mode, String source, String dest, Key key) {
	Log.i(TAG, "start===encryptByRSA mode--->>" + mode);
	FileInputStream fis = null;
	FileOutputStream fos = null;
	try {
		fis = new FileInputStream(source);
		fos = new FileOutputStream(dest);
		int size = mode == MODE_ENCRYPTION ? ENCRYPT_LEN : DECRYPT_LEN;
		byte buff[] = new byte[size];
		byte buffResult[];
		while ((fis.read(buff)) != -1) {
			buffResult = mode == MODE_ENCRYPTION ? encryptByRSA(buff, key) : decryptByRSA(buff, key);
			if (buffResult != null) {
				fos.write(buffResult);
			}
		}
		Log.i(TAG, "end===encryptByRSA");
	}
	catch (IOException e) {
		e.printStackTrace();
		Log.e(TAG, "encryptByRSA failed err: " + e.getMessage());
	}
	catch (Exception e) {
		e.printStackTrace();
	}
	finally {
		try {
			if (fis != null) {
				fis.close();
			}
			if (fos != null) {
				fos.close();
			}
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
}

MD5加密算法:

public String getMD5Code(String info) {
	try {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		md5.update(info.getBytes("UTF-8"));
		byte[] encryption = md5.digest();
		StringBuffer strBuf = new StringBuffer();
		for (int i = 0; i < encryption.length; i++) {
			if (Integer.toHexString(0xff & encryption[i]).length() == 1) {
				strBuf.append("0").append( 
				            Integer.toHexString(0xff & encryption[i]));
			} else {
				strBuf.append(Integer.toHexString(0xff & encryption[i]));
			}
		}
		return strBuf.toString();
	}
	catch (Exception e) {
		// TODO: handle exception 
		return "";
	}
}

1.AES公鑰加密,私鑰解密
2.AES加密耗時
3.AES加密后數(shù)據(jù)會變大

總結(jié)

以上就是本文關(guān)于Android常用的數(shù)據(jù)加密方式代碼詳解的全部內(nèi)容,希望對大家有所幫助。如有不足之處,歡迎留言指出。感謝朋友們對本站的支持。

相關(guān)文章

  • android webview中使用Java調(diào)用JavaScript方法并獲取返回值

    android webview中使用Java調(diào)用JavaScript方法并獲取返回值

    這篇文章主要介紹了android webview中使用Java調(diào)用JavaScript方法并獲取返回值,本文直接給出代碼示例,需要的朋友可以參考下
    2015-03-03
  • Android中的緩存與文件存儲目錄詳解

    Android中的緩存與文件存儲目錄詳解

    在Android應用開發(fā)中,合理管理應用的數(shù)據(jù)存儲至關(guān)重要,本文將詳細介紹cacheDir, filesDir, externalCacheDir, 以及getExternalFilesDir(Environment.DIRECTORY_PICTURES)這幾個目錄的用途和區(qū)別,感興趣的朋友跟隨小編一起看看吧
    2024-07-07
  • Android 換膚技術(shù)資料整理

    Android 換膚技術(shù)資料整理

    這篇文章主要介紹了 Android 換膚技術(shù)總結(jié)的相關(guān)資料,需要的朋友可以參考下
    2017-03-03
  • Android開發(fā)之彈出軟鍵盤工具類簡單示例

    Android開發(fā)之彈出軟鍵盤工具類簡單示例

    這篇文章主要介紹了Android開發(fā)之彈出軟鍵盤工具類,結(jié)合實例形式分析了Android彈出軟鍵盤及獲取焦點的簡單操作技巧,需要的朋友可以參考下
    2018-01-01
  • Android顯式Intent與隱式Intent的使用詳解

    Android顯式Intent與隱式Intent的使用詳解

    Intent的中文意思是“意圖,意向”, Intent對Android的核心和靈魂,是各組件之間的橋梁。四大組件分別為Activity 、Service、BroadcastReceiver、ContentProvider。而這四種組件是獨立的,它們之間可以互相調(diào)用,協(xié)調(diào)工作,最終組成一個真正的Android應用
    2022-09-09
  • 深入解析android5.1 healthd

    深入解析android5.1 healthd

    這篇文章主要為大家詳細介紹了android5.1 healthd的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-01-01
  • Android編程之Button控件用法實例分析

    Android編程之Button控件用法實例分析

    這篇文章主要介紹了Android編程之Button控件用法,較為詳細的分析了Button控件的功能、定義及相關(guān)使用注意事項,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-10-10
  • Android基礎開發(fā)小案例之短信發(fā)送器

    Android基礎開發(fā)小案例之短信發(fā)送器

    這篇文章主要為大家詳細介紹了Android基礎開發(fā)小案例之短信發(fā)送器的具體實現(xiàn)代碼,感興趣的小伙伴們可以參考一下
    2016-05-05
  • Android Studio 3.0的下載安裝教程

    Android Studio 3.0的下載安裝教程

    Android Studio從3.0版本新增了許多功能,當然首當其沖就是從3.0版本新增了對 Kotlin 開發(fā)語言的支持,除此之外還有其他一些新功能,今天我們主要來看看如何更新Android Studio 3.0
    2017-10-10
  • Android編程中ViewPage判斷左右滑動方向的方法

    Android編程中ViewPage判斷左右滑動方向的方法

    這篇文章主要介紹了Android編程中ViewPage判斷左右滑動方向的方法,涉及Android中ViewPage針對滑動判定的相關(guān)技巧,非常簡單實用,需要的朋友可以參考下
    2015-10-10

最新評論