java 非对称加密rsa的工具类及其源代码

package com;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.net.URLDecoder;
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.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.HashMap;
import javax.crypto.Cipher;
//import org.apache.axiom.om.util.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class RSAUtil
{
  private static String pubkey_modulus = "134190067438897081826740582440145422067900869849008684403538378941638802869993945880496658625706645091742373920883566067677773654354320529012495415902271883254486238289053260665883526826613130572068941537303300311148421800542854498460474283729308331346202252786121204803282713475685119875019014661914373104191";
      //"149456638099916245660005476770188313498627726664323766755721852765419292262673340867433127644309252714933757460748873481832527969552482308187075637909546476465102044823464982159467966045599649129861613835391725016815239759013533084997967161760549347170552416490577364208439610669258620427401217196643371642911";

  private static String private_exponent ="82272473560924724123476255291323728643519307435540503044365405866212807087892743632211365186681091695245438859194387417265981402957275328078048709986254872971222005560076228296902625258923375716022005085860155515851885266825475022765290746252800809495793873729187152347301854364000286340863093616915435947865";
      //"56791105155899938441965857271587035888983723348973171849760307908772702980260832928295271033557125293498258419595483411173466042476241923200371463613858359315835588820905303650647448710244829393562979299175488100200137865633304885569817664914187476876115101666452819556995176937752180225848937940730519112529";

  private static String public_exponent = "65537";
      //"65537";
  private static BouncyCastleProvider bouncyCastleProvider = null;

  public static byte[] encrypt(byte[] data)
    throws Exception
  {
    byte[] result = (byte[])null;
    try {
      PublicKey publicKey = getPublicKey(pubkey_modulus, public_exponent);
      result = encrypt(publicKey, data);
    } catch (Exception e) {
      result = (byte[])null;
      e.printStackTrace();
    }
    return result;
  }

  public static String decrypt(String encStr)
  {
    String decStr = null;
    try {
      byte[] raw = hexStringToBytes(encStr);
      PrivateKey priavteKey = getPrivateKey(pubkey_modulus, private_exponent);

      byte[] result = decrypt(priavteKey, raw);

      StringBuffer sb = new StringBuffer();
      sb.append(new String(result));
      String reserseStr = sb.reverse().toString();

      decStr = URLDecoder.decode(reserseStr, "UTF-8");
    } catch (Exception e) {
      decStr = null;
      e.printStackTrace();
    }
    return decStr;
  }

  public static RSAPublicKey getPublicKey(String modulus, String exponent)
  {
    try
    {
      BigInteger b1 = new BigInteger(modulus);
      BigInteger b2 = new BigInteger(exponent);
      KeyFactory keyFactory = KeyFactory.getInstance("RSA", getBcpInstance());
      RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
      return (RSAPublicKey)keyFactory.generatePublic(keySpec);
    }
    catch (Exception e) {
      e.printStackTrace();
    }return null;
  }

  public static RSAPrivateKey getPrivateKey(String modulus, String exponent)
    throws Exception
  {
    try
    {
      BigInteger b1 = new BigInteger(modulus);
      BigInteger b2 = new BigInteger(exponent);
      KeyFactory keyFactory = KeyFactory.getInstance("RSA", getBcpInstance());
      RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
      return (RSAPrivateKey)keyFactory.generatePrivate(keySpec);
    }
    catch (Exception e) {
      e.printStackTrace();
    }return null;
  }

  public static byte[] encrypt(PublicKey pk, byte[] data)
    throws Exception
  {
    try
    {
      Cipher cipher = Cipher.getInstance("RSA", getBcpInstance());
      cipher.init(1, pk);
      int blockSize = cipher.getBlockSize();

      int outputSize = cipher.getOutputSize(data.length);
      int leavedSize = data.length % blockSize;
      int blocksSize = leavedSize != 0 ? data.length / blockSize + 1 :
        data.length / blockSize;
      byte[] raw = new byte[outputSize * blocksSize];
      int i = 0;
      while (data.length - i * blockSize > 0) {
        if (data.length - i * blockSize > blockSize)
          cipher.doFinal(data, i * blockSize, blockSize, raw, i *
            outputSize);
        else {
          cipher.doFinal(data, i * blockSize, data.length - i *
            blockSize, raw, i * outputSize);
        }

        i++;
      }
      return raw;
    } catch (Exception e) {
      throw new Exception(e.getMessage());
    }
  }

  public static byte[] decrypt(PrivateKey pk, byte[] raw)
    throws Exception
  {
    try
    {
      Cipher cipher = Cipher.getInstance("RSA", getBcpInstance());
      cipher.init(2, pk);
      int blockSize = cipher.getBlockSize();
      ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
      int j = 0;
      while (raw.length - j * blockSize > 0) {
        bout.write(cipher.doFinal(raw, j * blockSize, blockSize));
        j++;
      }
      return bout.toByteArray();
    } catch (Exception e) {
      throw new Exception(e.getMessage());
    }
  }

  public static byte[] hexStringToBytes(String hexString)
  {
    if ((hexString == null) || (hexString.equals(""))) {
      return null;
    }
    hexString = hexString.toUpperCase();
    int length = hexString.length() / 2;
    char[] hexChars = hexString.toCharArray();
    byte[] d = new byte[length];
    for (int i = 0; i < length; i++) {
      int pos = i * 2;
      d[i] = ((byte)(charToByte(hexChars[pos]) << 4 | charToByte(hexChars[(pos + 1)])));
    }
    return d;
  }

  private static byte charToByte(char c)
  {
    return (byte)"0123456789ABCDEF".indexOf(c);
  }

  public static HashMap<String, Object> generateRSAKeys()
    throws NoSuchAlgorithmException
  {
    HashMap map = new HashMap();
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", getBcpInstance());
    keyPairGen.initialize(1024);//重要加密字符的大小
    KeyPair keyPair = keyPairGen.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();
    System.out.println("----转换前publicKey---" + publicKey);
    System.out.println("----转换前privateKey---" + privateKey);

    map.put("public static", publicKey);
    map.put("private", privateKey);

    String modulus = publicKey.getModulus().toString();
    System.out.println("pubkey modulus=" + modulus);

    String public_exponent = publicKey.getPublicExponent().toString();
    System.out.println("pubkey exponent=" + public_exponent);

    String private_exponent = privateKey.getPrivateExponent().toString();
    System.out.println("private exponent=" + private_exponent);
    bouncyCastleProvider = null;
    return map;
  }

  public static synchronized BouncyCastleProvider getBcpInstance()
  {
    if (bouncyCastleProvider == null) {
      bouncyCastleProvider = new BouncyCastleProvider();
    }
    return bouncyCastleProvider;
  }

  public static String encryptstr(String str)
  {
    String enStr = "";
    try {
      PublicKey publikcKey = getPublicKey(pubkey_modulus, public_exponent);
      byte[] enBytes = encrypt(publikcKey, str.getBytes());
      enStr = Base64.encode(enBytes);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return enStr;
  }

  public static String decryptstr(String data) {
    String decrptstr = "";
    try {
      PrivateKey priavteKey = getPrivateKey(pubkey_modulus, private_exponent);
      byte[] desBytes = decrypt(priavteKey, Base64.decode(data));
      decrptstr = new String(desBytes);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return decrptstr;
  }

      public static void main(String[] args) throws NoSuchAlgorithmException {
        String a = "fjajfaffffaaaafa叫阿法7*";
        System.out.println("原始数据" + a);
        System.out.println("加密数据" + encryptstr(a));
        System.out.println("解密数据" + decryptstr(encryptstr(a)));
        HashMap<String, Object> b=generateRSAKeys();
        System.out.println("获取的公锁和私锁" + b);
      }

}

java 非对称加密rsa的工具类及其源代码

java 非对称加密rsa的工具类及其源代码