package cn.daenx.my.util;

import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map; /**
* RSA公私钥生成
*
* @author DaenMax
*/
public class SHA256withRSAUtils { private static final String KEY_ALGORITHM = "RSA";
private static final String PUBLIC_KEY = "publicKey";
private static final String PRIVATE_KEY = "privateKey";
public static final String SIGNATURE_ALGORITHM = "SHA256withRSA";
public static final String ENCODE_ALGORITHM = "SHA-256"; /**
* 生成公、私钥
* 根据需要返回String或byte[]类型
*
* @param keySize 秘钥长度,1024、2048、4096等
* @return
*/
private static Map<String, String> createRSAKeys(int keySize) {
Map<String, String> keyPairMap = new HashMap<String, String>();
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGenerator.initialize(keySize, new SecureRandom());
KeyPair keyPair = keyPairGenerator.generateKeyPair(); PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate(); String publicKeyValue = Base64.getEncoder().encodeToString(publicKey.getEncoded());
String privateKeyValue = Base64.getEncoder().encodeToString(privateKey.getEncoded()); keyPairMap.put(PUBLIC_KEY, publicKeyValue);
keyPairMap.put(PRIVATE_KEY, privateKeyValue);
} catch (Exception e) {
e.printStackTrace();
}
return keyPairMap;
} /**
* 解码PublicKey
*
* @param key
* @return
*/
public static PublicKey getPublicKey(String key) {
try {
byte[] byteKey = Base64.getDecoder().decode(key);
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(byteKey);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
return keyFactory.generatePublic(x509EncodedKeySpec);
} catch (Exception e) {
e.printStackTrace();
}
return null;
} /**
* 解码PrivateKey
*
* @param key
* @return
*/
public static PrivateKey getPrivateKey(String key) {
try {
byte[] byteKey = Base64.getDecoder().decode(key);
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(byteKey);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); return keyFactory.generatePrivate(pkcs8EncodedKeySpec);
} catch (Exception e) {
e.printStackTrace();
}
return null;
} /**
* 签名
*
* @param key 私钥
* @param requestData 请求参数
* @return
*/
public static String sign(String key, String requestData) {
String signature = null;
byte[] signed = null;
try {
PrivateKey privateKey = getPrivateKey(key); Signature Sign = Signature.getInstance(SIGNATURE_ALGORITHM);
Sign.initSign(privateKey);
Sign.update(requestData.getBytes());
signed = Sign.sign(); signature = Base64.getEncoder().encodeToString(signed);
System.out.println("===签名结果:" + signature);
} catch (Exception e) {
e.printStackTrace();
}
return signature;
} /**
* 验签
*
* @param key 公钥
* @param requestData 请求参数
* @param signature 签名
* @return
*/
public static boolean verifySign(String key, String requestData, String signature) {
boolean verifySignSuccess = false;
try {
PublicKey publicKey = getPublicKey(key); Signature verifySign = Signature.getInstance(SIGNATURE_ALGORITHM);
verifySign.initVerify(publicKey);
verifySign.update(requestData.getBytes()); verifySignSuccess = verifySign.verify(Base64.getDecoder().decode(signature));
System.out.println("===验签结果:" + verifySignSuccess);
} catch (Exception e) {
e.printStackTrace();
}
return verifySignSuccess;
} public static void main(String[] args) {
Map<String, String> keyPairMap = createRSAKeys(1024); String publicKey = keyPairMap.get(PUBLIC_KEY);
System.out.println("生成公钥: " + publicKey); String privateKey = keyPairMap.get(PRIVATE_KEY);
System.out.println("生成私钥: " + privateKey); System.out.println("===开始RSA公、私钥测试===");
String str = "alpha=001&beta=002&gamma=003";
String sign = sign(privateKey, str); verifySign(publicKey, str, sign);
}
}

