栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

Android常用的数据加密方式代码详解

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android常用的数据加密方式代码详解

前言

Android 很多场合需要使用到数据加密,比如:本地登录密码加密,网络传输数据加密,等。在android 中一般的加密方式有如下:

亦或加密 
AES加密 
RSA非对称加密 
MD5加密算法 

当然还有其他的方式,这里暂且介绍以上四种加密算法的使用方式。

亦或加密算法

什么是亦或加密?

亦或加密是对某个字节进行亦或运算,比如字节 A^K = V,这是加密过程;
当你把 V^K得到的结果就是A,也就是 V^K = A,这是一个反向操作过程,解密过程。

亦或操作效率很高,当然亦或加密也是比较简单的加密方式,且亦或操作不会增加空间,源数据多大亦或加密后数据依然是多大。

示例代码如下:


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);
		
		for (int i = 0; i < count; i++) {
			fos.write(buff[i] ^ key);
		}
		while (true) {
			count = fis.read(buff);
			
			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();
		}
	}
}

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头部和尾部藏有文件压缩相关的信息,所有,我们只对头部和尾部采用亦或加密算法,即可对整个zip文件加密,当你不解密试图加压是会失败的。
也可以对整个文件进行亦或加密算法,所以你解密的时候其实是一个逆向的过程,使用同样的方法同样的key即可对加密的文件解密。当然以后加密的安全性可想而知,不是很安全,所以,亦或加密算法一般使用在不太重要的场景。由于亦或算法很快,所以加密速度也很快。

AES加密加密算法

什么是AES 加密

AES 对称加密

高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。 这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。

Android 中的AES 加密 秘钥 key 必须为16/24/32位字节,否则抛异常

示例代码:

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;
}

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();
		}
	}
}

public static void decryptByAES(String source, String dest) {
	encryptByAES(MODE_DECRYPTION, source, dest);
}

AES对称加密,加解密相比于亦或加密还是有点复杂的,安全性也比亦或加密高,AES加密不是绝对的安全。

RSA非对称加密

什么是Rsa加密?

RSA算法是最流行的公钥密码算法,使用长度可以变化的密钥。RSA是第一个既能用于数据加密也能用于数字签名的算法。

RSA的安全性依赖于大数分解,小于1024位的N已经被证明是不安全的,而且由于RSA算法进行的都是大数计算,使得RSA最快的情况也比DES慢上倍,这是RSA最大的缺陷,因此通常只能用于加密少量数据或者加密密钥,但RSA仍然不失为一种高强度的算法。

代码示例:


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;
//公钥加密

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;
	}
}

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);
}

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);
}

public static byte[] encryptByRSA(byte[] data, Key key) throws Exception {
	// 数据加密
	Cipher cipher = Cipher.getInstance(RSA);
	cipher.init(Cipher.ENCRYPT_MODE, key);
	return cipher.doFinal(data);
}

public static byte[] decryptByRSA(byte[] data, Key key) throws Exception {
	// 数据解密
	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加密后数据会变大

总结

以上就是本文关于Android常用的数据加密方式代码详解的全部内容,希望对大家有所帮助。如有不足之处,欢迎留言指出。感谢朋友们对本站的支持。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/157185.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号