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 ...
随机推荐
- [I2C].I2C总线详解
转自:https://www.cnblogs.com/BitArt/archive/2013/05/27/3101037.html 一. 基本信息 1. 概述 I²C 是Inter-Integrate ...
- 19.centos7基础学习与积累-005-命令总结01
从头开始积累centos7系统运用 大牛博客:https://blog.51cto.com/yangrong/p5 1.查看命令帮助的方法: --help 适用于一般命令,非内置命令 man 适用于 ...
- python3学习之lambda+sort
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] >>> pairs.sort(key ...
- CentOS6.5配置
关闭防火墙 查看防火墙状态 /etc/init.d/iptables status 停止 /etc/init.d/iptables stop 开机不启动 chkconfig iptables off ...
- 【深入ASP.NET原理系列】--Asp.Net Mvc和Asp.Net WebForm实际上共用一套ASP.NET请求管道
.NET FrameWork4在系统全局配置文件(如在如下目录中C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config) 中添加了一个名字叫Url ...
- “Another git process seems to be running in this repository...”Git此问题解决
Git中显示:Another git process seems to be running in this repository, e.g.an editor opened by 'git comm ...
- GlusterFS Dispersed Volume(纠错卷)总结
https://blog.csdn.net/daydayup_gzm/article/details/52748812 一.概念 Dispersed Volume是基于ErasureCodes(纠错码 ...
- 四行公式推完神经网络BP
据说多推推公式可以防止老年痴呆,(●ˇ∀ˇ●) 偶尔翻到我N年前第一次推导神经网络的博客居然四页纸,感慨毅力! http://blog.sina.com.cn/s/blog_1442877660102 ...
- Tensorflow细节-P319-使用GPU基本的操作
如果什么都不加,直接运行装了GPU的Tensorflow,结果是这样子的 import tensorflow as tf a = tf.constant([1.0, 2.0, 3.0], shape= ...
- RESTful API Design: 13 Best Practices to Make Your Users Happy
RESTful API Design: 13 Best Practices to Make Your Users Happy First step to the RESTful way: make s ...