关于RSA加密算法的工具类

最近在捣鼓SSO(单点登录),就是一个在应用(系统)登录之后,当切换其他应用(系统)的时候,可以省去登录,提高用户的使用的便捷。(具体有时间在写)

期间涉及的安全问题,发送数据涉及账户密码以及分布系统之间的信息安全问题。

  1. package test.rsa;
  2. import java.io.*;
  3. import java.math.BigInteger;
  4. import java.security.*;
  5. import java.security.interfaces.*;
  6. import java.security.spec.*;
  7. import javax.crypto.*;
  8. import org.bouncycastle.util.encoders.Hex;
  9. import sun.misc.*;
  10. public class TestRSA {
  11. /**
  12. * * 生成密钥对 *
  13. *
  14. * @return KeyPair *
  15. * @throws EncryptException
  16. */
  17. public static KeyPair generateKeyPair() throws Exception {
  18. try {
  19. KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",
  20. new org.bouncycastle.jce.provider.BouncyCastleProvider());
  21. final int KEY_SIZE = 1024;// 块加密的大小,是不要太大,否则效率会低
  22. keyPairGen.initialize(KEY_SIZE, new SecureRandom());
  23. KeyPair keyPair = keyPairGen.generateKeyPair();
  24. saveKeyPair(keyPair);
  25. return keyPair;
  26. } catch (Exception e) {
  27. throw new Exception(e.getMessage());
  28. }
  29. }
  30. public static KeyPair getKeyPair() throws Exception {
  31. FileInputStream fis = new FileInputStream(
  32. "D:/javasoft/TempTest/RSAKey.txt");
  33. ObjectInputStream oos = new ObjectInputStream(fis);
  34. KeyPair kp = (KeyPair) oos.readObject();
  35. oos.close();
  36. fis.close();
  37. return kp;
  38. }
  39. public static void saveKeyPair(KeyPair kp) throws Exception {
  40. FileOutputStream fos = new FileOutputStream(
  41. "D:/javasoft/TempTest/RSAKey.txt");
  42. ObjectOutputStream oos = new ObjectOutputStream(fos);
  43. // 生成密钥
  44. oos.writeObject(kp);
  45. oos.close();
  46. fos.close();
  47. }
  48. /**
  49. * * 生成公钥 *
  50. *
  51. * @param modulus *
  52. * @param publicExponent *
  53. * @return RSAPublicKey *
  54. * @throws Exception
  55. */
  56. public static RSAPublicKey generateRSAPublicKey(byte[] modulus,
  57. byte[] publicExponent) throws Exception {
  58. KeyFactory keyFac = null;
  59. try {
  60. keyFac = KeyFactory.getInstance("RSA",
  61. new org.bouncycastle.jce.provider.BouncyCastleProvider());
  62. } catch (NoSuchAlgorithmException ex) {
  63. throw new Exception(ex.getMessage());
  64. }
  65. RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(
  66. modulus), new BigInteger(publicExponent));
  67. try {
  68. return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);
  69. } catch (InvalidKeySpecException ex) {
  70. throw new Exception(ex.getMessage());
  71. }
  72. }
  73. /**
  74. * * 生成私钥 *
  75. *
  76. * @param modulus *
  77. * @param privateExponent *
  78. * @return RSAPrivateKey *
  79. * @throws Exception
  80. */
  81. public static RSAPrivateKey generateRSAPrivateKey(byte[] modulus,
  82. byte[] privateExponent) throws Exception {
  83. KeyFactory keyFac = null;
  84. try {
  85. keyFac = KeyFactory.getInstance("RSA",
  86. new org.bouncycastle.jce.provider.BouncyCastleProvider());
  87. } catch (NoSuchAlgorithmException ex) {
  88. throw new Exception(ex.getMessage());
  89. }
  90. RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(
  91. modulus), new BigInteger(privateExponent));
  92. try {
  93. return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);
  94. } catch (InvalidKeySpecException ex) {
  95. throw new Exception(ex.getMessage());
  96. }
  97. }
  98. /**
  99. * 加密的方法
  100. * @throws IOException
  101. * @throws NoSuchPaddingException
  102. * @throws NoSuchAlgorithmException
  103. */
  104. private static String encrypt(PublicKey pk,String source) throws Exception{
  105. Cipher cipher = Cipher.getInstance("RSA",new org.bouncycastle.jce.provider.BouncyCastleProvider());
  106. cipher.init(Cipher.ENCRYPT_MODE, pk);
  107. byte[] sbt = source.getBytes();
  108. byte[] epByte = cipher.doFinal(sbt);
  109. BASE64Encoder encoder = new BASE64Encoder();
  110. String epStr = encoder.encode(epByte);
  111. return epStr;
  112. }
  113. private static String encrypt1(PublicKey pk,String source) throws Exception{
  114. Cipher cipher = Cipher.getInstance("RSA",new org.bouncycastle.jce.provider.BouncyCastleProvider());
  115. cipher.init(Cipher.ENCRYPT_MODE, pk);
  116. byte[] s = source.getBytes();
  117. byte[] en_s = cipher.doFinal(s);
  118. return new String(Hex.encode(en_s));
  119. }
  120. /**
  121. * 解密的方法
  122. * @throws Exception
  123. */
  124. public static String decrypt(PrivateKey pk,String source) throws Exception {
  125. /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
  126. Cipher cipher = Cipher.getInstance("RSA",new org.bouncycastle.jce.provider.BouncyCastleProvider());
  127. cipher.init(Cipher.DECRYPT_MODE, pk);
  128. BASE64Decoder decoder = new BASE64Decoder();
  129. byte[] b1 = decoder.decodeBuffer(source);
  130. /** 执行解密操作 */
  131. byte[] b = cipher.doFinal(b1);
  132. return new String(b);
  133. }
  134. public static String decrypt1(PrivateKey pk,String source) throws Exception {
  135. /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
  136. Cipher cipher = Cipher.getInstance("RSA",new org.bouncycastle.jce.provider.BouncyCastleProvider());
  137. cipher.init(Cipher.DECRYPT_MODE, pk);
  138. /** 执行解密操作 */
  139. byte[] b = cipher.doFinal(Hex.decode(source));
  140. return new String(b);
  141. }
  142. public static void main(String[] args) throws Exception {
  143. String s = "1-Test-我";
  144. String en_s = encrypt1(getKeyPair().getPublic(), s);
  145. System.out.println("----------------分割线--------------------------");
  146. System.out.println("加密之后:");
  147. System.out.println(en_s);
  148. System.out.println("----------------分割线--------------------------");
  149. String de_s = decrypt1(getKeyPair().getPrivate(),en_s);
  150. System.out.println("还原密文:");
  151. System.out.println(de_s);
  152. }
  153. }

