RSA加密解密类:

package com.ihep;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.FileReader;

import java.io.FileWriter;

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.SecureRandom;

import java.security.interfaces.RSAPrivateKey;

import java.security.interfaces.RSAPublicKey;

import java.security.spec.InvalidKeySpecException;

import java.security.spec.PKCS8EncodedKeySpec;

import java.security.spec.X509EncodedKeySpec;

import javax.crypto.BadPaddingException;

import javax.crypto.Cipher;

import javax.crypto.IllegalBlockSizeException;

import javax.crypto.NoSuchPaddingException;

import com.fcplay.Base64;

public class RSAEncrypt {

/**

* 字节数据转字符串专用集合

*/

private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6',

'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

/**

* 随机生成密钥对

*/

public static void genKeyPair(String filePath) {

// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象

KeyPairGenerator keyPairGen = null;

try {

keyPairGen = KeyPairGenerator.getInstance("RSA");

} catch (NoSuchAlgorithmException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

// 初始化密钥对生成器,密钥大小为96-1024位

keyPairGen.initialize(1024,new SecureRandom());

// 生成一个密钥对,保存在keyPair中

KeyPair keyPair = keyPairGen.generateKeyPair();

// 得到私钥

RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

// 得到公钥

RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

try {

// 得到公钥字符串

String publicKeyString = Base64.encode(publicKey.getEncoded());

// 得到私钥字符串

String privateKeyString = Base64.encode(privateKey.getEncoded());

// 将密钥对写入到文件

FileWriter pubfw = new FileWriter(filePath + "/publicKey.keystore");

FileWriter prifw = new FileWriter(filePath + "/privateKey.keystore");

BufferedWriter pubbw = new BufferedWriter(pubfw);

BufferedWriter pribw = new BufferedWriter(prifw);

pubbw.write(publicKeyString);

pribw.write(privateKeyString);

pubbw.flush();

pubbw.close();

pubfw.close();

pribw.flush();

pribw.close();

prifw.close();

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 从文件中输入流中加载公钥

*

* @param in

*            公钥输入流

* @throws Exception

*             加载公钥时产生的异常

*/

public static String loadPublicKeyByFile(String path) throws Exception {

try {

BufferedReader br = new BufferedReader(new FileReader(path

+ "/publicKey.keystore"));

String readLine = null;

StringBuilder sb = new StringBuilder();

while ((readLine = br.readLine()) != null) {

sb.append(readLine);

}

br.close();

return sb.toString();

} catch (IOException e) {

throw new Exception("公钥数据流读取错误");

} catch (NullPointerException e) {

throw new Exception("公钥输入流为空");

}

}

/**

* 从字符串中加载公钥

*

* @param publicKeyStr

*            公钥数据字符串

* @throws Exception

*             加载公钥时产生的异常

*/

public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr)

throws Exception {

try {

byte[] buffer = Base64.decode(publicKeyStr);

KeyFactory keyFactory = KeyFactory.getInstance("RSA");

X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);

return (RSAPublicKey) keyFactory.generatePublic(keySpec);

} catch (NoSuchAlgorithmException e) {

throw new Exception("无此算法");

} catch (InvalidKeySpecException e) {

throw new Exception("公钥非法");

} catch (NullPointerException e) {

throw new Exception("公钥数据为空");

}

}

/**

* 从文件中加载私钥

*

* @param keyFileName

*            私钥文件名

* @return 是否成功

* @throws Exception

*/

public static String loadPrivateKeyByFile(String path) throws Exception {

try {

BufferedReader br = new BufferedReader(new FileReader(path

+ "/privateKey.keystore"));

String readLine = null;

StringBuilder sb = new StringBuilder();

while ((readLine = br.readLine()) != null) {

sb.append(readLine);

}

br.close();

return sb.toString();

} catch (IOException e) {

throw new Exception("私钥数据读取错误");

} catch (NullPointerException e) {

throw new Exception("私钥输入流为空");

}

}

public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)

throws Exception {

try {

byte[] buffer = Base64.decode(privateKeyStr);

PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);

KeyFactory keyFactory = KeyFactory.getInstance("RSA");

return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);

} catch (NoSuchAlgorithmException e) {

throw new Exception("无此算法");

} catch (InvalidKeySpecException e) {

throw new Exception("私钥非法");

} catch (NullPointerException e) {

throw new Exception("私钥数据为空");

}

}

/**

* 公钥加密过程

*

* @param publicKey

*            公钥

* @param plainTextData

*            明文数据

* @return

* @throws Exception

*             加密过程中的异常信息

*/

public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData)

throws Exception {

if (publicKey == null) {

throw new Exception("加密公钥为空, 请设置");

}

Cipher cipher = null;

try {

// 使用默认RSA

cipher = Cipher.getInstance("RSA");

// cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());

cipher.init(Cipher.ENCRYPT_MODE, publicKey);

byte[] output = cipher.doFinal(plainTextData);

return output;

} catch (NoSuchAlgorithmException e) {

throw new Exception("无此加密算法");

} catch (NoSuchPaddingException e) {

e.printStackTrace();

return null;

} catch (InvalidKeyException e) {

throw new Exception("加密公钥非法,请检查");

} catch (IllegalBlockSizeException e) {

throw new Exception("明文长度非法");

} catch (BadPaddingException e) {

throw new Exception("明文数据已损坏");

}

}

