欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-11-06 22:02:46
前言 android 很多场合需要使用到数据加密,比如:本地登录密码加密,网络传输数据加密,等。在android 中一般的加密方式有如下: 亦或加密  a...

前言

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

亦或加密 
aes加密 
rsa非对称加密 
md5加密算法 

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

亦或加密算法

什么是亦或加密?

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

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

示例代码如下:

/**
   * 亦或加解密,适合对整个文件的部分加密,比如文件头部,和尾部
   * 对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包结尾加密*/
			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头部和尾部藏有文件压缩相关的信息,所有,我们只对头部和尾部采用亦或加密算法,即可对整个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;
}
/**
   * 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是第一个既能用于数据加密也能用于数字签名的算法。

rsa的安全性依赖于大数分解,小于1024位的n已经被证明是不安全的,而且由于rsa算法进行的都是大数计算,使得rsa最快的情况也比des慢上倍,这是rsa最大的缺陷,因此通常只能用于加密少量数据或者加密密钥,但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 {
	// 数据加密
	cipher cipher = cipher.getinstance(rsa);
	cipher.init(cipher.encrypt_mode, key);
	return cipher.dofinal(data);
}
/**
   * 公钥解密
   *
   * @param data 待解密数据
   * @param key 密钥
   * @return byte[] 解密数据
   */
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常用的数据加密方式代码详解的全部内容,希望对大家有所帮助。如有不足之处,欢迎留言指出。感谢朋友们对本站的支持。