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 ...
随机推荐
- Codeforces B. Mouse Hunt(强连通分解缩点)
题目描述: Mouse Hunt time limit per test 2 seconds memory limit per test 256 megabytes input standard in ...
- Codeforces I. Barcelonian Distance(暴力)
题目描述: In this problem we consider a very simplified model of Barcelona city. Barcelona can be repres ...
- 一些带dga域名的恶意软件
04/02/2019 06:17下午 6,488,759 f4f242a50ba9efa1593beba6208a2508_PWS.win32.Simda_1250_DGADNS.pcap Simda ...
- poj1679The Unique MST(次小生成树模板)
次小生成树模板,别忘了判定不存在最小生成树的情况 #include <iostream> #include <cstdio> #include <cstring> ...
- Codeforces Round #560 (Div. 3) Microtransactions
Codeforces Round #560 (Div. 3) F2. Microtransactions (hard version) 题意: 现在有一个人他每天早上获得1块钱,现在有\(n\)种商品 ...
- Git的工作流程
git的工作流程为: 克隆Git资源作为工作目录 在克隆的资源上添加或者修改文件 如果别人修改了,你可以更新资源 在提交前查看修改 提交修改 在修改完成后,如果发现错误,可以撤回提交并再次修改并提交 ...
- centos7安装yum安装pip
pip是python中的一个包管理工具,可以对Python包的查找.下载.安装.卸载的作用. yum -y install epel-release yum -y install python-pip ...
- Linux学习笔记——管道PIPE
管道:当从一个进程连接数据流到另一个进程时,使用术语管道(pipe).# include <unistd.h> int pipe(int filedes[2]); //创建管道 pipe( ...
- 三.Python变量,常量,注释
1. 运行python代码. 在d盘下创建一个t1.py文件内容是: print('hello world') 打开windows命令行输入cmd,确定后 写入代码python d:t1.py 您已经 ...
- pgloader 学习(七) 从归档文件加载数据
我们可以直接从zip,tar,gzip 文件获取内容 command file 参考格式 LOAD ARCHIVE FROM /Users/dim/Downloads/GeoLiteCity-late ...