JAVA实现非对称加密:DH、RSA、ELGamal(相关API的应用)

2023-12-19 23:18

本文主要是介绍JAVA实现非对称加密:DH、RSA、ELGamal(相关API的应用),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

DH算法

import org.apache.commons.codec.binary.Hex;import javax.crypto.Cipher;
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;/*** 非对称加密 - DH算法** @author liuming* @create 2018/4/13*/
public class DH {private static String srcMsg = "imooc security dh";public static void main(String[] args) {jdkDH(srcMsg);}public static void jdkDH(String srcMsg) {try {// 初始化发送方密钥KeyPairGenerator senderKeyPairGenerator = KeyPairGenerator.getInstance("DH");senderKeyPairGenerator.initialize(512);KeyPair senderKeyPair = senderKeyPairGenerator.generateKeyPair();// 发送发公钥,需要发送给接收方byte[] senderPublicKeyEnc = senderKeyPair.getPublic().getEncoded();// 初始化接收方密钥KeyFactory receiverKeyFactory = KeyFactory.getInstance("DH");X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(senderPublicKeyEnc);PublicKey receiverPublicKey = receiverKeyFactory.generatePublic(x509EncodedKeySpec);DHParameterSpec dhParameterSpec = ((DHPublicKey) receiverPublicKey).getParams();KeyPairGenerator receiverKeyPairGenerator = KeyPairGenerator.getInstance("DH");receiverKeyPairGenerator.initialize(dhParameterSpec);KeyPair receiverKeyPair = receiverKeyPairGenerator.generateKeyPair();byte[] receiverPublicKeyEnc = receiverKeyPair.getPublic().getEncoded();// 密钥构建KeyAgreement receiverKeyAgreement = KeyAgreement.getInstance("DH");receiverKeyAgreement.init(receiverKeyPair.getPrivate());receiverKeyAgreement.doPhase(receiverPublicKey, true);SecretKey receiverDesKey = 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 senderDesKey = senderKeyAgreement.generateSecret("DES");// encryptCipher cipher = Cipher.getInstance("DES");cipher.init(Cipher.ENCRYPT_MODE, senderDesKey);byte[] bytes = cipher.doFinal(srcMsg.getBytes());// outputString encodedMsg = Hex.encodeHexString(bytes);System.out.println(encodedMsg);System.out.println(org.apache.commons.codec.binary.Base64.encodeBase64String(bytes));// decryptcipher.init(Cipher.DECRYPT_MODE, receiverDesKey);bytes = cipher.doFinal(bytes);// outputSystem.out.println(new String(bytes));} catch (Exception e) {e.printStackTrace();}}}

但是jdk1.8.0_161版本及以上,执行SecretKey receiverDesKey = receiverKeyAgreement.generateSecret("DES");会报如下错误:

java.security.NoSuchAlgorithmException: Unsupported secret key algorithm: DESat com.sun.crypto.provider.DHKeyAgreement.engineGenerateSecret(DHKeyAgreement.java:387)at javax.crypto.KeyAgreement.generateSecret(KeyAgreement.java:648)at DH.jdkDH(DH.java:53)at DH.main(DH.java:26)

需要在执行时添加VM option内容为-Djdk.crypto.KeyAgreement.legacyKDF=true再执行即可。

RSA

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;/*** RSA** @author liuming* @create 2018/4/13*/
public class RSA {private static String srcMsg = "imooc security rsa";public static void main(String[] args) {jdkRSA(srcMsg);}public static void jdkRSA(String srcMsg) {try {// 初始化发送方密钥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(Base64.encodeBase64String(rsaPublicKey.getEncoded()));System.out.println(Base64.encodeBase64String(rsaPrivateKey.getEncoded()));// 私钥加密PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());KeyFactory keyFactory = KeyFactory.getInstance("RSA");PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);// encryptCipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE, privateKey);byte[] bytes = cipher.doFinal(srcMsg.getBytes());// outputString encodedMsg = Hex.encodeHexString(bytes);System.out.println(encodedMsg);System.out.println(org.apache.commons.codec.binary.Base64.encodeBase64String(bytes));// 公钥解密X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());keyFactory = KeyFactory.getInstance("RSA");PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);// decryptcipher.init(Cipher.DECRYPT_MODE, publicKey);bytes = cipher.doFinal(bytes);// outputSystem.out.println(new String(bytes));// 公钥加密x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());keyFactory = KeyFactory.getInstance("RSA");publicKey = keyFactory.generatePublic(x509EncodedKeySpec);cipher.init(Cipher.ENCRYPT_MODE, publicKey);bytes = cipher.doFinal(srcMsg.getBytes());// outputencodedMsg = Hex.encodeHexString(bytes);System.out.println(encodedMsg);System.out.println(org.apache.commons.codec.binary.Base64.encodeBase64String(bytes));// 私钥解密pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());keyFactory = KeyFactory.getInstance("RSA");privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);// encryptcipher = Cipher.getInstance("RSA");cipher.init(Cipher.DECRYPT_MODE, privateKey);bytes = cipher.doFinal(bytes);// outputSystem.out.println(new String(bytes));} catch (Exception e) {e.printStackTrace();}}}

ELGamal

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jce.provider.BouncyCastleProvider;import javax.crypto.Cipher;
import javax.crypto.spec.DHParameterSpec;
import java.security.AlgorithmParameterGenerator;
import java.security.AlgorithmParameters;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;/*** ELGamal** @author liuming* @create 2018/4/13*/
public class ELGamal {private static String srcMsg = "imooc security elgamal";public static void main(String[] args) {jdkELGamal(srcMsg);}public static void jdkELGamal(String srcMsg) {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");System.out.println(keyPairGenerator.getProvider().getInfo());keyPairGenerator.initialize(dhParameterSpec, new SecureRandom());KeyPair keyPair = keyPairGenerator.generateKeyPair();PublicKey publicKey = keyPair.getPublic();PrivateKey privateKey = keyPair.getPrivate();System.out.println(Base64.encodeBase64String(publicKey.getEncoded()));System.out.println(Base64.encodeBase64String(privateKey.getEncoded()));// 公钥加密// encryptCipher cipher = Cipher.getInstance("ELGamal");cipher.init(Cipher.ENCRYPT_MODE, publicKey);byte[] bytes = cipher.doFinal(srcMsg.getBytes());// outputString encodedMsg = Hex.encodeHexString(bytes);System.out.println(encodedMsg);System.out.println(Base64.encodeBase64String(bytes));// 私钥解密// decryptcipher = Cipher.getInstance("ELGamal");cipher.init(Cipher.DECRYPT_MODE, privateKey);bytes = cipher.doFinal(bytes);// outputSystem.out.println(new String(bytes));} catch (Exception e) {e.printStackTrace();}}}

这篇关于JAVA实现非对称加密:DH、RSA、ELGamal(相关API的应用)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/514060

相关文章

SpringBoot3实现Gzip压缩优化的技术指南

《SpringBoot3实现Gzip压缩优化的技术指南》随着Web应用的用户量和数据量增加,网络带宽和页面加载速度逐渐成为瓶颈,为了减少数据传输量,提高用户体验,我们可以使用Gzip压缩HTTP响应,... 目录1、简述2、配置2.1 添加依赖2.2 配置 Gzip 压缩3、服务端应用4、前端应用4.1 N

Java编译生成多个.class文件的原理和作用

《Java编译生成多个.class文件的原理和作用》作为一名经验丰富的开发者,在Java项目中执行编译后,可能会发现一个.java源文件有时会产生多个.class文件,从技术实现层面详细剖析这一现象... 目录一、内部类机制与.class文件生成成员内部类(常规内部类)局部内部类(方法内部类)匿名内部类二、

SpringBoot实现数据库读写分离的3种方法小结

《SpringBoot实现数据库读写分离的3种方法小结》为了提高系统的读写性能和可用性,读写分离是一种经典的数据库架构模式,在SpringBoot应用中,有多种方式可以实现数据库读写分离,本文将介绍三... 目录一、数据库读写分离概述二、方案一:基于AbstractRoutingDataSource实现动态

Python FastAPI+Celery+RabbitMQ实现分布式图片水印处理系统

《PythonFastAPI+Celery+RabbitMQ实现分布式图片水印处理系统》这篇文章主要为大家详细介绍了PythonFastAPI如何结合Celery以及RabbitMQ实现简单的分布式... 实现思路FastAPI 服务器Celery 任务队列RabbitMQ 作为消息代理定时任务处理完整

Springboot @Autowired和@Resource的区别解析

《Springboot@Autowired和@Resource的区别解析》@Resource是JDK提供的注解,只是Spring在实现上提供了这个注解的功能支持,本文给大家介绍Springboot@... 目录【一】定义【1】@Autowired【2】@Resource【二】区别【1】包含的属性不同【2】@

springboot循环依赖问题案例代码及解决办法

《springboot循环依赖问题案例代码及解决办法》在SpringBoot中,如果两个或多个Bean之间存在循环依赖(即BeanA依赖BeanB,而BeanB又依赖BeanA),会导致Spring的... 目录1. 什么是循环依赖?2. 循环依赖的场景案例3. 解决循环依赖的常见方法方法 1:使用 @La

Java枚举类实现Key-Value映射的多种实现方式

《Java枚举类实现Key-Value映射的多种实现方式》在Java开发中,枚举(Enum)是一种特殊的类,本文将详细介绍Java枚举类实现key-value映射的多种方式,有需要的小伙伴可以根据需要... 目录前言一、基础实现方式1.1 为枚举添加属性和构造方法二、http://www.cppcns.co

使用Python实现快速搭建本地HTTP服务器

《使用Python实现快速搭建本地HTTP服务器》:本文主要介绍如何使用Python快速搭建本地HTTP服务器,轻松实现一键HTTP文件共享,同时结合二维码技术,让访问更简单,感兴趣的小伙伴可以了... 目录1. 概述2. 快速搭建 HTTP 文件共享服务2.1 核心思路2.2 代码实现2.3 代码解读3.

Elasticsearch 在 Java 中的使用教程

《Elasticsearch在Java中的使用教程》Elasticsearch是一个分布式搜索和分析引擎,基于ApacheLucene构建,能够实现实时数据的存储、搜索、和分析,它广泛应用于全文... 目录1. Elasticsearch 简介2. 环境准备2.1 安装 Elasticsearch2.2 J

Java中的String.valueOf()和toString()方法区别小结

《Java中的String.valueOf()和toString()方法区别小结》字符串操作是开发者日常编程任务中不可或缺的一部分,转换为字符串是一种常见需求,其中最常见的就是String.value... 目录String.valueOf()方法方法定义方法实现使用示例使用场景toString()方法方法