/**

* 私钥加密过程

*

* @param privateKey

*            私钥

* @param plainTextData

*            明文数据

* @return

* @throws Exception

*             加密过程中的异常信息

*/

public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData)

throws Exception {

if (privateKey == null) {

throw new Exception("加密私钥为空, 请设置");

}

Cipher cipher = null;

try {

// 使用默认RSA

cipher = Cipher.getInstance("RSA");

cipher.init(Cipher.ENCRYPT_MODE, privateKey);

byte[] output = cipher.doFinal(plainTextData);

return output;

} catch (NoSuchAlgorithmException e) {

throw new Exception("无此加密算法");

} catch (NoSuchPaddingException e) {

e.printStackTrace();

return null;

} catch (InvalidKeyException e) {

throw new Exception("加密私钥非法,请检查");

} catch (IllegalBlockSizeException e) {

throw new Exception("明文长度非法");

} catch (BadPaddingException e) {

throw new Exception("明文数据已损坏");

}

}

/**

* 私钥解密过程

*

* @param privateKey

*            私钥

* @param cipherData

*            密文数据

* @return 明文

* @throws Exception

*             解密过程中的异常信息

*/

public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData)

throws Exception {

if (privateKey == null) {

throw new Exception("解密私钥为空, 请设置");

}

Cipher cipher = null;

try {

// 使用默认RSA

cipher = Cipher.getInstance("RSA");

// cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());

cipher.init(Cipher.DECRYPT_MODE, privateKey);

byte[] output = cipher.doFinal(cipherData);

return output;

} catch (NoSuchAlgorithmException e) {

throw new Exception("无此解密算法");

} catch (NoSuchPaddingException e) {

e.printStackTrace();

return null;

} catch (InvalidKeyException e) {

throw new Exception("解密私钥非法,请检查");

} catch (IllegalBlockSizeException e) {

throw new Exception("密文长度非法");

} catch (BadPaddingException e) {

throw new Exception("密文数据已损坏");

}

}

/**

* 公钥解密过程

*

* @param publicKey

*            公钥

* @param cipherData

*            密文数据

* @return 明文

* @throws Exception

*             解密过程中的异常信息

*/

public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData)

throws Exception {

if (publicKey == null) {

throw new Exception("解密公钥为空, 请设置");

}

Cipher cipher = null;

try {

// 使用默认RSA

cipher = Cipher.getInstance("RSA");

// cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());

cipher.init(Cipher.DECRYPT_MODE, publicKey);

byte[] output = cipher.doFinal(cipherData);

return output;

} catch (NoSuchAlgorithmException e) {

throw new Exception("无此解密算法");

} catch (NoSuchPaddingException e) {

e.printStackTrace();

return null;

} catch (InvalidKeyException e) {

throw new Exception("解密公钥非法,请检查");

} catch (IllegalBlockSizeException e) {

throw new Exception("密文长度非法");

} catch (BadPaddingException e) {

throw new Exception("密文数据已损坏");

}

}

/**

* 字节数据转十六进制字符串

*

* @param data

*            输入数据

* @return 十六进制内容

*/

public static String byteArrayToString(byte[] data) {

StringBuilder stringBuilder = new StringBuilder();

for (int i = 0; i < data.length; i++) {

// 取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移

stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);

// 取出字节的低四位 作为索引得到相应的十六进制标识符

stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);

if (i < data.length - 1) {

stringBuilder.append(' ');

}

}

return stringBuilder.toString();

}

}

最后是一个MainTest:

package com.ihep;

public class MainTest {

public static void main(String[] args) throws Exception {

String filepath="G:/tmp/";

//RSAEncrypt.genKeyPair(filepath);

System.out.println("--------------公钥加密私钥解密过程-------------------");

String plainText="ihep_公钥加密私钥解密";

//公钥加密过程

byte[] cipherData=RSAEncrypt.encrypt(RSAEncrypt.loadPublicKeyByStr(RSAEncrypt.loadPublicKeyByFile(filepath)),plainText.getBytes());

String cipher=Base64.encode(cipherData);

//私钥解密过程

byte[] res=RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile(filepath)), Base64.decode(cipher));

String restr=new String(res);

System.out.println("原文:"+plainText);

System.out.println("加密:"+cipher);

System.out.println("解密:"+restr);

System.out.println();

System.out.println("--------------私钥加密公钥解密过程-------------------");

plainText="ihep_私钥加密公钥解密";

//私钥加密过程

cipherData=RSAEncrypt.encrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile(filepath)),plainText.getBytes());

cipher=Base64.encode(cipherData);

//公钥解密过程

res=RSAEncrypt.decrypt(RSAEncrypt.loadPublicKeyByStr(RSAEncrypt.loadPublicKeyByFile(filepath)), Base64.decode(cipher));

restr=new String(res);

