java之RSA和Base64加密帮助类

1、RSAUtils.java类

 

package com.sangfor.vpn.client.service.utils;
import java.io.BufferedReader;  
import java.io.ByteArrayOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.InputStreamReader;  
import java.math.BigInteger;  
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.interfaces.RSAPrivateKey;  
import java.security.interfaces.RSAPublicKey;  
import java.security.spec.InvalidKeySpecException;  
import java.security.spec.PKCS8EncodedKeySpec;  
import java.security.spec.RSAPublicKeySpec;  
import java.security.spec.X509EncodedKeySpec;  import javax.crypto.Cipher;  /** * Created by wk on 2017/2/14. */  public class RSAUtils {  private static String RSA = "RSA";  /** *//**  * RSA最大加密明文大小  */    private static final int MAX_ENCRYPT_BLOCK = 117;    /** * 随机生成RSA密钥对(默认密钥长度为1024) * * @return */  public static KeyPair generateRSAKeyPair()  {  return generateRSAKeyPair(1024);  }  /** * 随机生成RSA密钥对 * * @param keyLength *            密钥长度,范围:512~2048<br> *            一般1024 * @return */  public static KeyPair generateRSAKeyPair(int keyLength)  {  try  {  KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);  kpg.initialize(keyLength);  return kpg.genKeyPair();  } catch (NoSuchAlgorithmException e)  {  e.printStackTrace();  return null;  }  }  /** * 用公钥加密 <br> * 每次加密的字节数,不能超过密钥的长度值减去11 * * @param data *            需加密数据的byte数据 * @param publicKey 公钥 * @return 加密后的byte型数据 */  public static byte[] encryptData(byte[] data, PublicKey publicKey)  {  try  {  Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");  // 编码前设定编码方式及密钥  cipher.init(Cipher.ENCRYPT_MODE, publicKey);  // 传入编码数据并返回编码结果  int inputLen = data.length;    ByteArrayOutputStream out = new ByteArrayOutputStream();    int offSet = 0;    byte[] cache;    int i = 0;    // 对数据分段加密    while (inputLen - offSet > 0) {    if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {    cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);    } else {    cache = cipher.doFinal(data, offSet, inputLen - offSet);    }    out.write(cache, 0, cache.length);    i++;    offSet = i * MAX_ENCRYPT_BLOCK;    }    byte[] encryptedData = out.toByteArray();    out.close();    return encryptedData;    } catch (Exception e)  {  e.printStackTrace();  return null;  }  }  /** * 用私钥解密 * * @param encryptedData *            经过encryptedData()加密返回的byte数据 * @param privateKey *            私钥 * @return */  public static byte[] decryptData(byte[] encryptedData, PrivateKey privateKey)  {  try  {  Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");  cipher.init(Cipher.DECRYPT_MODE, privateKey);  return cipher.doFinal(encryptedData);  } catch (Exception e)  {     e.printStackTrace();  return null;  }  }  /** * 通过公钥byte[](publicKey.getEncoded())将公钥还原,适用于RSA算法 * * @param keyBytes * @return * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */  public static PublicKey getPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException,  InvalidKeySpecException  {  X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);  KeyFactory keyFactory = KeyFactory.getInstance(RSA);  PublicKey publicKey = keyFactory.generatePublic(keySpec);  return publicKey;  }  /** * 通过私钥byte[]将公钥还原,适用于RSA算法 * * @param keyBytes * @return * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */  public static PrivateKey getPrivateKey(byte[] keyBytes) throws NoSuchAlgorithmException,  InvalidKeySpecException  {  PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);  KeyFactory keyFactory = KeyFactory.getInstance(RSA);  PrivateKey privateKey = keyFactory.generatePrivate(keySpec);  return privateKey;  }  /** * 使用N、e值还原公钥 * * @param modulus * @param publicExponent * @return * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */  public static PublicKey getPublicKey(String modulus, String publicExponent)  throws NoSuchAlgorithmException, InvalidKeySpecException  {  BigInteger bigIntModulus = new BigInteger(modulus);  BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);  RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);  KeyFactory keyFactory = KeyFactory.getInstance(RSA);  PublicKey publicKey = keyFactory.generatePublic(keySpec);  return publicKey;  }  /** * 使用N、d值还原私钥 * * @param modulus * @param privateExponent * @return * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */  public static PrivateKey getPrivateKey(String modulus, String privateExponent)  throws NoSuchAlgorithmException, InvalidKeySpecException  {  BigInteger bigIntModulus = new BigInteger(modulus);  BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);  RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);  KeyFactory keyFactory = KeyFactory.getInstance(RSA);  PrivateKey privateKey = keyFactory.generatePrivate(keySpec);  return privateKey;  }  /** * 从字符串中加载公钥 * * @param publicKeyStr *            公钥数据字符串 * @throws Exception *             加载公钥时产生的异常 */  public static PublicKey loadPublicKey(String publicKeyStr) throws Exception  {  try  {  byte[] buffer = Base64Utils.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("公钥数据为空");  }  }  /** * 从字符串中加载私钥<br> * 加载时使用的是PKCS8EncodedKeySpec(PKCS#8编码的Key指令)。 * * @param privateKeyStr * @return * @throws Exception */  public static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception  {  try  {  byte[] buffer = Base64Utils.decode(privateKeyStr);  // X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);  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 in *            公钥输入流 * @throws Exception *             加载公钥时产生的异常 */  public static PublicKey loadPublicKey(InputStream in) throws Exception  {  try  {  return loadPublicKey(readKey(in));  } catch (IOException e)  {  throw new Exception("公钥数据流读取错误");  } catch (NullPointerException e)  {  throw new Exception("公钥输入流为空");  }  }  /** * 从文件中加载私钥 * * @param in *            私钥文件名 * @return 是否成功 * @throws Exception */  public static PrivateKey loadPrivateKey(InputStream in) throws Exception  {  try  {  return loadPrivateKey(readKey(in));  } catch (IOException e)  {  throw new Exception("私钥数据读取错误");  } catch (NullPointerException e)  {  throw new Exception("私钥输入流为空");  }  }  /** * 读取密钥信息 * * @param in * @return * @throws IOException */  private static String readKey(InputStream in) throws IOException  {  BufferedReader br = new BufferedReader(new InputStreamReader(in));  String readLine = null;  StringBuilder sb = new StringBuilder();  while ((readLine = br.readLine()) != null)  {  if (readLine.charAt(0) == '-')  {  continue;  } else  {  sb.append(readLine);  sb.append('\r');  }  }  return sb.toString();  }  /** * 打印公钥信息 * * @param publicKey */  public static void printPublicKeyInfo(PublicKey publicKey)  {  RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;  System.out.println("----------RSAPublicKey----------");  System.out.println("Modulus.length=" + rsaPublicKey.getModulus().bitLength());  System.out.println("Modulus=" + rsaPublicKey.getModulus().toString());  System.out.println("PublicExponent.length=" + rsaPublicKey.getPublicExponent().bitLength());  System.out.println("PublicExponent=" + rsaPublicKey.getPublicExponent().toString());  }  public static void printPrivateKeyInfo(PrivateKey privateKey)  {  RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;  System.out.println("----------RSAPrivateKey ----------");  System.out.println("Modulus.length=" + rsaPrivateKey.getModulus().bitLength());  System.out.println("Modulus=" + rsaPrivateKey.getModulus().toString());  System.out.println("PrivateExponent.length=" + rsaPrivateKey.getPrivateExponent().bitLength());  System.out.println("PrivatecExponent=" + rsaPrivateKey.getPrivateExponent().toString());  }  
}  

 

 

 

 

 

 

 

2、Base64Utils.java类

 

package com.sangfor.vpn.client.service.utils;import java.io.UnsupportedEncodingException;  /** * Created by wk on 2017/2/14. */  public class Base64Utils {  private static char[] base64EncodeChars = new char[]  { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',  'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',  'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',  '6', '7', '8', '9', '+', '/' };  private static byte[] base64DecodeChars = new byte[]  { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53,  54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,  12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29,  30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1,  -1, -1, -1 };  /** * 加密 * * @param data * @return */  public static String encode(byte[] data)  {  StringBuffer sb = new StringBuffer();  int len = data.length;  int i = 0;  int b1, b2, b3;  while (i < len)  {  b1 = data[i++] & 0xff;  if (i == len)  {  sb.append(base64EncodeChars[b1 >>> 2]);  sb.append(base64EncodeChars[(b1 & 0x3) << 4]);  sb.append("==");  break;  }  b2 = data[i++] & 0xff;  if (i == len)  {  sb.append(base64EncodeChars[b1 >>> 2]);  sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);  sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);  sb.append("=");  break;  }  b3 = data[i++] & 0xff;  sb.append(base64EncodeChars[b1 >>> 2]);  sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);  sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);  sb.append(base64EncodeChars[b3 & 0x3f]);  }  return sb.toString();  }  /** * 解密 * * @param str * @return */  public static byte[] decode(String str)  {  try  {  return decodePrivate(str);  } catch (UnsupportedEncodingException e)  {  e.printStackTrace();  }  return new byte[]  {};  }  private static byte[] decodePrivate(String str) throws UnsupportedEncodingException  {  StringBuffer sb = new StringBuffer();  byte[] data = null;  data = str.getBytes("US-ASCII");  int len = data.length;  int i = 0;  int b1, b2, b3, b4;  while (i < len)  {  do  {  b1 = base64DecodeChars[data[i++]];  } while (i < len && b1 == -1);  if (b1 == -1)  break;  do  {  b2 = base64DecodeChars[data[i++]];  } while (i < len && b2 == -1);  if (b2 == -1)  break;  sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));  do  {  b3 = data[i++];  if (b3 == 61)  return sb.toString().getBytes("iso8859-1");  b3 = base64DecodeChars[b3];  } while (i < len && b3 == -1);  if (b3 == -1)  break;  sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));  do  {  b4 = data[i++];  if (b4 == 61)  return sb.toString().getBytes("iso8859-1");  b4 = base64DecodeChars[b4];  } while (i < len && b4 == -1);  if (b4 == -1)  break;  sb.append((char) (((b3 & 0x03) << 6) | b4));  }  return sb.toString().getBytes("iso8859-1");  }  }  

 

 

 

 

3、SecurityUtils类

 

package com.sangfor.vpn.client.service.utils;import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.InputStream;  
import java.security.PrivateKey;  
import java.security.PublicKey;  public class SecurityUtils {  /** * 解密 * @param cipherText 密文 * @return 返回解密后的字符串 * @throws Exception  */  public static String decrypt(String cipherText) throws Exception{  // 从文件中得到私钥  FileInputStream inPrivate = new FileInputStream(  SecurityUtils.class.getClassLoader().getResource("").getPath() + "/pkcs8_private_key.pem");  PrivateKey privateKey = RSAUtils.loadPrivateKey(inPrivate);  byte[] decryptByte = RSAUtils.decryptData(Base64Utils.decode(cipherText), privateKey);  String decryptStr = new String(decryptByte,"utf-8");  return decryptStr;  }  /** * 加密 * @param plainTest 明文 * @return  返回加密后的密文 * @throws Exception  */  public static String encrypt(String plainTest) throws Exception{  PublicKey publicKey = RSAUtils.loadPublicKey(plainTest);  // 加密  byte[] encryptByte = RSAUtils.encryptData(plainTest.getBytes(), publicKey);  String afterencrypt = Base64Utils.encode(encryptByte);  return afterencrypt;  }  /** * 加密 * @param plainTest 明文 * @return  返回加密后的密文 * @throws Exception  */  public static String encrypt(String plainTest, String key) throws Exception{  PublicKey publicKey = RSAUtils.loadPublicKey(key);  // 加密  byte[] encryptByte = RSAUtils.encryptData(plainTest.getBytes(), publicKey);  String afterencrypt = Base64Utils.encode(encryptByte);  return afterencrypt;  }  
}  

 

 

 

 

 

 

 

 

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/290800.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

更强的压缩比!PostgreSQL开始支持Zstd

文 | 局长出品 | OSC开源社区&#xff08;ID&#xff1a;oschina2013&#xff09;PostgreSQL 现已通过其 TOAST 存储技术提供压缩支持&#xff0c;并且在过去的一年里构建了 LZ4 压缩支持——用于压缩 WAL、备份压缩以及其他用途&#xff0c;现在 PostgreSQL 开发者正准备通过 …

最近面试遇到的技术问题

京东性能组 1. oracle awr2. mysql 慢查询3. redis详细架构、如何插入数据4. jmeter使用及集群搭建5. nginx使用及tomcat集成 6. 数据库及sql优化的方案 7. 写存储过程 8. linux使用9. shell10. java e代驾 1. 接口测试方法2. sockets连接建立方法3. http三次握手过程 京东金融…

小程序和app用什么样的服务器,小程序和APP的本质区别是什么?哪个更值得开发?...

从微信小程序和用户见面到现在&#xff0c;这个功能已经越来越完善了&#xff0c;经过更彻底的挖掘&#xff0c;商业价值被挖掘出来了&#xff01;小程序和app有什么区别呢&#xff1f;为什么广州会更受欢迎呢&#xff1f;两者的区别首先&#xff0c;两者的区别在于&#xff0c…

jbpm6.5 环境搭建(三) 数据库 切换

2019独角兽企业重金招聘Python工程师标准>>> 经过一晚上的折腾&#xff0c;终于搞定&#xff0c;成功切换Mysql 步骤一&#xff1a; 安装mysql 数据库 创建数据库 名字为jbpm 设置用户名密码 我本地默认使用 root 步骤二&#xff1a; ** 修改配置文件 ** F:\jb…

Android之HandlerThread源码分析和简单使用(主线程和子线程通信、子线程和子线程通信)

1、先熟悉handler方式实现主线程和子线程互相通信方式&#xff0c;子线程和子线程的通信方式 如果不熟悉或者忘记了&#xff0c;请参考我的这篇博客 Android之用Handler实现主线程和子线程互相通信以及子线程和子线程之间的通信 http://blog.csdn.net/u011068702/arti…

CENTOS6.4安装vnc-server

yum install tigervnc-servervi /etc/sysconfig/vncservers只需要两类内容就可以了&#xff0c;一个是定义用户&#xff0c;一个是定义用户登录情况&#xff1a;参考&#xff1a;VNCSERVERS"1:root 2:river"VNCSERVERARGS[1]"-geometry 800x600 -nolisten tcp&q…

Avalonia跨平台入门第八篇之控件的拖放

在前面分享的几篇中咱已经玩耍了Popup、ListBox多选、Grid动态分、RadioButton模板,过程还算顺利;今天接着把把ListBox中的Item拖放到Cavans中(基于官方的Samples实现的);直接看效果吧:1、ListBox中PointerPressed、DragOver事件:2、Canvas中的Drop事件:3、控件的移除无非就是通…

sql server 之函数小技巧 整数类型为空是用空字符串替代实现

1、判空函数 说明&#xff1a;使用指定的替换值替换 NULL。 语法&#xff1a;ISNULL ( check_expression , replacement_value ) 参数&#xff1a; check_expression&#xff1a;将被检查是否为 NULL 的表达式。check_expression 可以为任何类型。 replacement_value&#xff1…

车牌识别系统连不上服务器怎么办,车牌识别系统出现故障的解决方法有哪些?...

在日常生活中&#xff0c;各个小区、商业广场、酒店、办公楼等等地方出入口装置有车牌识别系统&#xff0c;有此可见车牌识别系统的使用越来越广泛。停车场办理系统的使用给人们带来便利的同时&#xff0c;也常常会出现一些小问题。今天小编就给大家分享一下车牌识别系统遇到故…

霍夫变换

作者&#xff1a;桂。 时间&#xff1a;2017-04-24 12:18:17 链接&#xff1a;http://www.cnblogs.com/xingshansi/p/6756305.html 前言 今天群里有人问到一个图像的问题&#xff0c;但本质上是一个基本最小二乘问题&#xff0c;涉及到霍夫变换&#xff08;Hough Transform&a…

ASP.NET Core 实现基于 ApiKey 的认证

ASP.NET Core 实现基于 ApiKey 的认证Intro之前我们有介绍过实现基于请求头的认证&#xff0c;今天来实现一个基于 ApiKey 的认证方式&#xff0c;使用方式参见下面的示例Sample注册认证服务services.AddAuthentication().AddApiKey(options >{options.ApiKey "123456…

Android之调用系统分享

1、调用系统分享关键代码 private void shareImage() {Intent intent = new Intent(Intent.ACTION_SEND); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File("sdcard/screenshot.png")));intent.setTyp…

hdu4750Count The Pairs(最小生成树找瓶颈边)

1 /*2 题意&#xff1a;就是给你一个图&#xff0c;图的每两个点都有多条路径&#xff0c;每一条路径中都有一条最大边&#xff0c;3 所有最大边的最小边&#xff08;也就是瓶颈边&#xff09;就是这两点之间的val值&#xff01;然后给你一个值f&#xff0c;4 问有多少…

服务器的响应一直一直发送不过去,zeroRPC:在发送响应后继续运行进程

我使用Python2.7和zeroRPC使客户机和服务器通信。我希望客户端向服务器发送一个请求&#xff0c;我希望服务器发送一个响应以确认它已收到请求。但是我希望服务器对该请求执行一些繁重的计算。这些计算将花费数小时&#xff0c;并且不会产生任何响应&#xff0c;因此客户机不应…

白平衡自己主动(AWB)算法---2,颜色计算

本文说明了白平衡算法估计当前场景的色温过程. 色温计算的原理并不复杂,但要做到,还是一道&#xff0c;认真做好每一步,这需要大量的测试,和算法一直完好. 关于该过程首先简要: 1, 取的图像数据,并划分MxN块,如果是25x25,并统计每一块的基本信息(,白色像素的数量及R/G/B通道的分…

【机房收费系统】多么痛的领悟

这次机房收费系统&#xff0c;是全部的项目中&#xff0c;自己完毕的最不惬意的了。 时间之长。效率之慢。一開始。就感觉无从下手&#xff0c;但总会相信自己能慢慢的进入状态。最终有机会自己练练手了。也自觉得之前自己设计模式学的还不错。也最终有机会能自己想想设计模式了…

linux(windows)之svn重定向地址

1、问题 svn下载的项目路径需要换&#xff0c;也就是下面的URL:SVN:// 需要修改 2、解决办法 linux平台 svn switch --relocate oldSvnPath newSvnPath windows平台 右击项目 TortoiseSVN->Relocate 然后修改就行

简单的邮箱格式校验方式

简单的邮箱格式校验方式Intro前段时间有一个验证邮箱格式的小需求&#xff0c;然后突然发现了一种非常简单的邮箱格式判断方式Implement直接来看实现public static bool IsEmailAddress(string email) {if (string.IsNullOrWhiteSpace(email))return false;var symbolIndex em…

Ubuntu14.04LST安装weblogic11g

1:下载链接http://download.oracle.com/otn/nt/middleware/11g/wls/1036/wls1036_generic.jar 2:进行安装&#xff08;前提已经安装好JDK&#xff09; yy:~/my_download$ java -d64 -Xmx1024m -jar wls1036_generic.jar Extracting 0%.......................................…

服务器连接不稳定fifa,fifa服务器链接异常

fifa服务器链接异常 内容精选换一换获取登录密码Windows操作系统在创建时只能选择密钥登录&#xff0c;需要先将密钥文件解析为密码&#xff0c;参考链接&#xff1a;获取Windows裸金属服务器的密码Windows操作系统在创建时只能选择密钥登录&#xff0c;需要先将密钥文件解析为…