关于RSA加密算法的工具类的更多相关文章

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

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

  2. RSA和AES工具类

    AESUtil import com.xxx.common.BssException; import com.xxx.common.constants.CommonConstants; import ...

  3. AES/DES 可逆性加密算法 -- java工具类

    package com.lock.demo.service; import org.apache.tomcat.util.codec.binary.Base64; import javax.crypt ...

  4. Java中的RSA加解密工具类:RSAUtils

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

  5. 可用的 .net core 支持 RSA 私钥加密工具类

    首先说明 MS并不建议私钥加密,而且.net 于安全的考虑,RSACryptoServiceProvider类解密时只有同时拥有公钥和私钥才可以,原因是公钥是公开的,会被多人持有,这样的数据传输是不安 ...

  6. Android工具类整合

    Android-JSONUtil工具类 常用的Json工具类,包含Json转换成实体.实体转json字符串.list集合转换成json.数组转换成json public class JSONUtil ...

  7. JAVA的RSA加密算法工具类

    须要用到一个jar http://www.bouncycastle.org/latest_releases.html 须要注意的问题 JS用同一秘钥生成的密文用java解密出来是逆序的,即js加密12 ...

  8. Asp.Net 常用工具类之加密——非对称加密RSA算法

    踏入程序员这个行业也有几年了,几年中有收获(技术加强),有付出(时间和亚健康状态).当然喏,并不后悔,代码路还长!!! On The Way,永不止步!!! 开发过程中也积累了一些自己的经验.代码块和 ...

  9. java 加密工具类(MD5、RSA、AES等加密方式)

    1.加密工具类encryption MD5加密 import org.apache.commons.codec.digest.DigestUtils; /** * MD5加密组件 * * @autho ...

随机推荐

  1. Windows Server 2012上安装.NET Framework 3.5(不需要安装光盘)

    因为在windows2012里,安装数据库,IIS部分组件都需要.NET3.5,而默认windows2012安装时,并不会把此组件复制到电脑里 导致,后期要安装.NET3.5还需要安装盘.但是,很多人 ...

  2. MAT(Memory Analyzer Tool)内存分析工具的使用

    开发.应用中老是会遇到OutOfMemory异常,而且常常是过一段时间内存才被吃光,这里可以利用java heap dump出jvm内存镜像,然后再对其进行分析来查找问题. 平常利用jmap -dum ...

  3. OpenCV教程(47) sift特征和surf特征

         在前面三篇教程中的几种角检测方法,比如harris角检测,都是旋转无关的,即使我们转动图像,依然能检测出角的位置,但是图像缩放后,harris角检测可能会失效,比如下面的图像,图像放大之前可 ...

  4. go语言之进阶篇拷贝文件案例

    1.文件案例:拷贝文件 示例: package main import ( "fmt" "io" "os" ) func main() { ...

  5. go语言之进阶篇方法的继承

    1.方法的继承 示例: package main import "fmt" type Person struct { name string //名字 sex byte //性别, ...

  6. Set Matrix Zeroes leetcode java

    题目: Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. cl ...

  7. mybatis plus 主键生成 Twitter雪花算法 id 及修改id为字符型

    mybatis plus配置主键生成策略为2,就是 使用Twitter雪花算法 生成id spring boot中配置为: GlobalConfiguration conf = new GlobalC ...

  8. 重装linuxserver简易流程

             项目开发软件开发非常重要的一个环节,而能够拥有一个安全健康的server来使System正常高效的执行也是非常有必要的.由于是搭建在外网上的server.时不时会受到各种病毒的侵袭, ...

  9. PHPExcel-设置表格字体颜色背景样式、数据格式、对齐方式、添加图片、批注、文字块、合并拆分单元格、单元格密码保护

    首先到phpexcel官网上下载最新的phpexcel类,下周解压缩一个classes文件夹,里面包含了PHPExcel.php和PHPExcel的文件夹,这个类文件和文件夹是我们需要的,把class ...

  10. MySQL 百万级分页优化(Mysql千万级快速分页)(转)

    http://www.jb51.net/article/31868.htm 以下分享一点我的经验 一般刚开始学SQL的时候,会这样写 复制代码 代码如下: SELECT * FROM table OR ...