Java使⽤Cipher类实现加密,包括DES,DES3,AES和RSA加密
⼀、先看⼀个简单加密,解密实现
1.1 加密
/**
* content: 加密内容
* slatKey: 加密的盐,16位字符串
* vectorKey: 加密的向量,16位字符串
*/
public String encrypt(String content, String slatKey, String vectorKey) throws Exception {
Cipher cipher = Instance("AES/CBC/PKCS5Padding");
SecretKey secretKey = new Bytes(), "AES");
IvParameterSpec iv = new Bytes());
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] encrypted = cipher.Bytes());
deBase64String(encrypted);
}
1.2 解密
/**
* content: 解密内容(base64编码格式)
* slatKey: 加密时使⽤的盐,16位字符串
* vectorKey: 加密时使⽤的向量,16位字符串
*/
public String decrypt(String base64Content, String slatKey, String vectorKey) throws Exception {
Cipher cipher = Instance("AES/CBC/PKCS5Padding");
SecretKey secretKey = new Bytes(), "AES");
IvParameterSpec iv = new Bytes());
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] content = Base64.decodeBase64(base64Content);
byte[] encrypted = cipher.doFinal(content);
return new String(encrypted);
}
1.3 代码解释
上⾯简单实现了AES("AES/CBC/PKCS5Padding")的加密和解密。可以看到代码中主要的是cipher对象,并有以下调⽤
(1)新建Cipher对象时需要传⼊⼀个参数"AES/CBC/PKCS5Padding"
(2)cipher对象使⽤之前还需要初始化,共三个参数("加密模式或者解密模式","密匙","向量")
(3)调⽤数据转换:cipher.doFinal(content),其中content是⼀个byte数组
实际上Cipher类实现了多种加密算法,在创建Cipher对象时,传⼊不同的参数就可以进⾏不同的加密算法。⽽这些算法不同的地⽅只是创建密匙的⽅法不同⽽已。
如传⼊“AES/CBC/NoPadding”可进⾏AES加密,传⼊"DESede/CBC/NoPadding"可进⾏DES3加密。具体的后⾯会介绍到。
要参考Java⾃带的加密算法,可以参考JDK⽂档的附录:
⼆、Java的Cipher类
2.1 Cipher类提供了加密和解密的功能。
该项⽬使⽤Cipher类完成aes,des,des3和rsa加密.
获取Cipher类的对象:Cipher cipher = Instance("DES/CBC/PKCS5Padding"); 参数按"算法/
模式/填充模式",有以下的参数
* AES/CBC/NoPadding (128)
* AES/CBC/PKCS5Padding (128)
* AES/ECB/NoPadding (128)
* AES/ECB/PKCS5Padding (128)
* DES/CBC/NoPadding (56)
* DES/CBC/PKCS5Padding (56)
* DES/ECB/NoPadding (56)
* DES/ECB/PKCS5Padding (56)
* DESede/CBC/NoPadding (168)
* DESede/CBC/PKCS5Padding (168)
* DESede/ECB/NoPadding (168)
* DESede/ECB/PKCS5Padding (168)
* RSA/ECB/PKCS1Padding (1024, 2048)
* RSA/ECB/OAEPWithSHA-1AndMGF1Padding (1024, 2048)
* RSA/ECB/OAEPWithSHA-256AndMGF1Padding (1024, 2048)
(1)加密算法有:AES,DES,DESede(DES3)和RSA 四种
(2) 模式有CBC(有向量模式)和ECB(⽆向量模式),向量模式可以简单理解为偏移量,使⽤CBC模式需要定义⼀个IvParameterSpec对象
(3) 填充模式:
* NoPadding: 加密内容不⾜8位⽤0补⾜8位, Cipher类不提供补位功能,需⾃⼰实现代码给加密内容添加0, 如{65,65,65,0,0,0,0,0}
* PKCS5Padding: 加密内容不⾜8位⽤余位数补⾜8位, 如{65,65,65,5,5,5,5,5}或{97,97,97,97,97,97,2,2
}; 刚好8位补8位8
2.2 Cipher对象需要初始化
init(int opmode, Key key, AlgorithmParameterSpec params)
(1)opmode :Cipher.ENCRYPT_MODE(加密模式)和 Cipher.DECRYPT_MODE(解密模式)
(2)key :密匙,使⽤传⼊的盐构造出⼀个密匙,可以使⽤SecretKeySpec、KeyGenerator和KeyPairGenerator创建密匙,其中
* SecretKeySpec和KeyGenerator⽀持AES,DES,DESede三种加密算法创建密匙
* KeyPairGenerator⽀持RSA加密算法创建密匙
加密算法
密匙长度向量长度AES
1616DES
88DES3
248(3)params :使⽤CBC 模式时必须传⼊该参数,该项⽬使⽤IvParameterSpec 创建iv 对象
2.3 加密或解密
byte[] b = cipher.doFinal(content);
返回结果为byte 数组,如果直接使⽤ new String(b) 封装成字符串,则会出现乱码
三、创建密匙
创建密匙主要使⽤SecretKeySpec 、KeyGenerator 和KeyPairGenerator 三个类来创建密匙。
3.1 SecretKeySpec 类
SecretKeySpec 类⽀持创建密匙的加密算法
(ASE,DES,DES3)
SecretKey secretKey = new Bytes(), "AES");
但需要主要的是不同的加密算法的byte 数组的长度是不同的,创建密匙前最好先检测下byte 数组的长度。各加密算法的密匙长度如下
3.2 KeyGenerator 类
KeyGenerator 类⽀持创建密匙的加密算法(ASE,DES,DES3)
/**
* 获取加密的密匙,传⼊的slatKey 可以是任意长度的,作为SecureRandom 的随机种⼦,
* ⽽在KeyGenerator 初始化时设置密匙的长度128bit(16位byte)
*/
private static Key getSlatKey(String slatKey) throws Exception {
KeyGenerator kgen = Instance("AES");
SecureRandom random = Instance("SHA1PRNG");
random.Bytes());
kgen.init(128, random);
Key key = ateKey();
return key;
}
KeyGenerator 对象在初始化需要传⼊⼀个随机源。⼀般使⽤的都是SecureRandom 类来创建随机源,此时传⼊的盐只作为SecureRandom 类的随机种⼦,种⼦相同,产⽣的随机数也相同;
盐的长度不再受限制了,但KeyGenerator 对象则必须指定长度。
3.3KeyPairGenerator 类
RSA 加密算法使⽤的密匙是包含公匙和私匙两种,⼀般情况下,有使⽤公匙加密,则⽤私匙解密;使⽤私匙加密,则使⽤公匙解密。可以使⽤KeyPairGenerator 类来创建RSA 加密算法的密匙
KeyPairGenerator类⽀持创建密匙的加密算法(RSA)
/**
* 根据slatKey获取公匙,传⼊的slatKey作为SecureRandom的随机种⼦
java加密方式有哪些
* 若使⽤new SecureRandom()创建公匙,则需要记录下私匙,解密时使⽤
*/
private static byte[] getPublicKey(String slatKey) throws Exception {
KeyPairGenerator keyPairGenerator = Instance("RSA");
SecureRandom random = Instance("SHA1PRNG");
random.Bytes());
keyPairGenerator.initialize(1024, random);//or 2048
KeyPair keyPair = ateKeyPair();
Public().getEncoded();
}
/**
* 根据slatKey获取私匙,传⼊的slatKey作为SecureRandom的随机种⼦
*/
private static byte[] getPrivateKey(String slatKey) throws Exception {
KeyPairGenerator keyPairGenerator = Instance("RSA");
SecureRandom random = Instance("SHA1PRNG");
random.Bytes());
keyPairGenerator.initialize(1024, random);// or 2048
KeyPair keyPair = ateKeyPair();
Private().getEncoded();
}
同上,传⼊的盐只作为SecureRandom类的随机种⼦,盐相同,产⽣的keyPair的公匙和私匙也是同⼀对。
也可以不设置SecureRandom类的随机种⼦,直接使⽤new SecureRandom()创建⼀个新对象,此时就必须记录下公匙和私匙,在解密时使⽤。
四、对加密结果进⾏⼀层包装
4.1 针对1.3返回结果返回字符串乱码的问题,⼀般对byte数组进⾏处理
有两种处理⽅式:转换为base64的字符串或转换为16进制的字符串
4.2 转换为base64
使⽤apache下的Base64类进⾏封装即可,deBase64String(result); 结果形如
jar包下载:
4.3 转换为16进制
编码实现,即编码实现将2进制转换为16进制
/**
* 16进制⼯具类
*/
public class HexUtil {
private static final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
/**
* ⼗六进制转化为⼆进制
*/
public static byte[] hexStrToByteArray(String hexString) {
if (hexString == null) {
return null;
}
if (hexString.length() == 0) {
return new byte[0];
}
byte[] byteArray = new byte[hexString.length() / 2];
for (int i = 0; i < byteArray.length; i++) {
String subStr = hexString.substring(2 * i, 2 * i + 2);
byteArray[i] = ((byte) Integer.parseInt(subStr, 16));
}
return byteArray;
}
/**
* ⼆进制转化为⼗六进制
*/
public static String byteArrayToHexStr(byte[] byteArray) {
if (byteArray == null) {
return null;
}
char[] hexChars = new char[byteArray.length * 2];
for (int j = 0; j < byteArray.length; j++) {
int v = byteArray[j] & 0xFF;
hexChars[j * 2] = HEX_CHARS[v >>> 4];
hexChars[j * 2 + 1] = HEX_CHARS[v & 0x0F];
}
return new String(hexChars);
}
}
结果形如 五、Java加密的代码
代码我上传到github上了,欢迎下载~~
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论