RSA 签名、验证、加密、解密帮助类
import java.io.IOException; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.security.spec.EncodedKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import javax.crypto.Cipher; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; /** * RSA 签名、验证、加密、解密帮助类 * * @author sam * */ public class RsaHelper { // 签名对象 private Signature sign; private static final RsaHelper rsaHelper = new RsaHelper(); private String pubkey; private String prikey; private RsaHelper() { try { sign = Signature.getInstance("SHA1withRSA"); } catch (NoSuchAlgorithmException nsa) { System.out.println("" + nsa.getMessage()); } } public static RsaHelper getInstance() { return rsaHelper; } private PrivateKey getPrivateKey(String privateKeyStr) { try { byte[] privateKeyBytes = b64decode(privateKeyStr); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes); return keyFactory.generatePrivate(privateKeySpec); } catch (InvalidKeySpecException e) { System.out.println("Invalid Key Specs. Not valid Key files." + e.getCause()); return null; } catch (NoSuchAlgorithmException e) { System.out.println("There is no such algorithm. Please check the JDK ver." + e.getCause()); return null; } } private PublicKey getPublicKey(String publicKeyStr) { try { byte[] publicKeyBytes = b64decode(publicKeyStr); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes); return keyFactory.generatePublic(publicKeySpec); } catch (InvalidKeySpecException e) { System.out.println("Invalid Key Specs. Not valid Key files." + e.getCause()); return null; } catch (NoSuchAlgorithmException e) { System.out.println("There is no such algorithm. Please check the JDK ver." + e.getCause()); return null; } } /** * RSA 数据签名 * * @param toBeSigned * (待签名的原文) * @param priKey * (RSA私钥) * @return (返回RSA签名后的数据签名数据base64编码) */ public String signData(String toBeSigned, String priKey) { try { PrivateKey privateKey = getPrivateKey(priKey); byte[] signByte = toBeSigned.getBytes("utf-8"); Signature rsa = Signature.getInstance("SHA1withRSA"); rsa.initSign(privateKey); rsa.update(signByte); return b64encode(rsa.sign()); } catch (NoSuchAlgorithmException ex) { System.out.println(ex); } catch (InvalidKeyException in) { System.out.println("Invalid Key file.Please check the key file path" + in.getCause()); } catch (Exception se) { System.out.println(se); } return null; } /** * RSA 数据签名验证 * * @param signature * (RSA签名数据(base64编码) * @param data * (待验证的数据原文) * @param pubKey * (RSA公钥数据) * @return 返回验证结果(TRUE:验证成功;FALSE:验证失败) */ public boolean verifySignature(String signature, String data, String pubKey) { try { byte[] signByte = b64decode(signature); byte[] dataByte = data.getBytes("utf-8"); PublicKey publicKey = getPublicKey(pubKey); sign.initVerify(publicKey); sign.update(dataByte); return sign.verify(signByte); } catch (SignatureException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return false; } /** * base64编码 * * @param data * @return */ private String b64encode(byte[] data) { return new BASE64Encoder().encode(data); } /** * base64解码 * * @param data * @return */ private byte[] b64decode(String data) { try { return new BASE64Decoder().decodeBuffer(data); } catch (Exception ex) { } return null; } /** * RSA数据加密 * * @param data * (需要加密的数据) * @param pubKey * (RSA公钥) * @return 返回加密后的密文(BASE64编码) */ public String encryptData(String data, String pubKey) { try { byte[] dataByte = data.getBytes("utf-8"); PublicKey publicKey = getPublicKey(pubKey); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return b64encode(cipher.doFinal(dataByte)); } catch (Exception e) { return null; } } /** * RSA数据解密 * * @param encryptedData * (需要解密的数据base64编码数据) * @param priKey * (RSA的私钥) * @return 返回解密后的原始明文 */ public String decryptData(String encryptedData, String priKey) { try { byte[] encryData = b64decode(encryptedData); PrivateKey privateKey = getPrivateKey(priKey); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, privateKey); return new String(cipher.doFinal(encryData), "utf-8"); } catch (Exception e) { return null; } } /** * 得到私钥字符串(经过base64编码) * * @return */ public static String getPriKeyString(PrivateKey key) throws Exception { byte[] keyBytes = key.getEncoded(); String s = (new BASE64Encoder()).encode(keyBytes); return s; } /** * 得到公钥字符串(经过base64编码) * * @return */ public static String getPubKeyString(PublicKey key) throws Exception { byte[] keyBytes = key.getEncoded(); String s = (new BASE64Encoder()).encode(keyBytes); return s; } /** * 生成密钥 自动产生RSA1024位密钥 * * @throws NoSuchAlgorithmException * @throws IOException */ public void getAutoCreateRSA() throws NoSuchAlgorithmException, IOException { try { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(1024); KeyPair kp = kpg.genKeyPair(); PublicKey puk = kp.getPublic(); PrivateKey prk = kp.getPrivate(); pubkey = getPubKeyString(puk); prikey = getPriKeyString(prk); System.out.print("pubkey==:"+pubkey.replaceAll("\r", "").replaceAll("\n", "")); System.out.print("prikey==:"+prikey.replaceAll("\r", "").replaceAll("\n", "")); } catch (Exception e) { e.printStackTrace(); } } public String getPubkey() { return pubkey; } public void setPubkey(String pubkey) { this.pubkey = pubkey; } public String getPrikey() { return prikey; } public void setPrikey(String prikey) { this.prikey = prikey; } } |
RSA 签名、验证、加密、解密帮助类的更多相关文章
- php加密解密功能类
这两天突发奇想想要用php写一个对日常项目加密以及解密的功能,经过努力简单的封装了一个对php代码进行加密解密的类,一些思想也是来自于网络,初步测试用着还行,可以实现对指定项目的加密以及解密(只针对本 ...
- C# MD5加密解密帮助类
/// <summary> /// MD5加密解密帮助类 /// </summary> public static class DESHelper { ...
- php加密解密处理类
[PHP]代码 <?php /*=========================================================== = 版权协议: = GPL (The GN ...
- AES加密解密 助手类 CBC加密模式
"; string result1 = AESHelper.AesEncrypt(str); string result2 = AESHelper.AesDecrypt(result1); ...
- .Net(c#)加密解密工具类:
/// <summary> /// .Net加密解密帮助类 /// </summary> public class NetCryptoHelper { #region des实 ...
- Base64加密解密工具类
使用Apache commons codec类Base64进行加密解密 maven依赖 <dependency> <groupId>commons-codec</grou ...
- ios RSA 验签加密解密
关于公钥和私钥的生成,网上有很多本地生产的方法,我遇到的问题是,按照网上生产的方式生成7个文件,本地使用没有问题,但是和后台交互就不行了. 发现生成公钥和私钥的没有那么麻烦,使用在线生产工具就能使用, ...
- C#工具:加密解密帮助类
using System; using System.IO; using System.Security.Cryptography; using System.Text; //加密字符串,注意strE ...
- java使用RSA与AES加密解密
首先了解下,什么是堆成加密,什么是非对称加密? 对称加密:加密与解密的密钥是相同的,加解密速度很快,比如AES 非对称加密:加密与解密的秘钥是不同的,速度较慢,比如RSA 先看代码(先会用在研究) 相 ...
- PHP 服务端 和 APP 客户端 实现 RSA+AES 双向加密解密
目的:服务端和移动端双向加密解密 共有七个文件 其中包括三个类文件 lib_aes.php aes对称加密解密类 server_rsa_crypt.php 服务端RSA公钥私钥非对称加密解密类 cli ...
随机推荐
- OSPF但区域配置
原理概述 实验内容 实验拓扑 实验编址 实验步骤1.基本配置配置完成后,使用ping命令检测 2.部署单区域OSPF网络使用命令ospf创建并运行OSPF 其中1是进程号,如果没有写明进程号,则默认为 ...
- Python的csv文件(csv模块)和ini文件(configparser模块)处理
Python的csv文本文件(csv模块)和ini文本文件(configparser模块)处理 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.csv文件 1>.CSV文件 ...
- 使用Gerrit发送测试邮件
使用Gerrit发送测试邮件 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.安装HTTP服务 1>.安装HTTP服务 [root@gerrit.yinzhengjie.o ...
- Java 返回字符串中第一个不重复字符的下标 下标从0开始
比如abcdefgabdef 其中字符c和g不重复,返回c的小标,下标从0开始,那么是2 package com.example.demo; import org.testng.annotations ...
- Codeforces C. Elections(贪心枚举三分)
题目描述: C. Elections time limit per test 2 seconds memory limit per test 256 megabytes input standard ...
- MySQL:主键、外键、索引(一)
干货: 主键是关系表中记录的唯一标识.主键的选取非常重要:主键不要带有业务含义,而应该使用BIGINT自增或者GUID类型.主键也不应该允许NULL.可以使用多个列作为联合主键,但联合主键并不常用. ...
- 2019安徽省程序设计竞赛 D.自驾游(最短路)
这道题最后没过,估计是痛失省一了,现在来补一下,当时思路是对的应该是代码出了问题导致样例没过最后nc的除了2,一直WA 题意: 给一张联通图,有两个导航系统,其中一个系统认为第i条边的权值是Pi,另一 ...
- LightOJ - 1333 - Grid Coloring
链接: https://vjudge.net/problem/LightOJ-1333 题意: You have to color an M x N two dimensional grid. You ...
- 001_keil仿真
(一)参考文献:STM32F4 MDK5软件仿真 error : no 'read' permission (二)转载: 问题描述 CPU:STM32F407MDK5软件模拟提示没有读写权限,只能一 ...
- select类型的input
在选择类型一般都会用到下拉框 下拉选择类型 下拉框的类型就是在div中加一个select标签 然后在后面追加格式就行了 格式为 <select> <option value=&q ...