RSA实例 java 安全

public class RSAUtil {

   public static String RSADecode(String password) {
      String pwd = password;
      try {
         password = org.apache.commons.lang.StringUtils.substring(pwd, 0,
               256);
         byte[] en_result = RSAUtil.hexStringToBytes(password);
         byte[] de_result = RSAUtil.decrypt(RSAUtil.getKeyPair()
               .getPrivate(), en_result);
         StringBuffer sb = new StringBuffer();
         sb.append(new String(de_result));
         password = sb.reverse().toString();
         password = URLDecoder.decode(password, "UTF-8");
         return password;
      } catch (Exception e) {
         e.printStackTrace();
         return "";
      }
   }


   public static KeyPair getKeyPair() throws Exception {
      File file = new File("c:/RSAKey.txt");
      InputStream fis = new FileInputStream(file);
      ObjectInputStream oos = new ObjectInputStream(fis);
      KeyPair kp = (KeyPair) oos.readObject();
      oos.close();
      if(fis!=null){
         fis.close();
      }
      return kp;
   }
   public static byte[] encrypt(PublicKey pk, byte[] data) throws Exception {
      try {
         Cipher cipher = Cipher.getInstance("RSA",
               new org.bouncycastle.jce.provider.BouncyCastleProvider());
         cipher.init(Cipher.ENCRYPT_MODE, 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",
               new org.bouncycastle.jce.provider.BouncyCastleProvider());
         cipher.init(Cipher.DECRYPT_MODE, 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);
   }
   private static String  getServletPath(){
      return getRequest().getServletContext().getRealPath("");
   }
   private static HttpServletRequest getRequest(){
      RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
      if (requestAttributes instanceof ServletRequestAttributes) {
         return ((ServletRequestAttributes) requestAttributes).getRequest();
      }
      return null;
   }


   public static void genKey() throws Exception {
      KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",
            new org.bouncycastle.jce.provider.BouncyCastleProvider());
      final int KEY_SIZE = 1024;
      keyPairGen.initialize(KEY_SIZE, new SecureRandom());
      KeyPair KP = keyPairGen.generateKeyPair();
      PublicKey publicKey = KP.getPublic();
      PrivateKey prKey = KP.getPrivate();
      System.out.println(publicKey);
      FileOutputStream ko = new FileOutputStream("c:/RSAKey.txt");
      ObjectOutputStream fo = new ObjectOutputStream(ko);
      fo.writeObject(KP);
      FileOutputStream out = new FileOutputStream("c:/PublicKey.txt");
      ObjectOutputStream fileOut = new ObjectOutputStream(out);
      fileOut.writeObject(publicKey);
      FileOutputStream outPrivate = new FileOutputStream("c:/PrivateKey.txt");
      ObjectOutputStream privateOut = new ObjectOutputStream(outPrivate);
      privateOut.writeObject(prKey);

      ko.close();
      out.close();
      outPrivate.close();
   }

  public static void main(String[] args) throws Exception {
      //genKey();
      RSAPublicKey rsap = (RSAPublicKey) RSAUtil.getKeyPair().getPublic();
      System.out.println(rsap.getModulus());
      String test = "hello world";
      PublicKey pk = getKeyPair().getPublic();
      System.out.println(pk.getEncoded().toString());
      PrivateKey ck = getKeyPair().getPrivate();
      byte[] en_test = encrypt(pk, test.getBytes());
      byte[] de_test = decrypt(ck, en_test);
      System.out.println(new String(de_test));


   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值