技术交流群: 233513714

  1. //字符串进行加密算法的名称
  2. public static final String ALGORITHM = "RSA";
  3. //字符串进行加密填充的名称
  4. public static final String PADDING = "RSA/NONE/NoPadding";
  5. //字符串持有安全提供者的名称
  6. public static final String PROVIDER = "BC";
    //私钥文件路径(RSAUtil是RSA工具类的类名)
  7. public static final String PRIVATE_KEY_FILE = RSAUtil.class.getClassLoader().getResource("").getPath() + "key" + "private_response_key_1.key";
  8. //公钥文件路径
    public static final String PUBLIC_KEY_FILE = RSAUtil.class.getClassLoader().getResource("").getPath() + "key" + "public_request_key_1.key";
  9.  
  10. /**
  11. * 测试加密解密
  12. */
  13. public void rsaTest(String str) {
  14. log.info("[要加密解密的参数:{}]", str);
  15. try {
  16. String cipherText = encrypt(str);
  17. String plainText = decrypt(cipherText);
  18. log.info("[加密后的参数为:{}]", cipherText);
  19. log.info("[解密后的参数为:{}]", plainText);
  20. } catch (Exception e) {
  21. log.info("[RSA加密解密出现异常:{}]", e);
  22. }
  23. }
  24.  
  25. /**
  26. * 将字符串进行RSA加密
  27. *
  28. * @param text
  29. * @return
  30. */
  31. public static String encrypt(String text) {
  32. String cipherTextBase64 = "";
  33. try {
  34. ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));
  35. PublicKey publicKey = (PublicKey) inputStream.readObject();
  36. Security.addProvider(new BouncyCastleProvider());
  37. Cipher cipher = Cipher.getInstance(PADDING, PROVIDER);
  38. cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  39. byte[] cipherText = cipher.doFinal(text.getBytes());
  40. Base64 base64 = new Base64();
  41. cipherTextBase64 = base64.encodeToString(cipherText);
  42. } catch (Exception e) {
  43. log.info("[字符串进行RSA加密出现异常:{}]", e);
  44. }
  45. return cipherTextBase64;
  46. }
  47. /**
  48. * 将字符串进行RSA解密
  49. *
  50. * @param str
  51. * @return
  52. */
  53. public static String decrypt(String str) {
  54. byte[] dectyptedText = null;
  55. try {
  56. ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
  57. PrivateKey privateKey = (PrivateKey) inputStream.readObject();
  58. Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
  59. Cipher cipher = Cipher.getInstance(PADDING, PROVIDER);
  60. cipher.init(Cipher.DECRYPT_MODE, privateKey);
  61. Base64 base64 = new Base64();
  62. byte[] text = base64.decode(str);
  63. dectyptedText = cipher.doFinal(text);
  64. } catch (Exception e) {
  65. log.info("[字符串进行RSA解密出现异常:{}]", e);
  66. }
  67. return new String(dectyptedText);
  68. }
  69. /**
  70. * 判断秘钥文件是否存在
  71. *
  72. * @return
  73. */
  74. public static boolean areKeysPresent() {
  75. File privateKey = new File(PRIVATE_KEY_FILE);
  76. File publicKey = new File(PUBLIC_KEY_FILE);
  77. if (privateKey.exists() && publicKey.exists()) {
  78. return true;
  79. }
  80. return false;
  81. }
  82.  
  83. /**
  84. * 生成公钥文件和私钥文件
  85. */
  86. public static void generateKey() {
  87. try {
  88. Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
  89. final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM, PROVIDER);
  90. keyGen.initialize(1024);
  91. final KeyPair key = keyGen.generateKeyPair();
  92. File privateKeyFile = new File(PRIVATE_KEY_FILE);
  93. File publicKeyFile = new File(PUBLIC_KEY_FILE);
  94. if (privateKeyFile.getParentFile() != null) {
  95. privateKeyFile.getParentFile().mkdirs();
  96. }
  97. privateKeyFile.createNewFile();
  98. if (publicKeyFile.getParentFile() != null) {
  99. publicKeyFile.getParentFile().mkdirs();
  100. }
  101. publicKeyFile.createNewFile();
  102. ObjectOutputStream publicKeyOS = new ObjectOutputStream(new FileOutputStream(publicKeyFile));
  103. publicKeyOS.writeObject(key.getPublic());
  104. publicKeyOS.close();
  105. ObjectOutputStream privateKeyOS = new ObjectOutputStream(new FileOutputStream(privateKeyFile));
  106. privateKeyOS.writeObject(key.getPrivate());
  107. privateKeyOS.close();
  108. } catch (Exception e) {
  109. log.info("[生成公钥文件和私钥文件出现异常{}]", e);
  110. }
  111. }

