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

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

水位雨量在线监测系统概述及应用介绍

在当今社会,随着科技的飞速发展,各种智能监测系统已成为保障公共安全、促进资源管理和环境保护的重要工具。其中,水位雨量在线监测系统作为自然灾害预警、水资源管理及水利工程运行的关键技术,其重要性不言而喻。 一、水位雨量在线监测系统的基本原理 水位雨量在线监测系统主要由数据采集单元、数据传输网络、数据处理中心及用户终端四大部分构成,形成了一个完整的闭环系统。 数据采集单元:这是系统的“眼睛”,

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory