BouncyCastle
BouncyCastle就是一个提供了很多哈希算法和加密算法的第三方开源库。
用法:首先必须把BoucyCastle提供的文件添加至classpath。
代码实现:
package com.apesource.demo04;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.Arrays;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider;
//用第三方类库BouncyCastle提供RipeMD60算法加密
public class Main01 {
public static void main(String[] args) {
try {
//注册BouncyCastle提供通知类对象BouncyCastleProvider
Security.addProvider(new BouncyCastleProvider());
//获取RipeMD160算法的“消息摘要对象(加密对象)”
MessageDigest md = MessageDigest.getInstance("RipeMD160");
//更新原始数据
md.update("hello".getBytes());
//获取消息摘要
byte[] result =md.digest();
//消息摘要的字节长度和内容
System.out.println(result.length);//160位=20字节
System.out.println(Arrays.toString(result));
//16进制内容字符串
String hex = new BigInteger(1,result).toString(16);
System.out.println(hex.length());//字节=40字符
System.out.println(hex);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
}
对称加密算法
对称加密算法就是传统的用一个密码进行加密和解密。
从程序的角度看,加密就是一个函数,它接收密码和明文,然后输出密文。而解密则相反,它接收密码和密文,然后输出明文。
常见的对称加密算法有:
DES、AES 、IDEA
DES:DES算法由于密钥过短,可以在短时间内被暴力破解,不安全。
AES加密
AES算法是目前应用最广泛的加密算法。比较常见的工作模式是ECB 和 CBC。
ECB模式
步骤如下:
1、根据算法名称/工作模式/填充模式获取Cipher实例;
2、根据算法名称初始化一个SecretKey实例,密钥必须是指定长度;
3、使用SercetKey初始化Cipher实例,并设置加密或解密模式;
4、传入明文或密文,获得密文或明文。
代码实现:
package com.apesource.demo04;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class Main02 {
public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
//原文
String message = "Hello World";
System.out.println("Message"+message);
//128位密钥 = 16 bytes Key
byte[] key = "123877766555443221246677UIJHBwed".getBytes();
//加密
byte[] data = message.getBytes();
byte[] encrypted = encrypted(key,data);
System.out.println("Encrypt(加密):"+ Base64.getEncoder().encodeToString(encrypted));
//解密
byte[] decrypted= decrypt(key,encrypted);
System.out.println("Decrypted:"+new String(decrypted));
}
//加密
public static byte[] encrypted(byte[] key, byte[] input) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
//创建密码对象,需要传入算法/工作模式/填充模式
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
//根据key的字节内容,”恢复“密钥对象
SecretKey keySpec = new SecretKeySpec(key,"AES");
//初始化密钥:色湖之加密模式ENCRYPT_MOOD
cipher.init(Cipher.ENCRYPT_MODE,keySpec);
//根据原始内容,进行加密
return cipher.doFinal(input);
}
//解密
public static byte[] decrypt(byte[] key, byte[] input) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
//创建密码对象,需要传入算法/工作模式/填充模式
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
//根据key的字节内容,“恢复”密钥对象
SecretKey keySpec = new SecretKeySpec(key,"AES");
//初始化密钥:设置揭秘模式DECRYPT_MOOD
cipher.init(Cipher.DECRYPT_MODE,keySpec);
//根据原始内容(字节),进行解密
return cipher.doFinal(input);
}
}
CBC模式
在CBC模式下,需要生成一个随机的16字节的IV参数,必须使用SecureRandom生成。因为多了一个IvParameterSpec实例,因此,初始化方法需要调用Cipher的一个重载方法并传入IvParameterSpec。(每次生成的IV不同,密文也不同)。
它是最简单的AES加密模式。它只需要一个固定长度的密钥。固定的密钥会生成固定的密钥,这种一对一的加密方式会导致安全性降低。因此,它需要一个随机数作为IV参数。
代码实现:
package com.apesource.demo04;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.spec.IESParameterSpec;
public class Main03 {
public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
//AES对称加密
//CBC模式
//原文
String message = "Hello World";
System.out.println("Message(原始信息)"+message);
//256位密钥 = 32 bytes Key
byte[] key = "12232323233we555544545678767676n".getBytes();
//加密
byte[] data = message.getBytes();
byte[] encrypted = encrypt(key,data);
System.out.println("Ensrypted(加密内容)"+Base64.getEncoder().encodeToString(encrypted));
//解密
byte[] decrypted = decrpt(key,encrypted);
System.out.println("Decrypted(解密内容)"+new String(decrypted));
}
//加密
public static byte[] encrypt(byte[] key, byte[] input) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
//设置算法/工作模式CBC/填充
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//恢复密钥对象
SecretKeySpec keySpec = new SecretKeySpec(key,"AES");
//CBC模式需要生成一个16bytes的随机数
SecureRandom sr = SecureRandom.getInstanceStrong();
byte[] iv = sr.generateSeed(16);//生成16个字节的随机数
System.out.println(Arrays.toString(iv));
IvParameterSpec ivps = new IvParameterSpec(iv);//随机数封装成IvParameterSpec对象
//初始化密钥:操作模式、密钥、IV参数
cipher.init(Cipher.ENCRYPT_MODE,keySpec,ivps);
//加密
byte[] data = cipher.doFinal(input);
//IV不需要保密,把IV和密文一起返回
return join(iv,data);
}
//解密
public static byte[] decrpt(byte[] key,byte[] input) throws NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
//把input分割成IV和密文
byte[] iv = new byte[16];
byte[] data = new byte[input.length - 16];
System.arraycopy(input,0,iv,0,16);//iv
System.arraycopy(input,16,data,0,data.length);//密文
System.out.println(Arrays.toString(iv));
//解密
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//密码对象
SecretKey keySpec = new SecretKeySpec(key,"AES");//恢复密钥
IvParameterSpec ivps = new IvParameterSpec(iv);//恢复IV
//初始化密钥:操作模式、密钥、IV参数
cipher.init(Cipher.DECRYPT_MODE,keySpec,ivps);
//解密操作
return cipher.doFinal(data);
}
public static byte[] join(byte[] bs1,byte[] bs2) {
byte[] r = new byte[bs1.length+bs2.length];
System.arraycopy(bs1,0,r,0,bs1.length);
System.arraycopy(bs2, 0, r, bs1.length,bs2.length);
return r;
}
}
密钥交换算法
对称加密算法解决了数据加密的问题。
在安全的信道上传递加密文件是没有问题的,再不安全的信道上安全的传输密钥,就需要使用密钥交换算法:DH算法。
如图所示:
代码实例:
package com.apesource.demo04;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.KeyAgreement;
public class Main04 {
public static void main(String[] args) throws NoSuchAlgorithmException {
//Bob和Alice
Person Bob = new Person("Bob");
Person Alice = new Person("Alice");
//各自生成keyPair:公钥+私钥
Bob.generateKeyPair();
Alice.generateKeyPair();
//双方交换各自的PublicKey(公钥):
//Bob根据Alicede PublicKey生成自己的本地密钥(共享公钥)
Bob.generateSecretKey(Alice.publicKey.getEncoded());
//Alice根据Bob的publicKey生成自己的本地密钥(共享公钥)
Alice.generateSecretKey(Bob.publicKey.getEncoded());
//检查双方本地密钥是否相同:
Bob.printKeys();
Alice.printKeys();
//双方的SecreKey相同,后续通信将使用SecreKey作为密钥进行AES加解密...
}
}
class Person{
public final String name;
//密钥
public PublicKey publicKey;//公钥
private PrivateKey privateKey;//私钥
private byte[] secretKey;//本地密钥
//构造方法
public Person(String name) {
this.name = name;
}
//生成本地KeyPair:(公钥+私钥)
public void generateKeyPair() throws NoSuchAlgorithmException {
try {
//创建DH算法的“密钥对”生成器
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DH");
kpGen.initialize(512);
//生成一个“密钥对”
KeyPair kp = kpGen.generateKeyPair();
this.privateKey= kp.getPrivate();
this.publicKey = kp.getPublic();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//按照“对方的公钥”=>生成“共享密钥”
public void generateSecretKey(byte[] receivePubKeyBytes) {
try {
//从byte[]恢复PublicKey:
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(receivePubKeyBytes);
//根据DH算法获取KeyFactory
KeyFactory kf = KeyFactory.getInstance("DH");
//通过KeyFactory创建公钥
PublicKey receivePubilcKey = kf.generatePublic(keySpec);
//生成本地密钥(共享密钥)
KeyAgreement keyAgreement = KeyAgreement.getInstance("DH");
keyAgreement.init(this.privateKey);//初始化“自己的PrivateKey”
keyAgreement.doPhase(receivePubilcKey, true);//根据“对方的PublicKey”
//生成SecretKey本地密钥(共享公用)
this.secretKey = keyAgreement.generateSecret();
} catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void printKeys() {
System.out.printf("Name: %s\n",this.name);
System.out.printf("Private key: %x\n",new BigInteger(1,this.privateKey.getEncoded()));
System.out.printf("Public key: %x\n",new BigInteger(1,this.publicKey.getEncoded()));
System.out.printf("Secret key: %x\n",new BigInteger(1,this.secretKey));
}
}
非对称加密算法
根据DH算法我们知道,公钥和私钥组成的密钥对是非常有用的加密方式,公钥是公开的,而私钥是完全保密的,由此奠定了非对称加密的基础。
非对称加密:加密和解密使用的不是相同的密钥,只有一个公钥-私钥对才能正常加解密。
RSA算法
是典型的非对称加密算法。
优点:对称加密需要协商密钥,而非对称加密可以安全的公开各自的公钥。在N个人之间通信的时候:使用非对称加密只需要N个密钥,每个人只管理自己的密钥对。而使用加密对称需要N*(N-1)/2个密钥,因此每个人需要管理N-1个密钥,密钥管理难度大,而且非常容易泄露。
缺点:运算速度非常慢。
举例说明:
假设小明需要给小红传输加密文件,他俩首先交换了各自的公钥然后:
1、小明生成一个随机的AES口令,然后用小红的公钥通过RSA加密这个口令,并发给小红;
2、小红用自己的RSA私钥解密得到AES口令;
3、双方使用这个共享的AES口令用AES加密通信。
代码实现:
package com.apesource.demo04;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
// RSA
public class Main05 {
public static void main(String[] args) throws Exception {
// 明文:
byte[] plain = "Hello, encrypt use RSA".getBytes("UTF-8");
// 创建公钥/私钥对:
Human alice = new Human("Alice");
// 用Alice的公钥加密:
// 获取Alice的公钥,并输出
byte[] pk = alice.getPublicKey();
System.out.println(String.format("public key(公钥): %x", new BigInteger(1, pk)));
// 使用公钥加密
byte[] encrypted = alice.encrypt(plain);
System.out.println(String.format("encrypted: %x", new BigInteger(1, encrypted)));
// 用Alice的私钥解密:
// 获取Alice的私钥,并输出
byte[] sk = alice.getPrivateKey();
System.out.println(String.format("private key: %x", new BigInteger(1, sk)));
// 使用私钥解密
byte[] decrypted = alice.decrypt(encrypted);
System.out.println(new String(decrypted, "UTF-8"));
}
}
// 用户类
class Human {
// 姓名
String name;
// 私钥:
PrivateKey sk;
// 公钥:
PublicKey pk;
// 构造方法
public Human(String name) throws GeneralSecurityException {
// 初始化姓名
this.name = name;
// 生成公钥/私钥对:
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");
kpGen.initialize(1024);
KeyPair kp = kpGen.generateKeyPair();
this.sk = kp.getPrivate();
this.pk = kp.getPublic();
}
// 把私钥导出为字节
public byte[] getPrivateKey() {
return this.sk.getEncoded();
}
// 把公钥导出为字节
public byte[] getPublicKey() {
return this.pk.getEncoded();
}
// 用公钥加密:
public byte[] encrypt(byte[] message) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, this.pk); // 使用公钥进行初始化
return cipher.doFinal(message);
}
// 用私钥解密:
public byte[] decrypt(byte[] input) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, this.sk); // 使用私钥进行初始化
return cipher.doFinal(input);
}
}