java RSA公私钥生成工具类的更多相关文章

  1. Python rsa公私钥生成 rsa公钥加解密(分段加解密)-私钥加签验签实战

    一般现在的SAAS服务提供现在的sdk或api对接服务都涉及到一个身份验证和数据加密的问题.一般现在普遍的做法就是配置使用非对称加密的方式来解决这个问题,你持有SAAS公司的公钥,SAAS公司持有你的 ...

  2. Java 二维码生成工具类

    /** * 二维码 工具 * * @author Rubekid * */ public class QRcodeUtils { /** * 默认version */ public static fi ...

  3. RSA公私钥生成与使用

    参考 KeyStore 简述 Keytool 简述 Certificate Chain (证书链) 简述 详解RSA加密算法

  4. java生成RSA公私钥字符串,简单易懂

    java生成RSA公私钥字符串,简单易懂   解决方法: 1.下载bcprov-jdk16-140.jar包,参考:http://www.yayihouse.com/yayishuwu/chapter ...

  5. Openssl生成RSA公私钥以及将公钥转换成C#支持的格式

    Openssl生成RSA公私钥以及将公钥转换成C#支持的格式 1.RSA算法介绍 RSA算法是一种非对称密码算法,所谓非对称,就是指该算法需要一对密钥,使用其中一个加密,则需要用另一个才能解密.RSA ...

  6. java中excel导入\导出工具类

    1.导入工具 package com.linrain.jcs.test; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import ...

  7. ZXing 二维码解析生成工具类

    原文:http://www.open-open.com/code/view/1455848023292 import com.google.zxing.*; import com.google.zxi ...

  8. Java操作文件夹的工具类

    Java操作文件夹的工具类 import java.io.File; public class DeleteDirectory { /** * 删除单个文件 * @param fileName 要删除 ...

  9. Java汉字转成汉语拼音工具类

    Java汉字转成汉语拼音工具类,需要用到pinyin4j.jar包. import net.sourceforge.pinyin4j.PinyinHelper; import net.sourcefo ...

  10. java中定义一个CloneUtil 工具类

    其实所有的java对象都可以具备克隆能力,只是因为在基础类Object中被设定成了一个保留方法(protected),要想真正拥有克隆的能力, 就需要实现Cloneable接口,重写clone方法.通 ...

随机推荐

  1. ABAQUS 中的一些约定

    目录 自由度notation Axisymmetric elements Activation of degrees of freedom Internal variables in Abaqus/S ...

  2. 关于valueOf的一点思考

    官方描述:返回值为该对象的原始值. 来源:Object.prototype,所以所有js对象都继承了此方法,根据犀牛书第六版的描述,对象转换为数字和字符串的时候的过程是不一样的. 对象 -> 字 ...

  3. websocket: the client is not using the websocket protocol: ‘upgrade’ token not found in ‘Connection’ head,客户端没有使用websocket协议:'upgrade'令牌未在'Connection'头中找到

    错误分析 websocket: the client is not using the websocket protocol: 'upgrade' token not found in 'Connec ...

  4. OpnenHarmony 开源鸿蒙北向开发——2.第一个工程HelloWorld

    ​ 一.新建项目 我们打开IDE后,选择新建项目 选择这一个 设置参数 设置完成后选择Finish 项目创建后会自动下载一些东西,不用担心 二.运行 我们先什么都不用管,直接运行 先设置设备,我们这里 ...

  5. IvorySQL 增量备份与合并增量备份功能解析

    1. 概述 IvorySQL v4 引入了块级增量备份和增量备份合并功能,旨在优化数据库备份与恢复流程.通过 pg_basebackup 工具支持增量备份,显著降低了存储需求和备份时间.同时,pg_c ...

  6. C# 中合并2个 Dictionary

    内置方法 using System.Collections.Generic; using System.Linq; Dictionary<string, object> dicA = ne ...

  7. BuildAssetBundleOption.DisableWriteTypeTree和粒度问题

  8. 配置Thymeleaf模板引擎

    1).thymeleaf-starter: 关闭缓存 2).静态资源都放在static文件夹下就可以按照路径直接访问 3).页面放在templates下,直接访问 springboot ,访问项目的时 ...

  9. C#高性能开发之类型系统:从C# 7.0 到C# 14的类型系统演进全景

    自C# 7.0以来,C#语言在类型系统方面引入了众多新数据类型.类型构造和语言特性,以提升性能.类型安全性和开发效率.本文全面整理了从C# 7.0到C# 14.0(截至2025年4月,C# 14.0为 ...

  10. springboot加载配置文件的优先级

    如果springboot有多个配置文件,则加载顺序为项目根路径下的/config > 项目根路径 > resources/config > resources目录下 图示: 如果两个 ...