Java实现非对称加密【详解】

Java实现非对称加密

  • 1. 简介
  • 2. 非对称加密算法--DH(密钥交换)
  • 3. 非对称加密算法--RSA
  • 非对称加密算法--EIGamal
  • 5. 总结
  • 6 案例
    • 6.1 案例1
    • 6.2 案例2
    • 6.3 案例3

1. 简介

公开密钥密码学(英语:Public-key cryptography)也称非对称式密码学(英语:Asymmetric cryptography)是密码学的一种算法,它需要两个密钥,一个是公开密钥,另一个是私有密钥;公钥用作加密,私钥则用作解密。使用公钥把明文加密后所得的密文,只能用相对应的私钥才能解密并得到原本的明文,最初用来加密的公钥不能用作解密。由于加密和解密需要两个不同的密钥,故被称为非对称加密;不同于加密和解密都使用同一个密钥的对称加密。公钥可以公开,可任意向外发布;私钥不可以公开,必须由用户自行严格秘密保管,绝不透过任何途径向任何人提供,也不会透露给被信任的要通信的另一方。
基于公开密钥加密的特性,它还能提供数字签名的功能,使电子文件可以得到如同在纸本文件上亲笔签署的效果。公开密钥基础建设透过信任数字证书认证机构的根证书、及其使用公开密钥加密作数字签名核发的公开密钥认证,形成信任链架构,已在TLS实现并在万维网的HTTP以HTTPS、在电子邮件的SMTP以SMTPS或STARTTLS引入。
在现实世界上可作比拟的例子是,一个传统保管箱,开门和关门都是使用同一条钥匙,这是对称加密;而一个公开的邮箱,投递口是任何人都可以寄信进去的,这可视为公钥;而只有信箱主人拥有钥匙可以打开信箱,这就视为私钥。
非对称加密过程:

在这里插入图片描述
此流程图显示非对称加密过程是单向的,其中一条密钥加密后只能用相对应的另一条密钥解密。

2. 非对称加密算法–DH(密钥交换)

密钥长度默认工作模式填充方式实现方
512~1024(64倍数)1024JDK

DH加解密应用:

package com.bity.dh;import org.apache.commons.codec.binary.Base64;import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyAgreement;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
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 java.util.Objects;import static java.lang.System.*;/*** <p>Title: JdkDh</p >* <p>Description: DH非对称算法实现 </p >* <p>Company: http://www.agree.com</p >* <p>Project: security</p >** @author <a href="mailto:weiqi@agree.com.cn">WEIQI</a>* @version 1.0* @date 2022-04-27 19:51*/
public class JdkDh {private static final String SRC = "I'm DH encryption algorithm";public static void main(String[] args) {// 解决 Unsupported secret key algorithm: DES 异常System.getProperties().setProperty("jdk.crypto.KeyAgreement.legacyKDF", "true");jdkDh();}private static void jdkDh() {try {// 初始化发送方密钥KeyPairGenerator senderKeyPairGenerator = KeyPairGenerator.getInstance("DH");senderKeyPairGenerator.initialize(512);KeyPair senderKeyPair = senderKeyPairGenerator.generateKeyPair();// 发送方密钥,发送给接收方(可以通过文件、优盘、网络等...)byte[] senderPublicKeyEnc = senderKeyPair.getPublic().getEncoded();// 初始化接收方密钥,注意在实际环境中接收方和发送方肯定不会在一个函数中KeyFactory keyFactory = KeyFactory.getInstance("DH");X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(senderPublicKeyEnc);PublicKey receiverPublicKey = keyFactory.generatePublic(x509EncodedKeySpec);DHParameterSpec dhParameterSpec = ((DHPublicKey)receiverPublicKey).getParams();KeyPairGenerator receiverKeyPairGenerator = KeyPairGenerator.getInstance("DH");receiverKeyPairGenerator.initialize(dhParameterSpec);KeyPair receiverKeyPair = receiverKeyPairGenerator.generateKeyPair();PrivateKey receiverPrivateKey = receiverKeyPair.getPrivate();byte[] receiverPublicKeyEnc = receiverKeyPair.getPublic().getEncoded();// 构建密钥KeyAgreement receiverKeyAgreement = KeyAgreement.getInstance("DH");receiverKeyAgreement.init(receiverPrivateKey);receiverKeyAgreement.doPhase(receiverPublicKey, true);SecretKey receiverSecretKey = receiverKeyAgreement.generateSecret("DES");KeyFactory senderKeyFactory = KeyFactory.getInstance("DH");x509EncodedKeySpec = new X509EncodedKeySpec(receiverPublicKeyEnc);PublicKey senderPublicKey = senderKeyFactory.generatePublic(x509EncodedKeySpec);KeyAgreement senderKeyAgreement = KeyAgreement.getInstance("DH");senderKeyAgreement.init(senderKeyPair.getPrivate());senderKeyAgreement.doPhase(senderPublicKey, true);SecretKey senderSecretKey = senderKeyAgreement.generateSecret("DES");if (Objects.equals(receiverSecretKey, senderSecretKey)) {out.println("双方密钥相同");}// 加密Cipher cipher = Cipher.getInstance("DES");cipher.init(Cipher.ENCRYPT_MODE, senderSecretKey);byte[] result = cipher.doFinal(SRC.getBytes(StandardCharsets.UTF_8));out.println("jdk dh encryption is : " + Base64.encodeBase64String(result));// 解密cipher.init(Cipher.DECRYPT_MODE, receiverSecretKey);result = cipher.doFinal(result);out.println("jdk dh decrypt is : " + new String(result));} catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidAlgorithmParameterException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {e.printStackTrace();}}
}

运行结果:

双方密钥相同
jdk dh encryption is : Be3LeXqV/q1PDEbpH62LL129gaV5Og0Eo3GY9e00B4o=
jdk dh decrypt is : I'm DH encryption algorithm

注意:由于JDK8 update 161之后,DH的密钥长度至少为512位,但DES算法密钥不能达到这样的长度,所以运行会抛出Unsupported secret key algorithm: DES异常。解决办法有两种如下:

  1. 在代码中加如下代码:
System.getProperties().setProperty("jdk.crypto.KeyAgreement.legacyKDF", "true");
  1. 在启动的时候添加JVM变量:-Djdk.crypto.KeyAgreement.legacyKDF=true
    在这里插入图片描述
    在这里插入图片描述

3. 非对称加密算法–RSA

RSA加密算法是一种非对称加密算法,在公开密钥加密和电子商业中被广泛使用。RSA是由罗纳德·李维斯特(Ron Rivest)、阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)在1977年一起提出的。当时他们三人都在麻省理工学院工作。RSA 就是他们三人姓氏开头字母拼在一起组成的。

对极大整数做因数分解的难度决定了 RSA 算法的可靠性。换言之,对一极大整数做因数分解愈困难,RSA 算法愈可靠。假如有人找到一种快速因数分解的算法的话,那么用 RSA 加密的信息的可靠性就会极度下降。但找到这样的算法的可能性是非常小的。今天只有短的 RSA 钥匙才可能被强力方式破解。到2020年为止,世界上还没有任何可靠的攻击RSA算法的方式。只要其钥匙的长度足够长,用RSA加密的信息实际上是不能被破解的。

RSA算法加密实现:

package com.bity.rsa;import org.apache.commons.codec.binary.Base64;import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.nio.charset.StandardCharsets;
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.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;import static java.lang.System.*;/*** <p>Title: JdkRsa</p >* <p>Description: RSA非对称加密算法实现 </p >* <p>Company: http://www.agree.com</p >* <p>Project: security</p >** @author <a href="mailto:weiqi@agree.com.cn">WEIQI</a>* @version 1.0* @date 2022-04-27 21:38*/
public class JdkRsa {private static final String SRC = "I'm RSA encryption algorithm";public static void main(String[] args) {jdkRsa();}/*** JDK-RSA算法实现* * @author: <a href="mailto:weiqi@agree.com.cn">WEIQI</a>* @date: 2022-04-28 0:15*/private static void jdkRsa() {try {// 初始化密钥KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");keyPairGenerator.initialize(512);KeyPair keyPair = keyPairGenerator.generateKeyPair();RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();out.println("public key is : " + Base64.encodeBase64String(rsaPublicKey.getEncoded()));out.println("private key is : " + Base64.encodeBase64String(rsaPrivateKey.getEncoded()));// 私钥加密,公钥解密 -- 加密PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());KeyFactory keyFactory = KeyFactory.getInstance("RSA");PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE, privateKey);byte[] result = cipher.doFinal(SRC.getBytes(StandardCharsets.UTF_8));out.println("私钥加密,公钥解密 -- 加密 : " + Base64.encodeBase64String(result));// 私钥加密,公钥解密 -- 解密X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());keyFactory = KeyFactory.getInstance("RSA");PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);cipher.init(Cipher.DECRYPT_MODE, publicKey);result = cipher.doFinal(result);out.println("私钥加密,公钥解密 -- 解密 : " + new String(result));// 公钥加密,私钥解密 -- 加密cipher.init(Cipher.ENCRYPT_MODE, publicKey);byte[] res = cipher.doFinal(SRC.getBytes(StandardCharsets.UTF_8));out.println("公钥加密,私钥解密 -- 加密 : " + Base64.encodeBase64String(res));// 公钥加密,私钥解密 -- 解密cipher.init(Cipher.DECRYPT_MODE, privateKey);res = cipher.doFinal(res);out.println("公钥加密,私钥解密 -- 解密 : " + new String(res));} catch (NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {e.printStackTrace();}}
}

运行结果:

public key is : MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIfDTXqCrjGHP9tCmLujavsngP8nqSHIl/JkFN8ZmQEcn48xzSXdijEG8Ssgm3SkDWICT0cW9wf3mZ+UkVxLx90CAwEAAQ==
private key is : MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAh8NNeoKuMYc/20KYu6Nq+yeA/yepIciX8mQU3xmZARyfjzHNJd2KMQbxKyCbdKQNYgJPRxb3B/eZn5SRXEvH3QIDAQABAkASyfa5E8jj1eICiE72+QDfTXJO3cBMiqRsyWkSD0rbmlL/Qv1xDDQonWM58sIR6DOBWQZ+uXbkL1VtOuZ9sgfBAiEA9IxhRwkTYA1GVUKmgZPX+7CsfUmIZi8P/r9/C29XQZUCIQCOHtBkIOupaTLPv3A4yznEidygfbL8nrLV2Xhf6wVrKQIhAJ+RdewPDPhw0QLTIaiNWrIdXv/FWl4quUolk/VXKl1dAiASpbpkGOmy7cmr9otr+EZZIlmfeT695LjEVGd19mlcmQIhAJfua+j3/PT0+z0nPIaGDvczviyl5SxmDo79rfMNpi10
私钥加密,公钥解密 -- 加密 : AiYjJSlGlz5x86mwVW/wjieG/uJsoLEqF+xRcPLzq2HL7yIrSrE3oT4wibrvUDR6kp37eHvFaAT+/wVYCreVvg==
私钥加密,公钥解密 -- 解密 : I'm RSA encryption algorithm
公钥加密,私钥解密 -- 加密 : Io2diORtKbeTz5eOOziHrqZKzS1K19U4t3YPydhM4w2LrzW7bJK/d4DQrWTBAhg8rt28OjbGcJfqd1w8MMy4iw==
公钥加密,私钥解密 -- 解密 : I'm RSA encryption algorithm

从上面例子可以看出RSA算法是支持私钥加密、公钥解密和公钥加密、私钥解密的算法。RSA也是唯一被广泛接受并实现的非对称加密算法,从某种程度来说,RSA已经成为非对称加密算法的一个标准了。

RSA数据加密传输图示:
在这里插入图片描述

非对称加密算法–EIGamal

在密码学中,ElGamal加密算法是一个基于迪菲-赫尔曼密钥交换的非对称加密算法。它在1985年由塔希尔·盖莫尔提出。GnuPG和PGP等很多密码学系统中都应用到了ElGamal算法。
ElGamal加密算法由三部分组成:密钥生成、加密和解密。

ElGamal算法加解密应用:

package com.bity.eigamal;import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.DHParameterSpec;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameterGenerator;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
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.SecureRandom;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;import static java.lang.System.out;/*** <p>Title: BouncyCastleEiGamal</p >* <p>Description: ElGamal加密算法实现 </p >* <p>Company: http://www.agree.com</p >* <p>Project: security</p >** @author <a href="mailto:weiqi@agree.com.cn">WEIQI</a>* @version 1.0* @date 2022-04-28 0:38*/
public class BouncyCastleElGamal {private static final String SRC = "I'm ElGamal encryption algorithm";public static void main(String[] args) {bcElGamal();}private static void bcElGamal() {try {Security.addProvider(new BouncyCastleProvider());AlgorithmParameterGenerator algorithmParameterGenerator = AlgorithmParameterGenerator.getInstance("ElGamal");algorithmParameterGenerator.init(256);AlgorithmParameters algorithmParameters = algorithmParameterGenerator.generateParameters();DHParameterSpec dhParameterSpec = algorithmParameters.getParameterSpec(DHParameterSpec.class);// 初始化密钥KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ElGamal");keyPairGenerator.initialize(dhParameterSpec, new SecureRandom());KeyPair keyPair = keyPairGenerator.generateKeyPair();PublicKey elGamalPublicKey = keyPair.getPublic();PrivateKey elGamalPrivateKey = keyPair.getPrivate();out.println("public key is : " + Base64.encodeBase64String(elGamalPublicKey.getEncoded()));out.println("private key is : " + Base64.encodeBase64String(elGamalPrivateKey.getEncoded()));// 公钥加密,私钥解密 -- 加密X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(elGamalPublicKey.getEncoded());KeyFactory keyFactory = KeyFactory.getInstance("ElGamal");PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);Cipher cipher = Cipher.getInstance("ElGamal");cipher.init(Cipher.ENCRYPT_MODE, publicKey);byte[] result = cipher.doFinal(SRC.getBytes(StandardCharsets.UTF_8));out.println("私钥加密,公钥解密 -- 解密 : " + Base64.encodeBase64String(result));// 公钥加密,私钥解密 -- 解密PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(elGamalPrivateKey.getEncoded());keyFactory = KeyFactory.getInstance("ElGamal");PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);cipher.init(Cipher.DECRYPT_MODE, privateKey);result = cipher.doFinal(result);out.println("私钥加密,公钥解密 -- 加密 : " + new String(result));} catch (NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | InvalidParameterSpecException | InvalidAlgorithmParameterException e) {e.printStackTrace();}}
}

运行结果:

 
public key is : MHYwTwYGKw4HAgEBMEUCIQCxvT1SNSrVl1/8KpvPhaE1MKiaXOHWk5SACDd39SfnHwIgQ5O8oKi9mIKhEDOCKwvYB+mozFgvmuoipw/ZDl6xCicDIwACIBh0K6bn2mtdvmiSMJj/HDlotAGOmTRFMZs+PFoIobQG
private key is : MHgCAQAwTwYGKw4HAgEBMEUCIQCxvT1SNSrVl1/8KpvPhaE1MKiaXOHWk5SACDd39SfnHwIgQ5O8oKi9mIKhEDOCKwvYB+mozFgvmuoipw/ZDl6xCicEIgIge9eM9ELM12n6bQKkj8iBtIXjvPeN5mwX9clNriqfSsA=
私钥加密,公钥解密 -- 解密 : e39h4LkKXQn1EIXdDkIxmWiB2pwgO5dZJcNfSmlXqS07SrW1VSLrx0L3RhdWm8hPLaqBZieR5quU/7oTzH/uuA==
私钥加密,公钥解密 -- 加密 : I'm ElGamal encryption algorithm

ElGamal数据加密传输图示:
在这里插入图片描述

5. 总结

对称密码是指在加密和解密时使用同一个密钥的方式,公钥密码则是指在加密和解密时使用不同密钥的方式。
对称密钥加密牵涉到密钥管理的问题,尤其是密钥交换,它需要通信双方在通信之前先透过另一个安全的渠道交换共享的密钥,才可以安全地把密文透过不安全的渠道发送;对称密钥一旦被窃,其所作的加密将即时失效;而在互联网,如果通信双方分隔异地而素未谋面,则对称加密事先所需要的“安全渠道”变得不可行;非对称加密则容许加密公钥随便散布,解密的私钥不发往任何用户,只在单方保管;如此,即使公钥在网上被截获,如果没有与其匹配的私钥,也无法解密,极为适合在互联网上使用。
另一方面,公钥解密的特性可以形成数字签名,使数据和文件受到保护并可信赖;如果公钥透过数字证书认证机构签授成为电子证书,更可作为数字身份的认证,这都是对称密钥加密无法实现的。不过,公钥加密在在计算上相当复杂,性能欠佳、远远不比对称加密;因此,在一般实际情况下,往往通过公钥加密来随机创建临时的对称秘钥,亦即对话键,然后才通过对称加密来传输大量、主体的数据。

6 案例

6.1 案例1

package com.test;import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;public class MyTest02 {public static void main(String[] args) throws Exception {MyTest02 myTest02 = new MyTest02();myTest02.test1(); //生成密钥String jm = myTest02.test2(); //通过公钥加密myTest02.test3(jm); //通过私钥解密}public void test1() throws NoSuchAlgorithmException {// 初始化密钥KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");keyPairGenerator.initialize(512);KeyPair keyPair = keyPairGenerator.generateKeyPair();RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();System.out.println("public key is : " + Base64.getEncoder().encodeToString(rsaPublicKey.getEncoded()));System.out.println("private key is : " + Base64.getEncoder().encodeToString(rsaPrivateKey.getEncoded()));}public String test2() throws Exception {String SRC = "I'm RSA encryption algorithm";String pubKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIOz/OOCWjqI/6gssHGA/cHiJnR3hNdp230g1x7Y/aWzFc8WrQnjlX4vtdzgDAlz4gMTLkLdU30CAwEAAQ==";byte[] pubKeyDecode = Base64.getDecoder().decode(pubKey);X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(pubKeyDecode);KeyFactory keyFactory = KeyFactory.getInstance("RSA");PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE, publicKey);byte[] res = cipher.doFinal(SRC.getBytes(StandardCharsets.UTF_8));System.out.println("公钥加密,私钥解密 -- 加密 : " + Base64.getEncoder().encodeToString(res));return Base64.getEncoder().encodeToString(res);}public void test3 (String data) throws Exception {String pvtKey = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAg7P844JaOoj/qCywcYD9weImdHeE12nbfSDXHtj9pbMVzxatCeOVfi/Q90Q6mF+S3wK13OAMCXPiAxMuQt1TfQIDAQABAkAbcnUvjMj1DfwJtlaHMRSxRUoyV34tznfZmfB7E0m5MEwfA=";byte[] pvtDecoder = Base64.getDecoder().decode(pvtKey);PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(pvtDecoder);KeyFactory keyFactory = KeyFactory.getInstance("RSA");PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.DECRYPT_MODE, privateKey);byte[] decode = Base64.getDecoder().decode(data);byte[] res = cipher.doFinal(decode);System.out.printf("公钥加密,私钥解密 -- 解密: " + new String(res));}

6.2 案例2

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
import javax.crypto.Cipher;
public class RSAEncryptionExample {public static void main(String[] args) throws Exception {String data = "Hello, world!";KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();PublicKey publicKey = keyPair.getPublic();PrivateKey privateKey = keyPair.getPrivate();Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE, publicKey);byte[] encryptedData = cipher.doFinal(data.getBytes());System.out.println(Base64.getEncoder().encodeToString(encryptedData));cipher.init(Cipher.DECRYPT_MODE, privateKey);byte[] decryptedData = cipher.doFinal(encryptedData);System.out.println(new String(decryptedData));}
}

6.3 案例3

import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;/*** Description :** @author : * Date : Created in 20:32 2023/3/13* @version :*/
public class RSATest {public static void main(String[] args)throws Exception {//获取RSA算法的密钥生成器对象KeyPairGenerator keyPairGen =KeyPairGenerator.getInstance("RSA");//设定密钥长度为1024位keyPairGen.initialize(1024);//生成"密钥对"对象KeyPair keyPair = keyPairGen.generateKeyPair();//分别获取私钥和公钥对象RSAPrivateKey PrivateKey =(RSAPrivateKey) keyPair.getPrivate();RSAPublicKey publicKey =(RSAPublicKey) keyPair.getPublic();//执行加密和解密过程String InData="Hello World!";//得到要加密内容的数组byte[] byteInData =InData.getBytes("UTF-8");//用公钥加密byte[] cipherByte= encrypt(publicKey,byteInData);  //RSA加密String cipher=new String(encode(cipherByte));   //Base64a编码System.out.println("公钥加密,密文:"+cipher);//用私钥解密byte[] plain =decrypt(PrivateKey,decode(cipher)); //Base64a解码System.out.println("私钥解密,明文:"+new String(plain)); //RSA解密}/*** 编码* @param txt byte字节数组* @return encode Base64编码*/public static byte[] encode(byte[] txt) {return org.apache.commons.codec.binary.Base64.encodeBase64(txt);}/*** 解码* @param txt 编码后的byte* @return decode Base64解码*/public static byte[] decode(String txt){return org.apache.commons.codec.binary.Base64.decodeBase64(txt);}/*** 公钥加密* @param publicKey 公钥* @param obj 明文* @return byte[] 密文*/public static byte[] encrypt(RSAPublicKey publicKey, byte[] obj) throws Exception {Cipher cipher =Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE,publicKey);//返回加密后的内容return cipher.doFinal(obj);}/*** 私钥解密* @param privateKey 公钥* @param obj 密文* @return byte[] 密文*/public static byte[] decrypt(RSAPrivateKey privateKey, byte[] obj)throws Exception {Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.DECRYPT_MODE, privateKey);//返回解密后的数组return cipher.doFinal(obj);}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/317801.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

轻量级.Net Core服务注册工具CodeDi发布啦

为什么做这么一个工具因为我们的系统往往时面向接口编程的,所以在开发Asp .net core项目的时候,一定会有大量大接口及其对应的实现要在ConfigureService注册到ServiceCollection中,传统的做法是加了一个服务,我们就要注册一次(service.AddService()),又比如,当一个接口有多个实…

2020 CSP-S 游记

迟到的游记总述T1&#xff1a;儒略日T2&#xff1a;动物园T3&#xff1a;函数调用T4&#xff1a;贪吃蛇总结总述 可能是有了去年第一次的狂炸经历&#xff0c;很明显的就是在考试策略上的提升 头不铁了&#xff0c;手不残了&#xff0c;心态稳了&#xff0c;分也多了 T1&…

NOIP2018洛谷P5021:修建赛道

没有证明的贪心就是乱搞 解析 把标签写在题面上的一道题… 显然要二分答案然后看能不能分出来m个 关键策略是每个结点内部尽可能的多匹配的前提下&#xff0c;给父亲传一个最大的 这不纪念品分组&#xff1f; 然后我就无脑的敲了个双指针的贪心上去 然后就WA掉了qwq &#xf…

Weird Flecks, But OK

Weird Flecks, But OK 题意&#xff1a; 给出三维坐标中的 n 个点&#xff0c;求一个圆柱的最小直径&#xff0c;该圆柱垂直于坐标平面且能覆盖住所有点 题解&#xff1a; 本人最不擅长计算几何&#xff0c;比赛时没做出来。。。 其实就是将n个点投影到三个坐标平面&#x…

P7516-[省选联考2021A/B卷]图函数【bfs】

正题 题目链接:https://www.luogu.com.cn/problem/P7516 题目大意 懒了&#xff0c;直接抄题意了 对于一张 nnn 个点 mmm 条边的有向图 GGG&#xff08;顶点从 1∼n1 \sim n1∼n 编号&#xff09;&#xff0c;定义函数 f(u,G)f(u, G)f(u,G)&#xff1a; 初始化返回值 cnt0cn…

NOIP2022 游记

开个坑&#xff0c;希望能填上

【.NET Core项目实战-统一认证平台】第十三章 授权篇-如何强制有效令牌过期

上一篇我介绍了JWT的生成验证及流程内容&#xff0c;相信大家也对JWT非常熟悉了&#xff0c;今天将从一个小众的需求出发&#xff0c;介绍如何强制令牌过期的思路和实现过程。.netcore项目实战交流群&#xff08;637326624&#xff09;&#xff0c;有兴趣的朋友可以在群里交流讨…

[2020-11-24 contest]糖果机器(二维偏序),手套(状压dp),甲虫(区间dp),选举(线段树 最大子段和)

文章目录T1&#xff1a;糖果机器solutioncodeT2&#xff1a;手套solutioncodeT3&#xff1a;甲虫solutioncodeT4&#xff1a;选举solutioncodeT1&#xff1a;糖果机器 solution 考虑从第iii个糖果出发能到达第jjj个&#xff0c;则有Tj−Ti≥∣Sj−Si∣T_j-T_i≥|S_j-S_i|Tj​…

模板:树上启发式合并(dsu on tree)

文章目录解析step1&#xff1a;树剖step2&#xff1a;求出轻儿子的答案&#xff08;不继承&#xff09;step3&#xff1a;求出重儿子的答案&#xff08;继承&#xff09;step4&#xff1a;加入自己的答案、合并轻儿子的答案并记录答案step5&#xff1a;清空复杂度分析代码所谓树…

New Maths

New Maths 题意&#xff1a; 定义一个不进位的乘法运算 ⊗&#xff0c;先给出一个n&#xff0c;判断是否存在a&#xff0c;满足a ⊗ a n n的长度最多是25 题解&#xff1a; 17 * 17正常等于289 17 ⊗ 17 149 如果a的长度为x&#xff0c;那么最后得到的n的长度len是2x-1 倒…

CF827F-Dirty Arkady‘s Kitchen【堆】

正题 题目链接:https://www.luogu.com.cn/problem/CF827F 题目大意 给出nnn个点mmm条边的一张无向图&#xff0c;每条边只有在时刻[li,ri)[l_i,r_i)[li​,ri​)时候才能通过&#xff0c;且通过时间为111&#xff0c;你不能在一个点处停留&#xff0c;求111走到nnn的最短时间。…

linux一些好用的命令和快捷键

以后知道了再加吧 ctrl-alt-T&#xff1a;yjx之殇 快捷键 ctrl-x h&#xff1a;全选 ctrl-x 3&#xff1a;左右分栏 ctrl-x 1&#xff1a;还原1栏 ctrl-s&#xff1a;查找 alt-%&#xff1a;替换 配置 ctrl-xctrl-f :~/.emacs: (global-set-key (kbd “C-a”) mark-whole-buffe…

ASP.NET Core 数据加解密的一些坑

点击蓝字关注我ASP.NET Core 给我们提供了自带的Data Protection机制&#xff0c;用于敏感数据加解密&#xff0c;带来方便的同时也有一些限制可能引发问题&#xff0c;这几天我就被狠狠爆了一把我的场景我的博客系统有个发送邮件通知的功能&#xff0c;因此需要配置一个邮箱账…

[2020-11-28 contest]素数(数学),精灵(区间dp),农夫约的假期(结论),观察(树链剖分lca+set)

文章目录素数solutioncode精灵solutioncode农夫约的假期solutioncode观察solutionsolutioncode素数 solution 通过观察可得一个结论 对于两个相邻的质数p1,p2(p1<p2)p_1,p_2\ (p_1<p_2)p1​,p2​ (p1​<p2​) 对于x∈[p1,p2)x∈[p_1,p_2)x∈[p1​,p2​)&#xff0c;都…

B. Box Fitting

B. Box Fitting 题意&#xff1a; 现在有n个长方形&#xff0c;宽均为1&#xff0c;现在有一个底为m的容器&#xff0c;问将长方形放入其中&#xff0c;所用容器的最小宽度是多少 &#xff08;长方形必须长朝下放置详细如图&#xff09; 题解&#xff1a; 比赛时脑子抽了。…

AT2371-[AGC013E]Placing Squares【矩阵乘法】

正题 题目链接:https://www.luogu.com.cn/problem/AT2371 题目大意 给出nnn和mmm个数bbb。 求所有满足以下要求的序列aaa 和为nnn对于所有bib_ibi​不存在任何一个前缀和为bib_ibi​。 一个序列的贡献为所有数的二次方和&#xff0c;求所有合法序列的贡献。 1≤n≤109,1≤m…

博客搬迁通知

地址 CSDN 上所有博客由于更新困难的问题&#xff0c;已经全部搬迁到 我的博客园&#xff0c;如果您发现博客有许多缺失部分&#xff0c;请到 cnblogs 上查看&#xff0c;谢谢&#xff01;

洛谷P1074:靶形数独(搜索、剪枝)

解析 搜索题都是玄学 本题暴搜人人都会写&#xff0c;关键是如何剪枝 我一直在最优性剪枝上纠结qwq 但仔细想想&#xff0c;不同方案的权值差别没有那么大 再加上剪枝时不可避免的要放弃一些准确度 所以最优性剪枝在本题可能确实没有太大的作用 考虑我们平时如何玩数独 肯定是…

人工智能第六课:如何做研究

这是我学习 Data Science Research Methods 这门课程的笔记。这门课程的讲师是一名教授和数据科学家&#xff0c;可能因为他既有理论背景&#xff0c;又有实践经验&#xff0c;所以整个课程听下来还比较舒服&#xff0c;学到了一些不错的理论知识。这门课比较系统地介绍了什么…

CF889E-Mod Mod Mod【dp】

正题 题目链接:https://www.luogu.com.cn/problem/CF889E 题目大意 给出一个长度为nnn的序列aaa&#xff0c;定义函数f(i,x)f(i,x)f(i,x)有 f(n,x)xmodanf(n,x)x\bmod a_nf(n,x)xmodan​ f(i,x)(xmodai)f(xmodai)(i<n)f(i,x)(x\bmod a_i)f(x\bmod a_i)(i<n)f(i,x)(xmod…