JAVA中使用RSA通过秘钥文件对字符串进行加密解密的更多相关文章

  1. expect配合shell 实现自动分发秘钥文件

    expect使用场景 有时候需要批量地执行一些操作,或者执行自动化的操作的时候,有些指令需要交互式地进行这就会有很多麻烦,linux下有一个程序交expect,它可以模拟键盘输入文本,省去人工干预交互 ...

  2. 生成秘钥文件 sn.exe(Strong Name Tool)

    Visual Studio 内置 Strong Name Tool, 我们直接运行"VS开发人员命令提示"就可以生成秘钥文件. 秘钥文件包含公钥和私钥. 来看这个例子: 在文件夹下 ...

  3. SFTP协议生成公共秘钥文件

    [步骤] 1 ssh方式登录服务器 2 执行命令生成秘钥对 ssh-keygen -t rsa 然后给秘钥文件命名 3.查看当前目录的.ssh目录是否有authorized_keys文件 如果有则把新 ...

  4. sshd 指定端口,指定秘钥文件

     scp -i ~/test -P22219 SRC/ root@10.2.227.76:/data/ #sshd的端口指定的是22219,  -i 指定秘钥文件   指定秘钥文件需要注意的是,需要提 ...

  5. 使用CloudFlare 的 PKI 工具集 cfssl 来生成 Certificate Authority (CA) 证书和秘钥文件

    要安装kubernetes最新版集群,https://github.com/opsnull/follow-me-install-kubernetes-cluster 这个文档必须要研习一下了. 以下实 ...

  6. java中如何创建带路径的文件

    请教各位大侠了,java中如何创建带路径的文件,说明下 这个路径不存在 ------回答--------- ------其他回答(2分)--------- Java code File f = new ...

  7. java中File的delete()方法删除文件失败的原因

    java中File的delete()方法删除文件失败的原因 学习了:http://hujinfan.iteye.com/blog/1266387 的确是忘记关闭了: 引用原文膜拜一下: 一般来说 ja ...

  8. Java中使用RSA算法加密

    Java中使用RSA算法加密 概述 RSA加密算法是一种非对称加密算法 RSA加密的方式 使用公钥加密的数据,利用私钥进行解密 使用私钥加密的数据,利用公钥进行解密 RSA是一对密钥.分别是公钥和私钥 ...

  9. Java中Pattern类的quote方法将任何字符串(包括正则表达式)都转换成字符串常量,不具有任何匹配功能

    Java中Pattern类的quote方法将任何字符串(包括正则表达式)都转换成字符串常量,不具有任何匹配功能. 下面是个例子: import org.junit.Test; import java. ...

随机推荐

  1. 封装CoreGraphics的API简化绘图操作

    封装CoreGraphics的API简化绘图操作 效果 说明 1. 将CoreGraphics的API接口抽象为对象,让绘图变得简单易懂 2. 简化常用的绘制操作 3. 源码长期更新 源码 https ...

  2. 全网数据定时备份方案[cron + rsync]

    1.1.1. Rsync(远程同步)介绍 [Rsync等价scp  cp  rm共3个命令的和] 1.什么是Rsync: Linux下面开源的,很快,功能很多,可以实现全量及增量的本地或者远程数据同步 ...

  3. windows安装及配置mysql5.7

    引子 mysql官方网站上没有 windows mysql5.7 64位版本msi的安装包下载,我们可以通过zip版本解压缩后手动安装配置环境. msi安装的话有32位的,基本上就是看着图形界面来一步 ...

  4. 寒假短期学习计划 - C++

    寒假短期学习计划 - C++ 一.所选课程 && 相关 0.选以下课的理由: 选课理由0: 只是短期的计划,先选些短视频感受:之后再视情况选其他课: 选课理由1: 难度低,以前自学过一 ...

  5. 【linux】安装和配置 mysql服务器

    按照官网教程,根据自己的系统安装不同的发行版 https://dev.mysql.com/doc/refman/5.6/en/linux-installation-yum-repo.html 配置: ...

  6. echarts问题

    1.鼠标经过折线图  显示的框中的文字设置,需要设置tooltip下的formatter属性 formatter属性值可以为字符串也可function formatter:function(data) ...

  7. 【python库安装问题解决】UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc0 in position 121: invalid start byte

    好久没用python了...今天随便pip安装个库突然报错: Exception:‘’ (most recent call last):  File "C:\ProgramData\Anac ...

  8. NSKeyValueObserving.m

    https://github.com/farcaller/cocotron/blob/af740de86c9bee84c59ffc74d27e5df9e22e1391/Foundation/NSKey ...

  9. OSSpinLockLock加锁机制,保证线程安全并且性能高

    在aspect_add.aspect_remove方法里面用了aspect_performLocked, 而aspect_performLocked方法用了OSSpinLockLock加锁机制,保证线 ...

  10. 有料面试题之--Object里面的方法

    阿里的面试题里面有个题很奇妙:你知道Object类里面有哪些方法吗? 绝大部分猿类都知道 有hashcode .equals .clone.toString 只有部分人会回答有 wait和notify ...