test2.java 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. package com;
  2. /*
  3. * Copyright 1999-2017 Alibaba Group Holding Ltd.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. import com.alibaba.druid.util.Base64;
  18. import com.alibaba.druid.util.JdbcUtils;
  19. import javax.crypto.Cipher;
  20. import java.io.ByteArrayOutputStream;
  21. import java.io.FileInputStream;
  22. import java.security.*;
  23. import java.security.cert.Certificate;
  24. import java.security.cert.CertificateFactory;
  25. import java.security.interfaces.RSAPrivateKey;
  26. import java.security.interfaces.RSAPublicKey;
  27. import java.security.spec.PKCS8EncodedKeySpec;
  28. import java.security.spec.RSAPrivateKeySpec;
  29. import java.security.spec.RSAPublicKeySpec;
  30. import java.security.spec.X509EncodedKeySpec;
  31. public class test2 {
  32. private static final String DEFAULT_PRIVATE_KEY_STRING = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAocbCrurZGbC5GArEHKlAfDSZi7gFBnd4yxOt0rwTqKBFzGyhtQLu5PRKjEiOXVa95aeIIBJ6OhC2f8FjqFUpawIDAQABAkAPejKaBYHrwUqUEEOe8lpnB6lBAsQIUFnQI/vXU4MV+MhIzW0BLVZCiarIQqUXeOhThVWXKFt8GxCykrrUsQ6BAiEA4vMVxEHBovz1di3aozzFvSMdsjTcYRRo82hS5Ru2/OECIQC2fAPoXixVTVY7bNMeuxCP4954ZkXp7fEPDINCjcQDywIgcc8XLkkPcs3Jxk7uYofaXaPbg39wuJpEmzPIxi3k0OECIGubmdpOnin3HuCP/bbjbJLNNoUdGiEmFL5hDI4UdwAdAiEAtcAwbm08bKN7pwwvyqaCBC//VnEWaq39DCzxr+Z2EIk=";
  33. public static final String DEFAULT_PUBLIC_KEY_STRING = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKHGwq7q2RmwuRgKxBypQHw0mYu4BQZ3eMsTrdK8E6igRcxsobUC7uT0SoxIjl1WveWniCASejoQtn/BY6hVKWsCAwEAAQ==";
  34. public static void main(String[] args) throws Exception {
  35. String password = "fgjdb-1234";
  36. String[] arr = genKeyPair(512);
  37. System.out.println("privateKey:" + arr[0]);
  38. System.out.println("publicKey:" + arr[1]);
  39. System.out.println("password:" + encrypt(arr[0], password));
  40. }
  41. public static String decrypt(String cipherText) throws Exception {
  42. return decrypt((String) null, cipherText);
  43. }
  44. public static String decrypt(String publicKeyText, String cipherText)
  45. throws Exception {
  46. PublicKey publicKey = getPublicKey(publicKeyText);
  47. return decrypt(publicKey, cipherText);
  48. }
  49. public static PublicKey getPublicKeyByX509(String x509File) {
  50. if (x509File == null || x509File.length() == 0) {
  51. return com.alibaba.druid.filter.config.ConfigTools.getPublicKey(null);
  52. }
  53. FileInputStream in = null;
  54. try {
  55. in = new FileInputStream(x509File);
  56. CertificateFactory factory = CertificateFactory
  57. .getInstance("X.509");
  58. Certificate cer = factory.generateCertificate(in);
  59. return cer.getPublicKey();
  60. } catch (Exception e) {
  61. throw new IllegalArgumentException("Failed to get public key", e);
  62. } finally {
  63. JdbcUtils.close(in);
  64. }
  65. }
  66. public static PublicKey getPublicKey(String publicKeyText) {
  67. if (publicKeyText == null || publicKeyText.length() == 0) {
  68. publicKeyText = com.alibaba.druid.filter.config.ConfigTools.DEFAULT_PUBLIC_KEY_STRING;
  69. }
  70. try {
  71. byte[] publicKeyBytes = Base64.base64ToByteArray(publicKeyText);
  72. X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(
  73. publicKeyBytes);
  74. KeyFactory keyFactory = KeyFactory.getInstance("RSA", "SunRsaSign");
  75. return keyFactory.generatePublic(x509KeySpec);
  76. } catch (Exception e) {
  77. throw new IllegalArgumentException("Failed to get public key", e);
  78. }
  79. }
  80. public static PublicKey getPublicKeyByPublicKeyFile(String publicKeyFile) {
  81. if (publicKeyFile == null || publicKeyFile.length() == 0) {
  82. return com.alibaba.druid.filter.config.ConfigTools.getPublicKey(null);
  83. }
  84. FileInputStream in = null;
  85. try {
  86. in = new FileInputStream(publicKeyFile);
  87. ByteArrayOutputStream out = new ByteArrayOutputStream();
  88. int len = 0;
  89. byte[] b = new byte[512 / 8];
  90. while ((len = in.read(b)) != -1) {
  91. out.write(b, 0, len);
  92. }
  93. byte[] publicKeyBytes = out.toByteArray();
  94. X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyBytes);
  95. KeyFactory factory = KeyFactory.getInstance("RSA", "SunRsaSign");
  96. return factory.generatePublic(spec);
  97. } catch (Exception e) {
  98. throw new IllegalArgumentException("Failed to get public key", e);
  99. } finally {
  100. JdbcUtils.close(in);
  101. }
  102. }
  103. public static String decrypt(PublicKey publicKey, String cipherText)
  104. throws Exception {
  105. Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  106. try {
  107. cipher.init(Cipher.DECRYPT_MODE, publicKey);
  108. } catch (InvalidKeyException e) {
  109. // 因为 IBM JDK 不支持私钥加密, 公钥解密, 所以要反转公私钥
  110. // 也就是说对于解密, 可以通过公钥的参数伪造一个私钥对象欺骗 IBM JDK
  111. RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
  112. RSAPrivateKeySpec spec = new RSAPrivateKeySpec(rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent());
  113. Key fakePrivateKey = KeyFactory.getInstance("RSA").generatePrivate(spec);
  114. cipher = Cipher.getInstance("RSA"); //It is a stateful object. so we need to get new one.
  115. cipher.init(Cipher.DECRYPT_MODE, fakePrivateKey);
  116. }
  117. if (cipherText == null || cipherText.length() == 0) {
  118. return cipherText;
  119. }
  120. byte[] cipherBytes = Base64.base64ToByteArray(cipherText);
  121. byte[] plainBytes = cipher.doFinal(cipherBytes);
  122. return new String(plainBytes);
  123. }
  124. public static String encrypt(String plainText) throws Exception {
  125. return encrypt((String) null, plainText);
  126. }
  127. public static String encrypt(String key, String plainText) throws Exception {
  128. if (key == null) {
  129. key = DEFAULT_PRIVATE_KEY_STRING;
  130. }
  131. byte[] keyBytes = Base64.base64ToByteArray(key);
  132. return encrypt(keyBytes, plainText);
  133. }
  134. public static String encrypt(byte[] keyBytes, String plainText)
  135. throws Exception {
  136. PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
  137. KeyFactory factory = KeyFactory.getInstance("RSA", "SunRsaSign");
  138. PrivateKey privateKey = factory.generatePrivate(spec);
  139. Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  140. try {
  141. cipher.init(Cipher.ENCRYPT_MODE, privateKey);
  142. } catch (InvalidKeyException e) {
  143. //For IBM JDK, 原因请看解密方法中的说明
  144. RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
  145. RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getPrivateExponent());
  146. Key fakePublicKey = KeyFactory.getInstance("RSA").generatePublic(publicKeySpec);
  147. cipher = Cipher.getInstance("RSA");
  148. cipher.init(Cipher.ENCRYPT_MODE, fakePublicKey);
  149. }
  150. byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
  151. String encryptedString = Base64.byteArrayToBase64(encryptedBytes);
  152. return encryptedString;
  153. }
  154. public static byte[][] genKeyPairBytes(int keySize)
  155. throws NoSuchAlgorithmException, NoSuchProviderException {
  156. byte[][] keyPairBytes = new byte[2][];
  157. KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA", "SunRsaSign");
  158. gen.initialize(keySize, new SecureRandom());
  159. KeyPair pair = gen.generateKeyPair();
  160. keyPairBytes[0] = pair.getPrivate().getEncoded();
  161. keyPairBytes[1] = pair.getPublic().getEncoded();
  162. return keyPairBytes;
  163. }
  164. public static String[] genKeyPair(int keySize)
  165. throws NoSuchAlgorithmException, NoSuchProviderException {
  166. byte[][] keyPairBytes = genKeyPairBytes(keySize);
  167. String[] keyPairs = new String[2];
  168. keyPairs[0] = Base64.byteArrayToBase64(keyPairBytes[0]);
  169. keyPairs[1] = Base64.byteArrayToBase64(keyPairBytes[1]);
  170. return keyPairs;
  171. }
  172. }