非对称加密算法

文章介绍了非对称加密算法的概念,使用RSA作为例子,展示了如何通过公钥加密和私钥解密信息。通过Java代码示例,解释了用户小明如何使用小红的公钥加密消息,以及小红如何用自己的私钥解密该消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是非对称加密算法?

对称加密算法          在加密和解密时使用的是同一个秘钥

非对称加密算法      需要两个密钥来进行加密和解密,这两个秘钥是公开密钥和私有密钥

非对称加密即,用户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);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lcannal

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值