import org.apache.commons.codec.binary.Base64;

 import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map; /**
* RSA加密和解密工具
*
* @Author: syj
* @CreateDate: 2018/7/20 16:52
*/
public class RSAUtil { /**
* 数字签名,密钥算法
*/
private static final String RSA_KEY_ALGORITHM = "RSA"; /**
* 数字签名签名/验证算法
*/
private static final String SIGNATURE_ALGORITHM = "MD5withRSA"; /**
* RSA密钥长度,RSA算法的默认密钥长度是1024密钥长度必须是64的倍数,在512到65536位之间
*/
private static final int KEY_SIZE = 1024; /**
* 生成密钥对
*/
private static Map<String, String> initKey() throws Exception {
KeyPairGenerator keygen = KeyPairGenerator.getInstance(RSA_KEY_ALGORITHM);
SecureRandom secrand = new SecureRandom();
/**
* 初始化随机产生器
*/
secrand.setSeed("initSeed".getBytes());
/**
* 初始化密钥生成器
*/
keygen.initialize(KEY_SIZE, secrand);
KeyPair keys = keygen.genKeyPair(); byte[] pub_key = keys.getPublic().getEncoded();
String publicKeyString = Base64.encodeBase64String(pub_key); byte[] pri_key = keys.getPrivate().getEncoded();
String privateKeyString = Base64.encodeBase64String(pri_key); Map<String, String> keyPairMap = new HashMap<>();
keyPairMap.put("publicKeyString", publicKeyString);
keyPairMap.put("privateKeyString", privateKeyString); return keyPairMap;
} /**
* 密钥转成字符串
*
* @param key
* @return
*/
public static String encodeBase64String(byte[] key) {
return Base64.encodeBase64String(key);
} /**
* 密钥转成byte[]
*
* @param key
* @return
*/
public static byte[] decodeBase64(String key) {
return Base64.decodeBase64(key);
} /**
* 公钥加密
*
* @param data 加密前的字符串
* @param publicKey 公钥
* @return 加密后的字符串
* @throws Exception
*/
public static String encryptByPubKey(String data, String publicKey) throws Exception {
byte[] pubKey = RSAUtil.decodeBase64(publicKey);
byte[] enSign = encryptByPubKey(data.getBytes(), pubKey);
return Base64.encodeBase64String(enSign);
} /**
* 公钥加密
*
* @param data 待加密数据
* @param pubKey 公钥
* @return
* @throws Exception
*/
public static byte[] encryptByPubKey(byte[] data, byte[] pubKey) throws Exception {
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKey);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
} /**
* 私钥加密
*
* @param data 加密前的字符串
* @param privateKey 私钥
* @return 加密后的字符串
* @throws Exception
*/
public static String encryptByPriKey(String data, String privateKey) throws Exception {
byte[] priKey = RSAUtil.decodeBase64(privateKey);
byte[] enSign = encryptByPriKey(data.getBytes(), priKey);
return Base64.encodeBase64String(enSign);
} /**
* 私钥加密
*
* @param data 待加密的数据
* @param priKey 私钥
* @return 加密后的数据
* @throws Exception
*/
public static byte[] encryptByPriKey(byte[] data, byte[] priKey) throws Exception {
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKey);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return cipher.doFinal(data);
} /**
* 公钥解密
*
* @param data 待解密的数据
* @param pubKey 公钥
* @return 解密后的数据
* @throws Exception
*/
public static byte[] decryptByPubKey(byte[] data, byte[] pubKey) throws Exception {
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKey);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(data);
} /**
* 公钥解密
*
* @param data 解密前的字符串
* @param publicKey 公钥
* @return 解密后的字符串
* @throws Exception
*/
public static String decryptByPubKey(String data, String publicKey) throws Exception {
byte[] pubKey = RSAUtil.decodeBase64(publicKey);
byte[] design = decryptByPubKey(Base64.decodeBase64(data), pubKey);
return new String(design);
} /**
* 私钥解密
*
* @param data 待解密的数据
* @param priKey 私钥
* @return
* @throws Exception
*/
public static byte[] decryptByPriKey(byte[] data, byte[] priKey) throws Exception {
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKey);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
} /**
* 私钥解密
*
* @param data 解密前的字符串
* @param privateKey 私钥
* @return 解密后的字符串
* @throws Exception
*/
public static String decryptByPriKey(String data, String privateKey) throws Exception {
byte[] priKey = RSAUtil.decodeBase64(privateKey);
byte[] design = decryptByPriKey(Base64.decodeBase64(data), priKey);
return new String(design);
} /**
* RSA签名
*
* @param data 待签名数据
* @param priKey 私钥
* @return 签名
* @throws Exception
*/
public static String sign(byte[] data, byte[] priKey) throws Exception {
// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKey);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
// 生成私钥
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 实例化Signature
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
// 初始化Signature
signature.initSign(privateKey);
// 更新
signature.update(data);
return Base64.encodeBase64String(signature.sign());
} /**
* RSA校验数字签名
*
* @param data 待校验数据
* @param sign 数字签名
* @param pubKey 公钥
* @return boolean 校验成功返回true,失败返回false
*/
public boolean verify(byte[] data, byte[] sign, byte[] pubKey) throws Exception {
// 实例化密钥工厂
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
// 初始化公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKey);
// 产生公钥
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
// 实例化Signature
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
// 初始化Signature
signature.initVerify(publicKey);
// 更新
signature.update(data);
// 验证
return signature.verify(sign);
} public static void main(String[] args) {
try {
Map<String, String> keyMap = initKey();
String publicKeyString = keyMap.get("publicKeyString");
String privateKeyString = keyMap.get("privateKeyString");
System.out.println("公钥:" + publicKeyString);
System.out.println("私钥:" + privateKeyString); // 待加密数据
String data = "admin123";
// 公钥加密
String encrypt = RSAUtil.encryptByPubKey(data, publicKeyString);
// 私钥解密
String decrypt = RSAUtil.decryptByPriKey(encrypt, privateKeyString); System.out.println("加密前:" + data);
System.out.println("加密后:" + encrypt);
System.out.println("解密后:" + decrypt);
} catch (Exception e) {
e.printStackTrace();
}
} }

