当前位置: 首页 > news >正文

Java实现RSA数字签名算法

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

package com.runsun.bfc.protocol;

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**类名:RSACoder <br/>
 * 功能:RSA签名和验签的工具类<br/>
 * 详细: <br/>
 * 作者: Tliu <br/>
 * 日期:2015年12月3日 <br/>
 */
public class RSACoder {

	/*密钥长度*/
	public final static int KEY_SIZE = 1024;
	/*签名字符集*/
	public final static String CHARSET = "UTF-8";  
	/*数字签名密钥算法*/
	public static final String KEY_ALGORITHM = "RSA";	
	/*公钥文件名*/
	public static final String PUBLIC_KEY = "bfcPub.key";	
	/*私钥文件名*/
	public static final String PRIVATE_KEY = "bfcPri.key";
	/*数字签名验证算法*/
	public static final String SIGN_ALGORITHM = "SHA256withRSA";	
	/*日志输出*/
	public static Log log = LogFactory.getLog(RSACoder.class);	
	
	/**
	 * @详细 生成签名内容
	 * @param data 等签名的消息字符串
	 * @param privateKey 私钥字符串
	 * @return
	 */
	public static String sign(String data, String privateKey){
		byte[] dataByte = null;
		String signMsg = null;
		try {
			dataByte = data.getBytes(CHARSET);
			byte[] priKey = Base64.decodeBase64(privateKey);
			signMsg = sign(dataByte, priKey);
		}  catch (Exception ex){
			ex.printStackTrace();
			log.error(ex);
		}		
		return signMsg;
	}	
	
	/**
	 * @详细 验证签名
	 * @param data 待验签的字符串
	 * @param publicKey 公钥字符串
	 * @param sign 签名内容
	 * @return
	 */
	public static boolean verify(String data, String publicKey, String sign){
		boolean rs = false;
		try {
			byte[] dataByte = data.getBytes(CHARSET);
			byte[] pubKey = Base64.decodeBase64(publicKey);
			byte[] signByte = Hex.decodeHex(sign.toCharArray());
			rs = verify(dataByte, pubKey, signByte);
		} catch (Exception ex){
			ex.printStackTrace();
			log.error(ex);
		}
		return rs;
	}
	
	private static boolean verify(byte[] data, byte[] publicKey, byte[] sign)throws Exception{			
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		PublicKey pubKey = keyFactory.generatePublic(keySpec);
		Signature signature = Signature.getInstance(SIGN_ALGORITHM);
		signature.initVerify(pubKey);
		signature.update(data);
		return signature.verify(sign);		
	}
	
	private static String sign(byte[] data, byte[] privateKey) throws Exception{		
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		PrivateKey priKey = keyFactory.generatePrivate(keySpec);
		Signature signature = Signature.getInstance(SIGN_ALGORITHM);
		signature.initSign(priKey);
		signature.update(data);
		// 生成签名的字节数组
		byte[] sign = signature.sign();
		// 转换成16进制的字符串输出
		return Hex.encodeHexString(sign).toUpperCase();		
	}
	
	/**
	 * @详细 从文件中读取密钥字符串
	 * @param filePath 文件路径
	 * @return
	 * @throws Exception
	 */
	public static String loadKey(InputStream in) {        
		try {		
	       return IOUtils.toString(in, CHARSET);
		} catch (Exception ex){			
			log.error("读取RSA密钥文件出错。");
		}
		return "";
    }  
	
	/**
	 * @详细 生成密钥对
	 * @param filePath 密钥文件保存的路径
	 * @throws Exception
	 */
	public static void initKey(String filePath) throws Exception{
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
		keyPairGen.initialize(KEY_SIZE);
		KeyPair keyPair = keyPairGen.generateKeyPair();
		RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();
		RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();		
        // 得到公钥字符串  
        String publicKeyString = Base64.encodeBase64String(publicKey.getEncoded());
        // 得到私钥字符串  
        String privateKeyString = Base64.encodeBase64String(privateKey.getEncoded());
        // 将密钥对写入到文件         
        BufferedWriter pubbw = new BufferedWriter(new FileWriter(filePath + "/" + PUBLIC_KEY));
        BufferedWriter pribw = new BufferedWriter(new FileWriter(filePath + "/" + PRIVATE_KEY));  
        log.info(PUBLIC_KEY +"\n" + publicKeyString);
        log.info(PRIVATE_KEY +"\n" + privateKeyString);
        pubbw.write(publicKeyString);
        pribw.write(privateKeyString);
        pubbw.flush();
        pubbw.close();         
        pribw.flush();
        pribw.close();        
	}	
	
