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

相关文章

SpringBoot请求参数接收控制指南分享

《SpringBoot请求参数接收控制指南分享》:本文主要介绍SpringBoot请求参数接收控制指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Spring Boot 请求参数接收控制指南1. 概述2. 有注解时参数接收方式对比3. 无注解时接收参数默认位置

Go语言开发实现查询IP信息的MCP服务器

《Go语言开发实现查询IP信息的MCP服务器》随着MCP的快速普及和广泛应用,MCP服务器也层出不穷,本文将详细介绍如何在Go语言中使用go-mcp库来开发一个查询IP信息的MCP... 目录前言mcp-ip-geo 服务器目录结构说明查询 IP 信息功能实现工具实现工具管理查询单个 IP 信息工具的实现服

Python的time模块一些常用功能(各种与时间相关的函数)

《Python的time模块一些常用功能(各种与时间相关的函数)》Python的time模块提供了各种与时间相关的函数,包括获取当前时间、处理时间间隔、执行时间测量等,:本文主要介绍Python的... 目录1. 获取当前时间2. 时间格式化3. 延时执行4. 时间戳运算5. 计算代码执行时间6. 转换为指

SpringBoot基于配置实现短信服务策略的动态切换

《SpringBoot基于配置实现短信服务策略的动态切换》这篇文章主要为大家详细介绍了SpringBoot在接入多个短信服务商(如阿里云、腾讯云、华为云)后,如何根据配置或环境切换使用不同的服务商,需... 目录目标功能示例配置(application.yml)配置类绑定短信发送策略接口示例:阿里云 & 腾

SpringBoot项目中报错The field screenShot exceeds its maximum permitted size of 1048576 bytes.的问题及解决

《SpringBoot项目中报错ThefieldscreenShotexceedsitsmaximumpermittedsizeof1048576bytes.的问题及解决》这篇文章... 目录项目场景问题描述原因分析解决方案总结项目场景javascript提示:项目相关背景:项目场景:基于Spring

Spring Boot 整合 SSE的高级实践(Server-Sent Events)

《SpringBoot整合SSE的高级实践(Server-SentEvents)》SSE(Server-SentEvents)是一种基于HTTP协议的单向通信机制,允许服务器向浏览器持续发送实... 目录1、简述2、Spring Boot 中的SSE实现2.1 添加依赖2.2 实现后端接口2.3 配置超时时

Spring Boot读取配置文件的五种方式小结

《SpringBoot读取配置文件的五种方式小结》SpringBoot提供了灵活多样的方式来读取配置文件,这篇文章为大家介绍了5种常见的读取方式,文中的示例代码简洁易懂,大家可以根据自己的需要进... 目录1. 配置文件位置与加载顺序2. 读取配置文件的方式汇总方式一:使用 @Value 注解读取配置方式二

一文详解Java异常处理你都了解哪些知识

《一文详解Java异常处理你都了解哪些知识》:本文主要介绍Java异常处理的相关资料,包括异常的分类、捕获和处理异常的语法、常见的异常类型以及自定义异常的实现,文中通过代码介绍的非常详细,需要的朋... 目录前言一、什么是异常二、异常的分类2.1 受检异常2.2 非受检异常三、异常处理的语法3.1 try-

Java中的@SneakyThrows注解用法详解

《Java中的@SneakyThrows注解用法详解》:本文主要介绍Java中的@SneakyThrows注解用法的相关资料,Lombok的@SneakyThrows注解简化了Java方法中的异常... 目录前言一、@SneakyThrows 简介1.1 什么是 Lombok?二、@SneakyThrows

Java中字符串转时间与时间转字符串的操作详解

《Java中字符串转时间与时间转字符串的操作详解》Java的java.time包提供了强大的日期和时间处理功能,通过DateTimeFormatter可以轻松地在日期时间对象和字符串之间进行转换,下面... 目录一、字符串转时间(一)使用预定义格式(二)自定义格式二、时间转字符串(一)使用预定义格式(二)自