加解密类Cipher
Cipher类为加密和解密提供密码功能。它构成了Java Cryptographic Extension(JCE)框架的核心。在之前的内容中,只完成了密钥的处理,并未完成加密与解密的操作。这些核心操作需要通过Cipher类来实现。
1.创建加解密对象
新建Cipher对象,需要传入一个参数,指定算法、模式和填充方式。例如,传入“AES/CBC/NoPadding”表示进行AES加密,模式为CBC,不填充(NoPadding);传入“DESede/CBC/NoPadding”可进行DES3加密,模式为CBC,不填充。
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
2.初始化加解密对象
Cipher对象创建成功后,需要进行初始化。初始化就是将加解密所需要的密钥和一组参数准备给Cipher对象。初始化的函数init根据算法所需的数据不同,其形式也有多种,常用的是以下几种形式:
oid init(int opmode, Key key);
void init(int opmode, Key key, AlgorithmParameters params);
//用一个密钥、一组算法参数和一个随机源初始化此 Cipher
void init(int opmode, Key key, AlgorithmParameters params, SecureRandom random)
其中,参数opmode表示此Cipher的操作模式(取值为ENCRYPT_MODE、DECRYPT_MODE、WRAP_MODE或UNWRAP_MODE);key表示加解密密钥,可以由new SecretKeySpec得到;params表示算法参数(比如cbc需要向量iv);random表示一个随机数。
3.完成加解密运算
初始化后,就可以真正开始加解密运算工作了。函数doFinal用于完成大数据最后一部分的加解密操作,或者小数据的全部加解密工作。如果对长度不是很大的数据进行加解密,就用doFinal完成工作。如果对长度很大的数据进行加解密,那么不可能一下子把所有数据都传给doFinal,只能分段后进行加解密,而且要借助于分段加解密函数update。
实现DES加密
import jakarta.xml.bind.DatatypeConverter;
import lombok.SneakyThrows;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
public class test {
@SneakyThrows
public byte[] encrypt(byte[] originalContent, byte[] key) {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
SecretKeySpec skeySpec = new SecretKeySpec(key, "DES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(originalContent);
return encrypted;
}
@SneakyThrows
public byte[] decrypt(byte[] content, byte[] key) {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
Key sKeySpec = new SecretKeySpec(key, "DES");
cipher.init(Cipher.DECRYPT_MODE, sKeySpec);
byte[] result = cipher.doFinal(content);
return result;
}
public static void main(String[] args) {
test des = new test();
byte[] out, chk;
String in = "abc";
String key = "12345678";
System.out.print("明文:");
System.out.println(in);
out = des.encrypt(in.getBytes(), key.getBytes());
String strHexBytes = DatatypeConverter.printHexBinary(out);
System.out.print("密文:");
System.out.println(strHexBytes);
chk = des.decrypt(out, key.getBytes());
String strChk = new String(chk);
System.out.print("解密:");
System.out.println(strChk);
}
}