android安全加密专题文章索引
以上学习所有内容,对称加密、非对称加密、消息摘要、数字签名等知识都是为了理解数字证书工作原理而作为一个预备知识。数字证书是密码学里的终极武器,是人类几千年历史总结的智慧的结晶,只有在明白了数字证书工作原理后,才能理解https 协议的安全通讯机制。最终才能在ssl 开发过程中得心应手。
另外,对称加密和消息摘要这两个知识点是可以单独拿来使用的。
数字证书使用到了以上学习的所有知识
通过以上内容的学习,我们要能掌握以下知识点:
凯撒密码
1. 介绍
凯撒密码作为一种最为古老的对称加密体制,在古罗马的时候都已经很流行,他的基本思想是:通过把字母移动一定的位数来实现加密和解密。明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。例如,当偏移量是3 的时候,所有的字母a 将被替换成d,b 变成e,由此可见,位数就是凯撒密码加密和解密的密钥。
例如:字符串”abc”的每个字符都右移3 位则变成”def”,解密的时候”def”的每个字符左移3 位即能还原,如下图所示:
2. 准备知识
//字符转换成ascii 码数值 char chara = 'a'; int inta = chara; //char 强转为int 即得到对应的ascii 码值,'a'的值为97 //ascii 码值转成char int inta = 97;//97 对应的ascii 码'a' char chara = (char) inta; //int 值强转为char 即得到对应的ascii 字符,即'a'
3. 凯撒密码的简单代码实现
/** * 加密 * @param input 数据源(需要加密的数据) * @param key 秘钥,即偏移量 * @return 返回加密后的数据 */ public static string encrypt(string input, int key) { //得到字符串里的每一个字符 char[] array = input.tochararray(); for (int i = 0; i < array.length; ++i) { //字符转换成ascii 码值 int ascii = array[i]; //字符偏移,例如a->b ascii = ascii + key; //ascii 码值转换为char char newchar = (char) ascii; //替换原有字符 array[i] = newchar; //以上4 行代码可以简写为一行 //array[i] = (char) (array[i] + key); } //字符数组转换成string return new string(array); } /** * 解密 * @param input 数据源(被加密后的数据) * @param key 秘钥,即偏移量 * @return 返回解密后的数据 */ public static string decrypt(string input, int key) { //得到字符串里的每一个字符 char[] array = input.tochararray(); for (int i = 0; i < array.length; ++i) { //字符转换成ascii 码值 int ascii = array[i]; //恢复字符偏移,例如b->a ascii = ascii - key; //ascii 码值转换为char char newchar = (char) ascii; //替换原有字符 array[i] = newchar; //以上4 行代码可以简写为一行 //array[i] = (char) (array[i] - key); } //字符数组转换成string return new string(array); }
代码输出结果:
4. 破解凯撒密码:频率分析法
凯撒密码加密强度太低,只需要用频度分析法即可破解。
在任何一种书面语言中,不同的字母或字母组合出现的频率各不相同。而且,对于以这种语言书写的任意一段文本,都具有大致相同的特征字母分布。比如,在英语中,字母e 出现的频率很高,而x 则出现得较少。
英语文本中典型的字母分布情况如下图所示:
5. 破解流程
注意点:统计密文里出现次数最多的字符时,需多统计几个备选,因为最多的可能是空格或者其他字符,例如下图出现次数最多的字符'#'是空格加密后的字符,'h'才是'e'偏移后的值。
解密时要多几次尝试,因为不一定出现次数最多的字符就是我们想要的目标字符,如下图,第二次解密的结果才是正确的。
/** * 频率分析法破解凯撒密码 */ public class frequencyanalysis { //英文里出现次数最多的字符 private static final char magic_char = 'e'; //破解生成的最大文件数 private static final int de_max_file = 4; public static void main(string[] args) throws exception { //测试1,统计字符个数 //printcharcount("article1_en.txt"); //加密文件 //int key = 3; //encryptfile("article1.txt", "article1_en.txt", key); //读取加密后的文件 string artile = file2string("article1_en.txt"); //解密(会生成多个备选文件) decryptcaesarcode(artile, "article1_de.txt"); } public static void printcharcount(string path) throws ioexception{ string data = file2string(path); list<entry<character, integer>> maplist = getmaxcountchar(data); for (entry<character, integer> entry : maplist) { //输出前几位的统计信息 system.out.println("字符'" + entry.getkey() + "'出现" + entry.getvalue() + "次"); } } public static void encryptfile(string srcfile, string destfile, int key) throws ioexception { string artile = file2string(srcfile); //加密文件 string encryptdata = myencrypt.encrypt(artile, key); //保存加密后的文件 string2file(encryptdata, destfile); } /** * 破解凯撒密码 * @param input 数据源 * @return 返回解密后的数据 */ public static void decryptcaesarcode(string input, string destpath) { int decount = 0;//当前解密生成的备选文件数 //获取出现频率最高的字符信息(出现次数越多越靠前) list<entry<character, integer>> maplist = getmaxcountchar(input); for (entry<character, integer> entry : maplist) { //限制解密文件备选数 if (decount >= de_max_file) { break; } //输出前几位的统计信息 system.out.println("字符'" + entry.getkey() + "'出现" + entry.getvalue() + "次"); ++decount; //出现次数最高的字符跟magic_char的偏移量即为秘钥 int key = entry.getkey() - magic_char; system.out.println("猜测key = " + key + ", 解密生成第" + decount + "个备选文件" + "\n"); string decrypt = myencrypt.decrypt(input, key); string filename = "de_" + decount + destpath; string2file(decrypt, filename); } } //统计string里出现最多的字符 public static list<entry<character, integer>> getmaxcountchar(string data) { map<character, integer> map = new hashmap<character, integer>(); char[] array = data.tochararray(); for (char c : array) { if(!map.containskey(c)) { map.put(c, 1); }else{ integer count = map.get(c); map.put(c, count + 1); } } //输出统计信息 /*for (entry<character, integer> entry : map.entryset()) { system.out.println(entry.getkey() + "出现" + entry.getvalue() + "次"); }*/ //获取获取最大值 int maxcount = 0; for (entry<character, integer> entry : map.entryset()) { //不统计空格 if (/*entry.getkey() != ' ' && */entry.getvalue() > maxcount) { maxcount = entry.getvalue(); } } //map转换成list便于排序 list<entry<character, integer>> maplist = new arraylist<map.entry<character,integer>>(map.entryset()); //根据字符出现次数排序 collections.sort(maplist, new comparator<entry<character, integer>>(){ @override public int compare(entry<character, integer> o1, entry<character, integer> o2) { return o2.getvalue().compareto(o1.getvalue()); } }); return maplist; } public static string file2string(string path) throws ioexception { filereader reader = new filereader(new file(path)); char[] buffer = new char[1024]; int len = -1; stringbuffer sb = new stringbuffer(); while ((len = reader.read(buffer)) != -1) { sb.append(buffer, 0, len); } return sb.tostring(); } public static void string2file(string data, string path){ filewriter writer = null; try { writer = new filewriter(new file(path)); writer.write(data); } catch (exception e) { e.printstacktrace(); }finally { if (writer != null) { try { writer.close(); } catch (ioexception e) { e.printstacktrace(); } } } } }
对称加密
介绍
加密和解密都使用同一把秘钥,这种加密方法称为对称加密,也称为单密钥加密。
简单理解为:加密解密都是同一把钥匙。
凯撒密码就属于对称加密,他的字符偏移量即为秘钥。
对称加密常用算法
aes、des、3des、tdea、blowfish、rc2、rc4、rc5、idea、skipjack 等。
des:全称为data encryption standard,即数据加密标准,是一种使用密钥加密的块算法,1976 年被美国联邦政府的国家标准局确定为联邦资料处理标准(fips),随后在国际上广泛流传开来。
3des:也叫triple des,是三重数据加密算法(tdea,triple data encryption algorithm)块密码的通称。
它相当于是对每个数据块应用三次des 加密算法。由于计算机运算能力的增强,原版des 密码的密钥长度变得容易被暴力破解;3des 即是设计用来提供一种相对简单的方法,即通过增加des 的密钥长度来避免类似的攻击,而不是设计一种全新的块密码算法。
aes: 高级加密标准(英语:advanced encryption standard,缩写:aes),在密码学中又称rijndael 加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的des,已经被多方分析且广为全世界所使用。经过五年的甄选流程,高级加密标准由美国国家标准与技术研究院(nist)于2001 年11 月26 日发布于fips pub 197,并在2002 年5 月26 日成为有效的标准。2006 年,高级加密标准已然成为对称密钥加密中最流行的算法之一。
des 算法简介
des 加密原理(对比特位进行操作,交换位置,异或等等,无需详细了解)
准备知识
bit 是计算机最小的传输单位。以0 或1 来表示比特位的值
例如数字3 对应的二进制数据为:00000011
代码示例
int i = 97; string bit = integer.tobinarystring(i); //输出:97 对应的二进制数据为: 1100001 system.out.println(i + "对应的二进制数据为: " + bit);
byte 与bit 区别
数据存储是以“字节”(byte)为单位,数据传输是以大多是以“位”(bit,又名“比特”)为单位,一个位就代表一个0 或1(即二进制),每8 个位(bit,简写为b)组成一个字节(byte,简写为b),是最小一级的信息单位。
byte 的取值范围:
//byte 的取值范围:-128 到127 system.out.println(byte.min_value + "到" + byte.max_value);
即10000000 到01111111 之间,一个字节占8 个比特位
二进制转十进制图示:
任何字符串都可以转换为字节数组
string data = "1234abcd";
byte[] bytes = data.getbytes();//内容为:49 50 51 52 97 98 99 100
上面数据49 50 51 52 97 98 99 100 对应的二进制数据(即比特位为):
00110001
00110010
00110011
00110100
01100001
01100010
01100011
01100100
将他们间距调大一点,可看做一个矩阵:
之后可对他们进行各种操作,例如交换位置、分割、异或运算等,常见的加密方式就是这样操作比特位的,例如下图的ip 置换以及s-box 操作都是常见加密的一些方式:
ip 置换:
s-box 置换:
des 加密过程图解(流程很复杂,只需要知道内部是操作比特位即可):
对称加密应用场景
des 算法代码实现
//1,得到cipher 对象(可翻译为密码器或密码系统) cipher cipher = cipher.getinstance("des"); //2,创建秘钥 secretkey key = keygenerator.getinstance("des").generatekey(); //3,设置操作模式(加密/解密) cipher.init(cipher.encrypt_mode, key); //4,执行操作 byte[] result = cipher.dofinal("黑马".getbytes());
aes 算法代码实现
用法同上,只需把”des”参数换成”aes”即可。
使用base64 编码加密后的结果
byte[] result = cipher.dofinal("黑马".getbytes());
system.out.println(new string(result));
输出结果:
加密后的结果是字节数组,这些被加密后的字节在码表(例如utf-8 码表)上找不到对应字符,会出现乱码,当乱码字符串再次转换为字节数组时,长度会变化,导致解密失败,所以转换后的数据是不安全的。
使用base64 对字节数组进行编码,任何字节都能映射成对应的base64 字符,之后能恢复到字节数组,利于加密后数据的保存于传输,所以转换是安全的。同样,字节数组转换成16 进制字符串也是安全的。
密文转换成base64 编码后的输出结果:
密文转换成16 进制编码后的输出结果:
java 里没有直接提供base64 以及字节数组转16 进制的api,开发中一般是自己手写或直接使用第三方提供的成熟稳定的工具类(例如apache 的commons-codec)。
base64 字符映射表
对称加密的具体应用方式
1. 生成秘钥并保存到硬盘上,以后读取该秘钥进行加密解密操作,实际开发中用得比较少
//生成随机秘钥 secretkey secretkey = keygenerator.getinstance("aes").generatekey(); //序列化秘钥到磁盘上 fileoutputstream fos = new fileoutputstream(new file("heima.key")); objectoutputstream oos = new objectoutputstream(fos); oos.writeobject(secretkey); //从磁盘里读取秘钥 fileinputstream fis = new fileinputstream(new file("heima.key")); objectinputstream ois = new objectinputstream(fis); key key = (key) ois.readobject();
2. 使用自定义秘钥(秘钥写在代码里)
//创建密钥写法1 keyspec keyspec = new deskeyspec(key.getbytes()); secretkey secretkey = secretkeyfactory.getinstance(algorithm). generatesecret(keyspec); //创建密钥写法2 //secretkey secretkey = new secretkeyspec(key.getbytes(), key_algorithm); cipher cipher = cipher.getinstance(cipher_algorithm); cipher.init(cipher.decrypt_mode, secretkey); //得到key 后,后续代码就是cipher 的写法,此处省略...
注意事项
把秘钥写在代码里有一定风险,当别人反编译代码的时候,可能会看到秘钥,android 开发里建议用jni 把秘钥值写到c 代码里,甚至拆分成几份,最后再组合成真正的秘钥
算法/工作模式/填充模式
初始化cipher 对象时,参数可以直接传算法名:例如:
cipher c = cipher.getinstance("des");
也可以指定更详细的参数,格式:”algorithm/mode/padding” ,即”算法/工作模式/填充模式”
cipher c = cipher.getinstance("des/cbc/pkcs5padding");
密码块工作模式
块密码工作模式(block cipher mode of operation),是对于按块处理密码的加密方式的一种扩充,不仅仅适用于aes,包括des, rsa 等加密方法同样适用。
填充模式
填充(padding),是对需要按块处理的数据,当数据长度不符合块处理需求时,按照一定方法填充满块长的一种规则。
具体代码:
//秘钥算法 private static final string key_algorithm = "des"; //加密算法:algorithm/mode/padding 算法/工作模式/填充模式 private static final string cipher_algorithm = "des/ecb/pkcs5padding"; //秘钥 private static final string key = "12345678";//des 秘钥长度必须是8 位或以上 //private static final string key = "1234567890123456";//aes 秘钥长度必须是16 位 //初始化秘钥 secretkey secretkey = new secretkeyspec(key.getbytes(), key_algorithm); cipher cipher = cipher.getinstance(cipher_algorithm); //加密 cipher.init(cipher.encrypt_mode, secretkey); byte[] result = cipher.dofinal(input.getbytes());
注意:aes、des 在cbc 操作模式下需要iv 参数
//aes、des 在cbc 操作模式下需要iv 参数 ivparameterspec iv = new ivparameterspec(key.getbytes()); //加密 cipher.init(cipher.encrypt_mode, secretkey, iv);
总结
des 安全度在现代已经不够高,后来又出现的3des 算法强度提高了很多,但是其执行效率低下,aes算法加密强度大,执行效率高,使用简单,实际开发中建议选择aes 算法。实际android 开发中可以用对称加密(例如选择aes 算法)来解决很多问题,例如:
如对本文有疑问, 点击进行留言回复!!
荐 【Android 电量优化】电量优化 ( 网络状态获取 | 主动获取 WIFI 状态 | 被动获取 WIFI 状态 )
Android xhdpi图片转换,能任意转换Android Drawable下“ldpi“, “mdpi“, “hdpi“, “xhdpi“,“xxhdpi“, “xxxhdpi“ 各个类型的图片
unity 之 Bugly(AndroidStudio) 的使用
荐 Android开发7年,疫情期间八家大厂高工的面试经历和真题整理
Android 自定义可编辑可任意全屏拖动的EditText
【android 布局】px和dp的概念和区别,什么情况下用px,dp,sp?
网友评论