JAVA RSA加解密

来源:互联网 发布:java excel预览插件 编辑:程序博客网 时间:2024/05/22 03:32
package com.tagding.utils;


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;


import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;


import sun.security.rsa.RSAPrivateKeyImpl;
import sun.security.rsa.RSAPublicKeyImpl;
import sun.security.util.DerValue;


public class RsaUtil {


  public static final String ALGORITHM = "RSA";
  public static final int KEY_LENGTH = 1024;
  public static final String PUBLIC_KEY_FILEPATH = "key_pub.key";
  public static final String PRIVATE_KEY_FILEPATH = "key_pri.key";
  private static final String public_exponent = PropertiesUtil.getProperty("public_exponent");
  private static final String private_exponent = PropertiesUtil.getProperty("private_exponent");
  private static PublicKey pubKey;  
  private static PrivateKey priKey;  


  static{
    try {
      loadExistKeyPair(false);
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }


  public static synchronized KeyPair generatorNewKeyPair() throws IOException {
      KeyPair keyPair;
      try {
          KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
          keyPairGenerator.initialize(KEY_LENGTH);
          keyPair = keyPairGenerator.generateKeyPair();
      } catch (NoSuchAlgorithmException e) {
          throw new RuntimeException("初始化密钥对时发生错误:"+ KEY_LENGTH,e);
      }


      try {
          Path publicKeyPath = Paths.get(PUBLIC_KEY_FILEPATH);
          Files.write(publicKeyPath, Base64.encodeToByte(keyPair.getPublic().getEncoded(), false));
      } catch (IOException e) {
          throw new IOException("写入公钥到本地文件时发生错误:"+PUBLIC_KEY_FILEPATH,e);
      }


      try {
          Path privateKeyPath = Paths.get(PRIVATE_KEY_FILEPATH);
          Files.write(privateKeyPath,Base64.encodeToByte(keyPair.getPrivate().getEncoded(), false));
      } catch (IOException e) {
          throw new IOException("写入私钥到本地文件时发生错误:"+PRIVATE_KEY_FILEPATH,e);
      }


      return keyPair;
  }


  /**
   * 加载公钥私钥
   * @param ifNotExistCreateNew
   * @return
   * @throws IOException
   * @throws InvalidKeyException
   */
  public static KeyPair loadExistKeyPair(boolean ifNotExistCreateNew) throws IOException, InvalidKeyException {
      if(ifNotExistCreateNew){
          return generatorNewKeyPair();
      }
//      Path private_key_path = Paths.get(PRIVATE_KEY_FILEPATH);
//      if(!Files.exists(private_key_path)){
//          throw new IOException("在系统目录下不存在私钥:"+PRIVATE_KEY_FILEPATH);
//      }
//      Path public_key_path = Paths.get(PUBLIC_KEY_FILEPATH);
//      if(!Files.exists(public_key_path)){
//          throw new IOException("在系统目录下不存在公钥:"+PUBLIC_KEY_FILEPATH);
//      }
//      
//      byte[] public_key_bytes = Base64.decode(Files.readAllBytes(public_key_path));
//      byte[] private_key_bytes = Base64.decode(Files.readAllBytes(private_key_path));
      byte[] public_key_bytes = Base64.decode(public_exponent.getBytes());
      byte[] private_key_bytes = Base64.decode(private_exponent.getBytes());
      pubKey = RSAPublicKeyImpl.parse(new DerValue(public_key_bytes));
      priKey = RSAPrivateKeyImpl.parseKey(new DerValue(private_key_bytes));
      return new KeyPair(pubKey, priKey);
  }


  /**
   * 公钥加密
   * @param publicKey
   * @param data
   * @return
   * @throws BadPaddingException
   */
  public static byte[] encrypt(PublicKey publicKey, byte[] data) throws BadPaddingException {
      try {
          byte[] bytes = cipherDoFinal(publicKey, Cipher.ENCRYPT_MODE, data);
          return Base64.encodeToByte(bytes, false);
      } catch (NoSuchAlgorithmException | NoSuchPaddingException e1) {
          throw new RuntimeException("初始化加密器时发生错误", e1);
      } catch (InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
          e.printStackTrace();
          throw new BadPaddingException("加密时发生错误");
      }
  }
  
  /**
   * 公钥加密
   * @param data
   * @return
   * @throws BadPaddingException
   */
  public static String encrypt(byte[] data) throws BadPaddingException {
    byte[] bytes = encrypt(pubKey, data);
    return new String(bytes);
  }


  /**
   * 私钥解密
   * @param privateKey
   * @param data
   * @return
   * @throws BadPaddingException
   */
  public static byte[] decrypt(PrivateKey privateKey, byte[] data) throws BadPaddingException {
      try {
          byte[] decode = Base64.decode(data);
          byte[] bytes = cipherDoFinal(privateKey, Cipher.DECRYPT_MODE, decode);
          return bytes;
      } catch (NoSuchAlgorithmException | NoSuchPaddingException e1) {
          throw new RuntimeException("初始化解密器时发生错误", e1);
      } catch (InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
          e.printStackTrace();
          throw new BadPaddingException("解密时发生错误");
      }
  }


  /**
   * 私钥解密
   * @param data
   * @return
   * @throws BadPaddingException
   */
  public static String decrypt(byte[] data) throws BadPaddingException {
    byte[] bytes = decrypt(priKey, data);
    return new String(bytes);
  }
  
  private static byte[] cipherDoFinal(Key key, int mode, byte[] data) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException {
      final Cipher instance = Cipher.getInstance(ALGORITHM);
      instance.init(mode, key);
      return instance.doFinal(data);
  }
  
  public static void main(String[] args) throws Exception {  
    String ming = "00001,001,2015-08-12 12:12:12,01,48BE23F2*"; 
//    String mi = encrypt(ming.getBytes());
    String mi = "LPy9eqF9Jb4wXRohyxUAxmCpcfgexzWnThhDB8CzIDA63ewJN+cVoezwOJ3JySDFgyO1EKd3UObMGZm84cGKD864J2+eUoiDKA9xb9QCrZdT940l17v533t5To0Ufp9SGZPC2gGYxySk8gQZm67KiP+d1hOY25GQ44aUa4pIw50=";
    System.err.println("mi:"+mi);  
    System.err.println("mi size:"+mi.length());  
    ming = decrypt(mi.getBytes());
    System.err.println(ming); 
  }
  
}
0 0
原创粉丝点击