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 ...
随机推荐
- C#锁对象代码
private static readonly object SequenceLock = new object(); private static readonly object SequenceL ...
- beta版本——第一次冲刺
第一次冲刺 (1)SCRUM部分☁️ ✨成员描述: 姓名 李星晨 完成了哪个任务 增加了个人中心返回主页按钮 花了多少时间 1h 还剩余多少时间 1h 遇到什么困难 没有遇到问题 这两天解决的进度 1 ...
- 解决Invalid character found in the request target. The valid characters are defined in RFC 7230 and RF
通过这里的回答,我们可以知道: Tomcat在 7.0.73, 8.0.39, 8.5.7 版本后,添加了对于http头的验证. 具体来说,就是添加了些规则去限制HTTP头的规范性 参考这里 具体来说 ...
- Python 通过lxml 解析html页面自动组合xpath实例
#coding:utf-8 ''' @author: li.liu ''' from selenium import webdriver from selenium.webdriver.common. ...
- element ui 中的 resetFields() 报错'resetFields' of undefined
每次做各种form表单时,首先要注意的是初始化,但是刚开始若没有仔细看文档,则会自己写个方法将数据设置为空,但是这样就会出现一个问题,表单内存在各种验证,假如是一个弹框内有form表单,弹框出现就执行 ...
- python中的glob模块的使用
最近常常用到glob模块,这里做一个简单小结: 用它可以查找符合特定规则的文件路径名.跟使用windows下的文件搜索差不多.查找文件只用到三个匹配符:”*”, “?”, “[]”.”*”匹配0个或多 ...
- [PWA] Storage information for PWA application
Be careful with the storage use cases, free the storage when it is necessary.
- omnibus-gitlab 架构学习
omnibus-gitlab是gitlab 团队fork 自chef 的omnibus 项目,同时做了一些自定义的开发,omnibus-gitlab 简化了 gitlab 的部署以及维护,同时里边集成 ...
- Html结构标准
< ! doctype html> 声明文档类型 <html> 根标签 <head> 头标签 <title></title> 标题标签 &l ...
- .NET API Gateway Ocelot 介绍
项目:https://github.com/ThreeMammals/Ocelot Windows (AppVeyor) Linux & OSX (Travis) Windows Ma ...