RSAutil.java 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package com.zksy.visualization.utils;
  2. import javax.crypto.Cipher;
  3. import java.security.KeyFactory;
  4. import java.security.interfaces.RSAPublicKey;
  5. import java.security.spec.X509EncodedKeySpec;
  6. import java.util.Arrays;
  7. public class RSAutil {
  8. /**
  9. * 基于原生RSA公钥加密
  10. * @param password 用户密码
  11. * @param publicKey 公钥
  12. * @return
  13. * @throws Exception
  14. */
  15. public static String encrypt(String password, String publicKey) throws Exception {
  16. //base64编码的公钥
  17. byte[] decoded = java.util.Base64.getDecoder().decode(publicKey);
  18. RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
  19. //RSA加密
  20. Cipher cipher = Cipher.getInstance("RSA");
  21. cipher.init(Cipher.ENCRYPT_MODE, pubKey);
  22. String outStr;
  23. byte[] inputArray = password.getBytes("UTF-8");
  24. int inputLength = inputArray.length;
  25. // 最大加密字节数,超出最大字节数需要分组加密
  26. int MAX_ENCRYPT_BLOCK = 117;
  27. // 标识
  28. int offSet = 0;
  29. byte[] resultBytes = {};
  30. byte[] cache = {};
  31. while (inputLength - offSet > 0) {
  32. if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
  33. cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);
  34. offSet += MAX_ENCRYPT_BLOCK;
  35. } else {
  36. cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
  37. offSet = inputLength;
  38. }
  39. resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
  40. System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
  41. }
  42. outStr = java.util.Base64.getEncoder().encodeToString(resultBytes);
  43. return outStr;
  44. }
  45. }