System.out.println("原文:"+plainText);

System.out.println("加密:"+cipher);

System.out.println("解密:"+restr);

System.out.println();

System.out.println("---------------私钥签名过程------------------");

String content="ihep_这是用于签名的原始数据";

String signstr=RSASignature.sign(content,RSAEncrypt.loadPrivateKeyByFile(filepath));

System.out.println("签名原串:"+content);

System.out.println("签名串:"+signstr);

System.out.println();

System.out.println("---------------公钥校验签名------------------");

System.out.println("签名原串:"+content);

System.out.println("签名串:"+signstr);

System.out.println("验签结果:"+RSASignature.doCheck(content, signstr, RSAEncrypt.loadPublicKeyByFile(filepath)));

System.out.println();

}

}

java rsa 验_Java使用RSA加密解密签名及校验相关推荐

  1. java rsa签名_Java使用RSA加密解密签名及校验

    由于项目要用到非对称加密解密签名校验什么的,于是参考<Java加密解密的艺术>写一个RSA进行加密解密签名及校验的Demo,代码很简单,特此分享! 一.项目截图 代码下载后,导入到ecli ...

  2. Java使用RSA加密解密签名及校验

    RSA加密解密类: import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; i ...

  3. .NET Core 使用RSA算法 加密/解密/签名/验证签名

    前言 前不久移植了支付宝官方的SDK,以适用ASP.NET Core使用支付宝支付,但是最近有好几位用户反应在Linux下使用会出错,调试发现是RSA加密的错误,下面具体讲一讲. RSA在.NET C ...

  4. iOS使用Security.framework进行RSA 加密解密签名和验证签名

    iOS 上 Security.framework为我们提供了安全方面相关的api: Security框架提供的RSA在iOS上使用的一些小结 支持的RSA keySize 大小有:512,768,10 ...

  5. RSACryptoServiceProvider加密解密签名验签和DESCryptoServiceProvider加解密

    RSACryptoServiceProvider加密解密签名验签和DESCryptoServiceProvider加解密 原文:RSACryptoServiceProvider加密解密签名验签和DES ...

  6. js rsa验签_js rsa sign使用笔记(加密,解密,签名,验签)

    你将会收获: js如何加密, 解密 js如何签名, 验签 js和Java交互如何相互解密, 验签(重点) 通过谷歌, 发现jsrsasign库使用者较多. 查看api发现这个库功能很健全. 本文使用方 ...

  7. java的rsa作用_java 中RSA的方式实现非对称加密的实例

    java 中rsa的方式实现非对称加密的实例 rsa通俗理解: 你只要去想:既然是加密,那肯定是不希望别人知道我的消息,所以只有我才能解密,所以可得出公钥负责加密,私钥负责解密:同理,既然是签名,那肯 ...

  8. Java DES、AES、RSA、DM5读取文件加密解密

    //下面代码是直接读取文件来进行加密解密,算法文件 package Test; import javax.crypto.KeyGenerator; import javax.crypto.Cipher ...

  9. RSA 加密解密签名验签

    api package v1// get请求 import "github.com/gogf/gf/v2/frame/g"type GetKeyReq struct {g.Meta ...

最新文章

  1. 【FFmpeg】解决警告warning: xxx is deprecated [-Wdeprecated-declarations]的方法
  2. 选择NLP供应商之前需要提出的一些关键问题
  3. dragsort html拖拽排序 的应用
  4. 面试:URI中的 “//” 有什么用?
  5. java 子线程传参_踩坑之Java执行Linux命令死锁阻塞挂起
  6. 小菜鸟学 Spring-Dependency injection(二)
  7. 音视频技术开发周刊 | 173
  8. sql timestep 秒数后6位_excel中,如何截取身份证号后6位?前4位?或者中间8位?...
  9. 通过Shell脚本快速搭建高效Rsync服务
  10. 【雷达通信】基于matlab GUI多算法雷达一维恒虚警检测CFAR【含Matlab源码 874期】
  11. CF(427D-Match amp; Catch)后缀数组应用
  12. Python合成PDF文件
  13. 码神之路博客部署总结补充
  14. 《跟任何人都聊得来》读书笔记
  15. 64位先行进位加法器的原理
  16. [汇]我常去逛的iOS干货文章、blog等
  17. linux卸载exe文件怎么恢复,linux中误删除程序包恢复实例
  18. linux基因组文件,转录组入门(四):了解参考基因组及基因注释
  19. 电脑重装系统,微信备份与恢复聊天记录,保存的文件。微信聊天记录迁移
  20. 主成分分析(R语言)

热门文章

  1. javascript将base64编码的图片数据转换为file并提交
  2. Lua程序设计--全局变量
  3. 运用Axure6.5快速完成微信交互效果的简单办法
  4. SCCM 2007 R2 报表问题(二)
  5. 【.NET框架】—— ASP.NET MVC5路由基础(五)
  6. Swift4.0 从相册中获取图片和拍照
  7. C#以对象为成员的例子
  8. 【模块化开发】之 模块化概述
  9. 什么是IDE(集成开发环境)?
  10. os.path vs pathlib