	public static void main(String[] args) throws Exception {
		initKey("c:\\tmp");
		String data = "这个一段RSA签名的内容。";
		String privateKey = loadKey(new FileInputStream("c:\\tmp\\" + PRIVATE_KEY));
		String sign = sign(data, privateKey);
		log.info("签名内容:\n" + sign);
		String publicKey = loadKey(new FileInputStream("c:\\tmp\\" + PUBLIC_KEY));
		boolean rs = verify(data, publicKey, sign);
		log.info("验签状态:" + rs);
	}
}


转载于:https://my.oschina.net/liu13430/blog/541159

相关文章:

  • ASP.NET中字段赋值问题
  • 我的Git使用-资料查询,名博笔记
  • Discuz!X/数据库操作方法
  • 前端,移动开发者,UI须懂: 不同设备的之间的尺寸
  • maven发布时在不同的环境使用不同的配置文件
  • P2P通信标准协议(一)之STUN
  • 最佳实践:如何基于消息服务MNS实现严格有序队列
  • Android Material Design-Creating Lists and Cards(创建列表和卡)-(三)
  • 自己写一个切换桌面的文件
  • GTK+重拾--07 GTK+中的事件
  • eclipse报错: Unhandled event loop exception No more handles
  • CMS 回收器的两次 STW
  • Linux指令--rcp,scp
  • Asp.net 使用正则和网络编程抓取网页数据(有用)
  • Linux设备驱动程序学习 高级字符驱动程序操作[阻塞型I/O和非阻塞I/O]【转】
  • 分享一款快速APP功能测试工具
  • [deviceone开发]-do_Webview的基本示例
  • 【140天】尚学堂高淇Java300集视频精华笔记(86-87)
  • 07.Android之多媒体问题
  • Angularjs之国际化
  • eclipse(luna)创建web工程
  • js正则,这点儿就够用了
  • LeetCode541. Reverse String II -- 按步长反转字符串
  • leetcode98. Validate Binary Search Tree
  • Mac转Windows的拯救指南
  • Markdown 语法简单说明
  • 开源SQL-on-Hadoop系统一览
  • 区块链技术特点之去中心化特性
  • 深度学习中的信息论知识详解
  • 十年未变!安全,谁之责?(下)
  • 时间复杂度与空间复杂度分析
  • 微信小程序上拉加载:onReachBottom详解+设置触发距离
  • 项目管理碎碎念系列之一:干系人管理
  • 小试R空间处理新库sf
  • 学习使用ExpressJS 4.0中的新Router
  • # 再次尝试 连接失败_无线WiFi无法连接到网络怎么办【解决方法】
  • #QT项目实战(天气预报)
  • #周末课堂# 【Linux + JVM + Mysql高级性能优化班】(火热报名中~~~)
  • (二)什么是Vite——Vite 和 Webpack 区别(冷启动)
  • (附源码)spring boot网络空间安全实验教学示范中心网站 毕业设计 111454
  • (原创) cocos2dx使用Curl连接网络(客户端)
  • (转)大道至简,职场上做人做事做管理
  • ./和../以及/和~之间的区别
  • .net 4.0 A potentially dangerous Request.Form value was detected from the client 的解决方案
  • .NET/C# 的字符串暂存池
  • .NetCore实践篇:分布式监控Zipkin持久化之殇
  • .Net面试题4
  • .vimrc 配置项
  • @Builder用法
  • @RequestMapping 的作用是什么?
  • @Resource和@Autowired的区别
  • [ C++ ] STL_stack(栈)queue(队列)使用及其重要接口模拟实现
  • [1181]linux两台服务器之间传输文件和文件夹
  • [AI]文心一言出圈的同时,NLP处理下的ChatGPT-4.5最新资讯
  • [C#]科学计数法(scientific notation)显示为正常数字