RSA加密和解密工具类的更多相关文章

  1. AES加密、解密工具类

    AES加密.解密工具类代码如下: package com.util; import java.io.IOException; import java.io.UnsupportedEncodingExc ...

  2. java常用加密和解密工具类EncryptUtil.java

    package cn.util; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; im ...

  3. RSA加密方法java工具类

    package com.qianmi.weidian.common.util; import java.io.ByteArrayOutputStream; import java.security.K ...

  4. RSA加解密工具类RSAUtils.java,实现公钥加密私钥解密和私钥解密公钥解密

    package com.geostar.gfstack.cas.util; import org.apache.commons.codec.binary.Base64; import javax.cr ...

  5. Base64加密解密工具类

    使用Apache commons codec类Base64进行加密解密 maven依赖 <dependency> <groupId>commons-codec</grou ...

  6. RSA 签名、验证、加密、解密帮助类

    import java.io.IOException; import java.security.InvalidKeyException; import java.security.KeyFactor ...

  7. RSA加密、解密、公钥私钥生成

    有时项目中需要用到一些加密和解密工具,这里之前整理了一个demo,记录一下,方便查询 package com.test; import java.security.KeyFactory; import ...

  8. Java中的AES加解密工具类:AESUtils

    本人手写已测试,大家可以参考使用 package com.mirana.frame.utils.encrypt; import com.mirana.frame.constants.SysConsta ...

  9. 通过ios实现RSA加密和解密

    在加密和解密中,我们需要了解的知识有什么事openssl:RSA加密算法的基本原理:如何通过openssl生成最后我们需要的der和p12文件. 废话不多说,直接写步骤: 第一步:openssl来生成 ...

随机推荐

  1. Microsoft Corporation 去掉 windows 修改 启动加载 版权

    windows 修改 开机界面 boot启动界面 windows 修改 启动加载 版权 windows 系统如何修改开机画面的版权文字“Microsoft Corporation ... ◎Micro ...

  2. UVA - 1625 Color Length[序列DP 提前计算代价]

    UVA - 1625 Color Length   白书 很明显f[i][j]表示第一个取到i第二个取到j的代价 问题在于代价的计算,并不知道每种颜色的开始和结束   和模拟赛那道环形DP很想,计算这 ...

  3. 洛谷.T22136.最长不下降子序列(01归并排序 分治)

    题目链接 \(Description\) 给定一个长为n的序列,每次可以反转 \([l,r]\) 区间,代价为 \(r-l+1\).要求在\(4*10^6\)代价内使其LIS长度最长,并输出需要操作的 ...

  4. ab测试swoole和ngixn+php-fpm对比

    做个swoole http_server和ngixn+php7-fpm测试 nginx swoole卓越的性能让我惊呆了   如需应用可nginx反代, swoole作为http_server, 不用 ...

  5. [TC14126]BagAndCards

    [TC14126]BagAndCards 题目大意: 有\(n(n\le500)\)个袋子,第\(i\)个袋子里有\(count[i][j]\)张值为\(j(j\le m\le500)\)的牌.给一个 ...

  6. PHP类的继承

    每个子类(也叫派生类)都会在设置自己的属性前调用父类的构造方法.父类(也叫基类或超类)现在仅知道自己的数据,子类一般是父类的特例,要避免告诉父类任何关于子类的信息 以下为一个使用继承的实例: < ...

  7. 应用栈解决迷宫问题的C语言实现

    题目来自于严蔚敏<数据结构>,参考伪代码实现的程序: #include <stdio.h> #include <malloc.h> //记录通道块在迷宫矩阵当中的横 ...

  8. 在Win7 64位旗舰版下,利用Vs2008编译64位的Qt 4.8.2

    1.下载qt-everywhere-opensource-src-4.8.2.zip. 2.VS2008需要安装x64编译器. 3.将qt-everywhere-opensource-src-4.8. ...

  9. MyEclipse 2016 破解详细过程

    转自:https://blog.csdn.net/u012318074/article/details/71310553/ 文件资源 MyEclipse 和 破解程序可以到百度云下载:http://p ...

  10. 基于Socket网络编程

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/a2011480169/article/details/73602708 博客核心内容: 1.Sock ...