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;  }
}  

java之RSA和Base64加密帮助类相关推荐

  1. Java 开发中常用的 4 种加密方法。MD5加密工具类测试 base64加密工具类测试 SHA加密工具类测试 BCrypt加密工具类测试

    一.工具类 1, md5加密工具类 2, base64加密工具类 3, Bcrypt工具类 二.加密测试 MD5加密测试 base64加密测试 SHA加密测试 BCrypt加密测试 一.工具类 1, ...

  2. Java 实现RSA签名和加密

    Java 实现RSA签名和加密 RSA在1977年发明,是公钥加密方式的事实标准,名称有其三位作者首字母组成.本文我们介绍Java中如何使用RSA实现加密和签名. RSA属于非对称加密算法,有两个密钥 ...

  3. java实现RSA和AES加密(一)

    java实现RSA和AES加密(一) 由于公司要求接口安全升级,从自定义防篡改数据MD5加密验证,到使用RSA加密. 原始的MD5防数据篡改的方式: 将所有参数拼接起来,然后在某一字节后加入自定义的字 ...

  4. Android网络传输中必用的两个加密算法:MD5 和 RSA 及Base64加密总结

    (1)commons-codec包简介 包含一些通用的编码解码算法.包括一些语音编码器,Hex,Base64.MD5 一.md5.base64.commons-codec包 commons-codec ...

  5. 基于TCP协议RSA与Base64加密的聊天程序

    一.理论依据 1.TCP协议 TCP(Transmission Control Protocol 传输控制协议)是一种面向连接的.可靠的.基于字节流的传输层通信协议.其中TCP提供IP环境下的数据可靠 ...

  6. Base64加密工具类

    Base64是网络上最常见的用于传输8Bit字节码的编码方式之一,Base64就是一种基于64个可打印字符来表示二进制数据的方法. Base64编码是从二进制到字符的过程,可用于在HTTP环境下传递较 ...

  7. Base64加密工具类 - Base64Utils

    package com.zykj.zycxapplet.utils;import java.io.*;/*** <p>* BASE64编码解码工具包* </p>* <p& ...

  8. Java教程:微信排序并加密工具类

    Java教程:微信排序并加密工具类 源码: import cn.bsit.commons.md5.MD5Utils;import java.util.Arrays; import java.util. ...

  9. Java 使用 RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING 算法解密

      Java 实现 RSA 解密(算法模式为 RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING),代码如下. package com.test.utils;import lo ...

最新文章

  1. 18岁的他从月薪2000到月薪11000经历了什么?
  2. 015_面向对象_异常,包和Object类
  3. SpringBoot整合MyBatis-Plus3.1详细教程
  4. Delphi下载指定网址(URL)的文件,带进度条显示
  5. php join a.id b.id,mysql,sql_MySQL A left join B on B.cid=A.id 左链接查询失败,求解,mysql,sql - phpStudy...
  6. Python—— *与** 参数说明
  7. Codeforces Round #524 Div. 2 翻车记
  8. 用JSLint精炼提升JavaScript代码
  9. mac下使用pyenv
  10. PPT转换PDF格式怎么转换?后悔现在才知道
  11. 阶段1 语言基础+高级_1-3-Java语言高级_06-File类与IO流_05 IO字符流_7_字符输出流的续写和换行...
  12. 优云automation实践技巧:简单4步完成自动化构建与发布
  13. 旧手机改装服务器——Android上的Linux(linux deploy)
  14. android 图片字体涂鸦,android 实现在照片上绘制涂鸦的方法
  15. 汽车牌照 (license) C++
  16. T00ls - Metasploit 教程 笔记
  17. vue手机端回退_从外链回退到vue应用不触发生命周期、beforeRouterEnter等钩子函数的问题...
  18. 揭秘 typedef四用途与两陷阱
  19. java计算方法所耗费的时间
  20. PBC Library Manual(PBC库手册)翻译(一)

热门文章

  1. Dapr + .NET 实战(十-终篇)K8S运行Dapr
  2. 中国宜坚持发展自主操作系统
  3. 使用Select.HtmlToPdf 把html内容生成pdf文件
  4. 关于C# Span的一些实践
  5. 谈了千百遍的缓存数据的一致性问题
  6. .NET Core 下使用 gRPC
  7. .NET Core + Kubernetes:Service
  8. 一键分享博客或新闻到Teams好友或频道
  9. 【 .NET Core 3.0 】框架之五 || JWT权限验证
  10. asp.net core 使用 signalR(一)