什么是非对称加密算法?
对称加密算法 在加密和解密时使用的是同一个秘钥
非对称加密算法 需要两个密钥来进行加密和解密,这两个秘钥是公开密钥和私有密钥
非对称加密即,用户A要加密一个消息发送给用户B,他应该首先向用户B索取她的公钥。然后,他用用户B的公钥加密,把加密结果发送给用户B,此文除了用户B,没有人能解开此加密结果。
案例
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 Main {
public static void main(String[] args) throws Exception {
// 明文:
byte[] plain = "Hello, encrypt use RSA".getBytes("UTF-8");
// 创建公钥/私钥对
Human hong = new Human("小红");
Human ming = new Human("小明");
// 小明使用小红的公钥对原文进行加密
// 1.获取小红的公钥
PublicKey hongPublicKey = hong.publickey;
System.out.println(String.format("小红的public key(公钥): %x", new BigInteger(1, hongPublicKey.getEncoded())));
// 2.使用公钥加密
byte[] encrypted = ming.encrypt(plain, hongPublicKey);
System.out.println(String.format("encrypted(加密): %x", new BigInteger(1, encrypted)));
// 小红使用自己的私钥解密:
// 1.获取小红的私钥,并输出
PrivateKey hongPrivateKey = hong.privatekey;
System.out.println(String.format("小红的private key(私钥): %x", new BigInteger(1, hongPrivateKey.getEncoded())));
// 2.使用私钥解密
byte[] decrypted = hong.decrypt(encrypted);
System.out.println("decrypted(解密): " + new String(decrypted, "UTF-8"));
}
}
// 用户类
class Human {
// 姓名
String name;
// 私钥:
PrivateKey privatekey;
// 公钥:
PublicKey publickey;
// 构造方法
public Human(String name) throws GeneralSecurityException {
// 初始化姓名
this.name = name;
// 生成公钥/私钥对:
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp = kpg.generateKeyPair();
this.privatekey = kp.getPrivate();
this.publickey = kp.getPublic();
}
// 把私钥导出为字节
public PrivateKey getPrivateKey() {
return this.privatekey;
}
// 把公钥导出为字节
public PublicKey getPublicKey() {
return this.publickey;
}
// 用公钥加密
public byte[] encrypt(byte[] message,PublicKey publickey) throws GeneralSecurityException {
// 使用公钥进行初始化
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publickey);//使用公钥初始化
return cipher.doFinal(message);
}
// 用私钥解密:
public byte[] decrypt(byte[] input) throws GeneralSecurityException {
// 使用私钥进行初始化
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, this.privatekey);//使用私钥初始化
return cipher.doFinal(input);
}
}