【非对称加密算法】RSA算法
一、非对称加密算法
非对称加密算法使用了两个不同的密钥:公钥和私钥。公钥是公开的,可以被任何人使用,而私钥是只有特定的人能够使用的。这种算法的加密和解密过程使用不同的密钥,因此称为非对称加密算法。
在非对称加密算法中,使用公钥进行加密,私钥进行解密。因此,它的主要优点是可以实现安全的通信,因为即使公钥被攻击者获得,攻击者也无法破解消息,因为只有使用私钥才能解密。
非对称加密算法常用于网络安全、电子邮件通信、电子支付和数字签名等领域。其中最常见的非对称加密算法是RSA算法。
二、RSA算法
该算法的基本思想是将要加密的数据转化为一个数字,然后通过公钥进行加密。只有私钥才能解密这个加密后的数字,将其转化为原始的数据。加密和解密采用的是不同的密钥,公钥可以由任何人获得,而私钥只能由算法的使用者获得。
RSA算法的应用场景包括:身份验证、加密通信、数字签名、SSL/TLS证书、VPN等。
(1)具体使用
public class Demo04 {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.getPublicKey();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.getPrivateKey();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 kpGen=KeyPairGenerator.getInstance("RSA");kpGen.initialize(1024);KeyPair kp=kpGen.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);}
}
只用使用同一个公钥-私钥对才能正常加解密!!!