转载

Java使用RSA加密解密签名及校验

由于项目要用到非对称加密解密签名校验什么的,于是参考《Java加密解密的艺术》写一个RSA进行加密解密签名及校验的Demo,代码很简单,特此分享!

RSA加密解密类:

  1. package com.ihep;
  2. import java.io.BufferedReader;
  3. import java.io.BufferedWriter;
  4. import java.io.FileReader;
  5. import java.io.FileWriter;
  6. import java.io.IOException;
  7. import java.security.InvalidKeyException;
  8. import java.security.KeyFactory;
  9. import java.security.KeyPair;
  10. import java.security.KeyPairGenerator;
  11. import java.security.NoSuchAlgorithmException;
  12. import java.security.SecureRandom;
  13. import java.security.interfaces.RSAPrivateKey;
  14. import java.security.interfaces.RSAPublicKey;
  15. import java.security.spec.InvalidKeySpecException;
  16. import java.security.spec.PKCS8EncodedKeySpec;
  17. import java.security.spec.X509EncodedKeySpec;
  18. import javax.crypto.BadPaddingException;
  19. import javax.crypto.Cipher;
  20. import javax.crypto.IllegalBlockSizeException;
  21. import javax.crypto.NoSuchPaddingException;
  22. import com.fcplay.Base64;
  23. public class RSAEncrypt {
  24. /**
  25. * 字节数据转字符串专用集合
  26. */
  27. private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6',
  28. '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  29. /**
  30. * 随机生成密钥对
  31. */
  32. public static void genKeyPair(String filePath) {
  33. // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
  34. KeyPairGenerator keyPairGen = null;
  35. try {
  36. keyPairGen = KeyPairGenerator.getInstance("RSA");
  37. } catch (NoSuchAlgorithmException e) {
  38. // TODO Auto-generated catch block
  39. e.printStackTrace();
  40. }
  41. // 初始化密钥对生成器,密钥大小为96-1024位
  42. keyPairGen.initialize(1024,new SecureRandom());
  43. // 生成一个密钥对,保存在keyPair中
  44. KeyPair keyPair = keyPairGen.generateKeyPair();
  45. // 得到私钥
  46. RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
  47. // 得到公钥
  48. RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
  49. try {
  50. // 得到公钥字符串
  51. String publicKeyString = Base64.encode(publicKey.getEncoded());
  52. // 得到私钥字符串
  53. String privateKeyString = Base64.encode(privateKey.getEncoded());
  54. // 将密钥对写入到文件
  55. FileWriter pubfw = new FileWriter(filePath + "/publicKey.keystore");
  56. FileWriter prifw = new FileWriter(filePath + "/privateKey.keystore");
  57. BufferedWriter pubbw = new BufferedWriter(pubfw);
  58. BufferedWriter pribw = new BufferedWriter(prifw);
  59. pubbw.write(publicKeyString);
  60. pribw.write(privateKeyString);
  61. pubbw.flush();
  62. pubbw.close();
  63. pubfw.close();
  64. pribw.flush();
  65. pribw.close();
  66. prifw.close();
  67. } catch (Exception e) {
  68. e.printStackTrace();
  69. }
  70. }
  71. /**
  72. * 从文件中输入流中加载公钥
  73. *
  74. * @param in
  75. * 公钥输入流
  76. * @throws Exception
  77. * 加载公钥时产生的异常
  78. */
  79. public static String loadPublicKeyByFile(String path) throws Exception {
  80. try {
  81. BufferedReader br = new BufferedReader(new FileReader(path
  82. + "/publicKey.keystore"));
  83. String readLine = null;
  84. StringBuilder sb = new StringBuilder();
  85. while ((readLine = br.readLine()) != null) {
  86. sb.append(readLine);
  87. }
  88. br.close();
  89. return sb.toString();
  90. } catch (IOException e) {
  91. throw new Exception("公钥数据流读取错误");
  92. } catch (NullPointerException e) {
  93. throw new Exception("公钥输入流为空");
  94. }
  95. }
  96. /**
  97. * 从字符串中加载公钥
  98. *
  99. * @param publicKeyStr
  100. * 公钥数据字符串
  101. * @throws Exception
  102. * 加载公钥时产生的异常
  103. */
  104. public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr)
  105. throws Exception {
  106. try {
  107. byte[] buffer = Base64.decode(publicKeyStr);
  108. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  109. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
  110. return (RSAPublicKey) keyFactory.generatePublic(keySpec);
  111. } catch (NoSuchAlgorithmException e) {
  112. throw new Exception("无此算法");
  113. } catch (InvalidKeySpecException e) {
  114. throw new Exception("公钥非法");
  115. } catch (NullPointerException e) {
  116. throw new Exception("公钥数据为空");
  117. }
  118. }
  119. /**
  120. * 从文件中加载私钥
  121. *
  122. * @param keyFileName
  123. * 私钥文件名
  124. * @return 是否成功
  125. * @throws Exception
  126. */
  127. public static String loadPrivateKeyByFile(String path) throws Exception {
  128. try {
  129. BufferedReader br = new BufferedReader(new FileReader(path
  130. + "/privateKey.keystore"));
  131. String readLine = null;
  132. StringBuilder sb = new StringBuilder();
  133. while ((readLine = br.readLine()) != null) {
  134. sb.append(readLine);
  135. }
  136. br.close();
  137. return sb.toString();
  138. } catch (IOException e) {
  139. throw new Exception("私钥数据读取错误");
  140. } catch (NullPointerException e) {
  141. throw new Exception("私钥输入流为空");
  142. }
  143. }
  144. public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)
  145. throws Exception {
  146. try {
  147. byte[] buffer = Base64.decode(privateKeyStr);
  148. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
  149. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  150. return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
  151. } catch (NoSuchAlgorithmException e) {
  152. throw new Exception("无此算法");
  153. } catch (InvalidKeySpecException e) {
  154. throw new Exception("私钥非法");
  155. } catch (NullPointerException e) {
  156. throw new Exception("私钥数据为空");
  157. }
  158. }
  159. /**
  160. * 公钥加密过程
  161. *
  162. * @param publicKey
  163. * 公钥
  164. * @param plainTextData
  165. * 明文数据
  166. * @return
  167. * @throws Exception
  168. * 加密过程中的异常信息
  169. */
  170. public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData)
  171. throws Exception {
  172. if (publicKey == null) {
  173. throw new Exception("加密公钥为空, 请设置");
  174. }
  175. Cipher cipher = null;
  176. try {
  177. // 使用默认RSA
  178. cipher = Cipher.getInstance("RSA");
  179. // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
  180. cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  181. byte[] output = cipher.doFinal(plainTextData);
  182. return output;
  183. } catch (NoSuchAlgorithmException e) {
  184. throw new Exception("无此加密算法");
  185. } catch (NoSuchPaddingException e) {
  186. e.printStackTrace();
  187. return null;
  188. } catch (InvalidKeyException e) {
  189. throw new Exception("加密公钥非法,请检查");
  190. } catch (IllegalBlockSizeException e) {
  191. throw new Exception("明文长度非法");
  192. } catch (BadPaddingException e) {
  193. throw new Exception("明文数据已损坏");
  194. }
  195. }
  196. /**
  197. * 私钥加密过程
  198. *
  199. * @param privateKey
  200. * 私钥
  201. * @param plainTextData
  202. * 明文数据
  203. * @return
  204. * @throws Exception
  205. * 加密过程中的异常信息
  206. */
  207. public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData)
  208. throws Exception {
  209. if (privateKey == null) {
  210. throw new Exception("加密私钥为空, 请设置");
  211. }
  212. Cipher cipher = null;
  213. try {
  214. // 使用默认RSA
  215. cipher = Cipher.getInstance("RSA");
  216. cipher.init(Cipher.ENCRYPT_MODE, privateKey);
  217. byte[] output = cipher.doFinal(plainTextData);
  218. return output;
  219. } catch (NoSuchAlgorithmException e) {
  220. throw new Exception("无此加密算法");
  221. } catch (NoSuchPaddingException e) {
  222. e.printStackTrace();
  223. return null;
  224. } catch (InvalidKeyException e) {
  225. throw new Exception("加密私钥非法,请检查");
  226. } catch (IllegalBlockSizeException e) {
  227. throw new Exception("明文长度非法");
  228. } catch (BadPaddingException e) {
  229. throw new Exception("明文数据已损坏");
  230. }
  231. }
  232. /**
  233. * 私钥解密过程
  234. *
  235. * @param privateKey
  236. * 私钥
  237. * @param cipherData
  238. * 密文数据
  239. * @return 明文
  240. * @throws Exception
  241. * 解密过程中的异常信息
  242. */
  243. public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData)
  244. throws Exception {
  245. if (privateKey == null) {
  246. throw new Exception("解密私钥为空, 请设置");
  247. }
  248. Cipher cipher = null;
  249. try {
  250. // 使用默认RSA
  251. cipher = Cipher.getInstance("RSA");
  252. // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
  253. cipher.init(Cipher.DECRYPT_MODE, privateKey);
  254. byte[] output = cipher.doFinal(cipherData);
  255. return output;
  256. } catch (NoSuchAlgorithmException e) {
  257. throw new Exception("无此解密算法");
  258. } catch (NoSuchPaddingException e) {
  259. e.printStackTrace();
  260. return null;
  261. } catch (InvalidKeyException e) {
  262. throw new Exception("解密私钥非法,请检查");
  263. } catch (IllegalBlockSizeException e) {
  264. throw new Exception("密文长度非法");
  265. } catch (BadPaddingException e) {
  266. throw new Exception("密文数据已损坏");
  267. }
  268. }
  269. /**
  270. * 公钥解密过程
  271. *
  272. * @param publicKey
  273. * 公钥
  274. * @param cipherData
  275. * 密文数据
  276. * @return 明文
  277. * @throws Exception
  278. * 解密过程中的异常信息
  279. */
  280. public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData)
  281. throws Exception {
  282. if (publicKey == null) {
  283. throw new Exception("解密公钥为空, 请设置");
  284. }
  285. Cipher cipher = null;
  286. try {
  287. // 使用默认RSA
  288. cipher = Cipher.getInstance("RSA");
  289. // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
  290. cipher.init(Cipher.DECRYPT_MODE, publicKey);
  291. byte[] output = cipher.doFinal(cipherData);
  292. return output;
  293. } catch (NoSuchAlgorithmException e) {
  294. throw new Exception("无此解密算法");
  295. } catch (NoSuchPaddingException e) {
  296. e.printStackTrace();
  297. return null;
  298. } catch (InvalidKeyException e) {
  299. throw new Exception("解密公钥非法,请检查");
  300. } catch (IllegalBlockSizeException e) {
  301. throw new Exception("密文长度非法");
  302. } catch (BadPaddingException e) {
  303. throw new Exception("密文数据已损坏");
  304. }
  305. }
  306. /**
  307. * 字节数据转十六进制字符串
  308. *
  309. * @param data
  310. * 输入数据
  311. * @return 十六进制内容
  312. */
  313. public static String byteArrayToString(byte[] data) {
  314. StringBuilder stringBuilder = new StringBuilder();
  315. for (int i = 0; i < data.length; i++) {
  316. // 取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移
  317. stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);
  318. // 取出字节的低四位 作为索引得到相应的十六进制标识符
  319. stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
  320. if (i < data.length - 1) {
  321. stringBuilder.append(' ');
  322. }
  323. }
  324. return stringBuilder.toString();
  325. }
  326. }


签名及校验类:

  1. package com.ihep;
  2. import java.security.KeyFactory;
  3. import java.security.PrivateKey;
  4. import java.security.PublicKey;
  5. import java.security.spec.PKCS8EncodedKeySpec;
  6. import java.security.spec.X509EncodedKeySpec;
  7. /**
  8. * RSA签名验签类
  9. */
  10. public class RSASignature{
  11. /**
  12. * 签名算法
  13. */
  14. public static final String SIGN_ALGORITHMS = "SHA1WithRSA";
  15. /**
  16. * RSA签名
  17. * @param content 待签名数据
  18. * @param privateKey 商户私钥
  19. * @param encode 字符集编码
  20. * @return 签名值
  21. */
  22. public static String sign(String content, String privateKey, String encode)
  23. {
  24. try
  25. {
  26. PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec( Base64.decode(privateKey) );
  27. KeyFactory keyf = KeyFactory.getInstance("RSA");
  28. PrivateKey priKey = keyf.generatePrivate(priPKCS8);
  29. java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
  30. signature.initSign(priKey);
  31. signature.update( content.getBytes(encode));
  32. byte[] signed = signature.sign();
  33. return Base64.encode(signed);
  34. }
  35. catch (Exception e)
  36. {
  37. e.printStackTrace();
  38. }
  39. return null;
  40. }
  41. public static String sign(String content, String privateKey)
  42. {
  43. try
  44. {
  45. PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec( Base64.decode(privateKey) );
  46. KeyFactory keyf = KeyFactory.getInstance("RSA");
  47. PrivateKey priKey = keyf.generatePrivate(priPKCS8);
  48. java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
  49. signature.initSign(priKey);
  50. signature.update( content.getBytes());
  51. byte[] signed = signature.sign();
  52. return Base64.encode(signed);
  53. }
  54. catch (Exception e)
  55. {
  56. e.printStackTrace();
  57. }
  58. return null;
  59. }
  60. /**
  61. * RSA验签名检查
  62. * @param content 待签名数据
  63. * @param sign 签名值
  64. * @param publicKey 分配给开发商公钥
  65. * @param encode 字符集编码
  66. * @return 布尔值
  67. */
  68. public static boolean doCheck(String content, String sign, String publicKey,String encode)
  69. {
  70. try
  71. {
  72. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  73. byte[] encodedKey = Base64.decode(publicKey);
  74. PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
  75. java.security.Signature signature = java.security.Signature
  76. .getInstance(SIGN_ALGORITHMS);
  77. signature.initVerify(pubKey);
  78. signature.update( content.getBytes(encode) );
  79. boolean bverify = signature.verify( Base64.decode(sign) );
  80. return bverify;
  81. }
  82. catch (Exception e)
  83. {
  84. e.printStackTrace();
  85. }
  86. return false;
  87. }
  88. public static boolean doCheck(String content, String sign, String publicKey)
  89. {
  90. try
  91. {
  92. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  93. byte[] encodedKey = Base64.decode(publicKey);
  94. PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
  95. java.security.Signature signature = java.security.Signature
  96. .getInstance(SIGN_ALGORITHMS);
  97. signature.initVerify(pubKey);
  98. signature.update( content.getBytes() );
  99. boolean bverify = signature.verify( Base64.decode(sign) );
  100. return bverify;
  101. }
  102. catch (Exception e)
  103. {
  104. e.printStackTrace();
  105. }
  106. return false;
  107. }
  108. }

再来一个Base64的类,当然你也可以用commons-codec-1.9.jar

  1. package com.ihep;
  2. public final class Base64 {
  3. static private final int BASELENGTH = 128;
  4. static private final int LOOKUPLENGTH = 64;
  5. static private final int TWENTYFOURBITGROUP = 24;
  6. static private final int EIGHTBIT = 8;
  7. static private final int SIXTEENBIT = 16;
  8. static private final int FOURBYTE = 4;
  9. static private final int SIGN = -128;
  10. static private final char PAD = '=';
  11. static private final boolean fDebug = false;
  12. static final private byte[] base64Alphabet = new byte[BASELENGTH];
  13. static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
  14. static {
  15. for (int i = 0; i < BASELENGTH; ++i) {
  16. base64Alphabet[i] = -1;
  17. }
  18. for (int i = 'Z'; i >= 'A'; i--) {
  19. base64Alphabet[i] = (byte) (i - 'A');
  20. }
  21. for (int i = 'z'; i >= 'a'; i--) {
  22. base64Alphabet[i] = (byte) (i - 'a' + 26);
  23. }
  24. for (int i = '9'; i >= '0'; i--) {
  25. base64Alphabet[i] = (byte) (i - '0' + 52);
  26. }
  27. base64Alphabet['+'] = 62;
  28. base64Alphabet['/'] = 63;
  29. for (int i = 0; i <= 25; i++) {
  30. lookUpBase64Alphabet[i] = (char) ('A' + i);
  31. }
  32. for (int i = 26, j = 0; i <= 51; i++, j++) {
  33. lookUpBase64Alphabet[i] = (char) ('a' + j);
  34. }
  35. for (int i = 52, j = 0; i <= 61; i++, j++) {
  36. lookUpBase64Alphabet[i] = (char) ('0' + j);
  37. }
  38. lookUpBase64Alphabet[62] = (char) '+';
  39. lookUpBase64Alphabet[63] = (char) '/';
  40. }
  41. private static boolean isWhiteSpace(char octect) {
  42. return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
  43. }
  44. private static boolean isPad(char octect) {
  45. return (octect == PAD);
  46. }
  47. private static boolean isData(char octect) {
  48. return (octect < BASELENGTH && base64Alphabet[octect] != -1);
  49. }
  50. /**
  51. * Encodes hex octects into Base64
  52. *
  53. * @param binaryData Array containing binaryData
  54. * @return Encoded Base64 array
  55. */
  56. public static String encode(byte[] binaryData) {
  57. if (binaryData == null) {
  58. return null;
  59. }
  60. int lengthDataBits = binaryData.length * EIGHTBIT;
  61. if (lengthDataBits == 0) {
  62. return "";
  63. }
  64. int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
  65. int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
  66. int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
  67. char encodedData[] = null;
  68. encodedData = new char[numberQuartet * 4];
  69. byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
  70. int encodedIndex = 0;
  71. int dataIndex = 0;
  72. if (fDebug) {
  73. System.out.println("number of triplets = " + numberTriplets);
  74. }
  75. for (int i = 0; i < numberTriplets; i++) {
  76. b1 = binaryData[dataIndex++];
  77. b2 = binaryData[dataIndex++];
  78. b3 = binaryData[dataIndex++];
  79. if (fDebug) {
  80. System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= " + b3);
  81. }
  82. l = (byte) (b2 & 0x0f);
  83. k = (byte) (b1 & 0x03);
  84. byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
  85. byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
  86. byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
  87. if (fDebug) {
  88. System.out.println("val2 = " + val2);
  89. System.out.println("k4 = " + (k << 4));
  90. System.out.println("vak = " + (val2 | (k << 4)));
  91. }
  92. encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
  93. encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
  94. encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
  95. encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
  96. }
  97. // form integral number of 6-bit groups
  98. if (fewerThan24bits == EIGHTBIT) {
  99. b1 = binaryData[dataIndex];
  100. k = (byte) (b1 & 0x03);
  101. if (fDebug) {
  102. System.out.println("b1=" + b1);
  103. System.out.println("b1<<2 = " + (b1 >> 2));
  104. }
  105. byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
  106. encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
  107. encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
  108. encodedData[encodedIndex++] = PAD;
  109. encodedData[encodedIndex++] = PAD;
  110. } else if (fewerThan24bits == SIXTEENBIT) {
  111. b1 = binaryData[dataIndex];
  112. b2 = binaryData[dataIndex + 1];
  113. l = (byte) (b2 & 0x0f);
  114. k = (byte) (b1 & 0x03);
  115. byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
  116. byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
  117. encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
  118. encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
  119. encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
  120. encodedData[encodedIndex++] = PAD;
  121. }
  122. return new String(encodedData);
  123. }
  124. /**
  125. * Decodes Base64 data into octects
  126. *
  127. * @param encoded string containing Base64 data
  128. * @return Array containind decoded data.
  129. */
  130. public static byte[] decode(String encoded) {
  131. if (encoded == null) {
  132. return null;
  133. }
  134. char[] base64Data = encoded.toCharArray();
  135. // remove white spaces
  136. int len = removeWhiteSpace(base64Data);
  137. if (len % FOURBYTE != 0) {
  138. return null;//should be divisible by four
  139. }
  140. int numberQuadruple = (len / FOURBYTE);
  141. if (numberQuadruple == 0) {
  142. return new byte[0];
  143. }
  144. byte decodedData[] = null;
  145. byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
  146. char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
  147. int i = 0;
  148. int encodedIndex = 0;
  149. int dataIndex = 0;
  150. decodedData = new byte[(numberQuadruple) * 3];
  151. for (; i < numberQuadruple - 1; i++) {
  152. if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))
  153. || !isData((d3 = base64Data[dataIndex++]))
  154. || !isData((d4 = base64Data[dataIndex++]))) {
  155. return null;
  156. }//if found "no data" just return null
  157. b1 = base64Alphabet[d1];
  158. b2 = base64Alphabet[d2];
  159. b3 = base64Alphabet[d3];
  160. b4 = base64Alphabet[d4];
  161. decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
  162. decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
  163. decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
  164. }
  165. if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) {
  166. return null;//if found "no data" just return null
  167. }
  168. b1 = base64Alphabet[d1];
  169. b2 = base64Alphabet[d2];
  170. d3 = base64Data[dataIndex++];
  171. d4 = base64Data[dataIndex++];
  172. if (!isData((d3)) || !isData((d4))) {//Check if they are PAD characters
  173. if (isPad(d3) && isPad(d4)) {
  174. if ((b2 & 0xf) != 0)//last 4 bits should be zero
  175. {
  176. return null;
  177. }
  178. byte[] tmp = new byte[i * 3 + 1];
  179. System.arraycopy(decodedData, 0, tmp, 0, i * 3);
  180. tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
  181. return tmp;
  182. } else if (!isPad(d3) && isPad(d4)) {
  183. b3 = base64Alphabet[d3];
  184. if ((b3 & 0x3) != 0)//last 2 bits should be zero
  185. {
  186. return null;
  187. }
  188. byte[] tmp = new byte[i * 3 + 2];
  189. System.arraycopy(decodedData, 0, tmp, 0, i * 3);
  190. tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
  191. tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
  192. return tmp;
  193. } else {
  194. return null;
  195. }
  196. } else { //No PAD e.g 3cQl
  197. b3 = base64Alphabet[d3];
  198. b4 = base64Alphabet[d4];
  199. decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
  200. decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
  201. decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
  202. }
  203. return decodedData;
  204. }
  205. /**
  206. * remove WhiteSpace from MIME containing encoded Base64 data.
  207. *
  208. * @param data the byte array of base64 data (with WS)
  209. * @return the new length
  210. */
  211. private static int removeWhiteSpace(char[] data) {
  212. if (data == null) {
  213. return 0;
  214. }
  215. // count characters that's not whitespace
  216. int newSize = 0;
  217. int len = data.length;
  218. for (int i = 0; i < len; i++) {
  219. if (!isWhiteSpace(data[i])) {
  220. data[newSize++] = data[i];
  221. }
  222. }
  223. return newSize;
  224. }
  225. }

最后是一个MainTest:

  1. package com.ihep;
  2. public class MainTest {
  3. public static void main(String[] args) throws Exception {
  4. String filepath="G:/tmp/";
  5. //RSAEncrypt.genKeyPair(filepath);
  6. System.out.println("--------------公钥加密私钥解密过程-------------------");
  7. String plainText="ihep_公钥加密私钥解密";
  8. //公钥加密过程
  9. byte[] cipherData=RSAEncrypt.encrypt(RSAEncrypt.loadPublicKeyByStr(RSAEncrypt.loadPublicKeyByFile(filepath)),plainText.getBytes());
  10. String cipher=Base64.encode(cipherData);
  11. //私钥解密过程
  12. byte[] res=RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile(filepath)), Base64.decode(cipher));
  13. String restr=new String(res);
  14. System.out.println("原文:"+plainText);
  15. System.out.println("加密:"+cipher);
  16. System.out.println("解密:"+restr);
  17. System.out.println();
  18. System.out.println("--------------私钥加密公钥解密过程-------------------");
  19. plainText="ihep_私钥加密公钥解密";
  20. //私钥加密过程
  21. cipherData=RSAEncrypt.encrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile(filepath)),plainText.getBytes());
  22. cipher=Base64.encode(cipherData);
  23. //公钥解密过程
  24. res=RSAEncrypt.decrypt(RSAEncrypt.loadPublicKeyByStr(RSAEncrypt.loadPublicKeyByFile(filepath)), Base64.decode(cipher));
  25. restr=new String(res);
  26. System.out.println("原文:"+plainText);
  27. System.out.println("加密:"+cipher);
  28. System.out.println("解密:"+restr);
  29. System.out.println();
  30. System.out.println("---------------私钥签名过程------------------");
  31. String content="ihep_这是用于签名的原始数据";
  32. String signstr=RSASignature.sign(content,RSAEncrypt.loadPrivateKeyByFile(filepath));
  33. System.out.println("签名原串:"+content);
  34. System.out.println("签名串:"+signstr);
  35. System.out.println();
  36. System.out.println("---------------公钥校验签名------------------");
  37. System.out.println("签名原串:"+content);
  38. System.out.println("签名串:"+signstr);
  39. System.out.println("验签结果:"+RSASignature.doCheck(content, signstr, RSAEncrypt.loadPublicKeyByFile(filepath)));
  40. System.out.println();
  41. }
  42. }

看看运行截图:


原文地址:https://blog.csdn.net/wangqiuyun/article/details/42143957

RSA加签验签流程:
本地发送请求时(本地已对请求根据私钥进行加签)      接收方平台根据公钥进行验签          判断是否合法
接收来自平台的响应时(平台已根据私钥进行加签)      需要根据本地公钥对响应进行验签    判断是否合法
生成公私钥方法:
在Linuxx下输入openssl 进入openssl 获取公私钥
生成私钥: openssl>genrsa -out rsa_private_key.pem 1024 默认输出pkcs1
生成公钥: openssl>rsa -in rsa_oo_private_key.pem -pubout -out rsa_public_key.pem
私钥需要做pkcs1转pkcs8
---------------------------------------------------------------------
-  PKCS8格式私钥转换为PKCS1(传统私钥格式)                    -
-  openssl pkcs8 -in pkcs8.pem -nocrypt -out pri_key.pem   -
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
-  PKCS1格式私钥转换为PKCS8(传统私钥格式)                                                  -
-  pkcs8 -topk8 -inform PEM -in rsa_key.pem -outform PEM -nocrypt   -
-----------------------------------------------------------------------------------------------------------
生成私钥:
  1. Last login: Fri Aug 4 09:30:12 2017 from 192.168.88.211
  2. [koolapp@aop-70-104 ~]$ openssl
  3. OpenSSL> genrsa -out rsa_oo_private_key.pem 1024
  4. Generating RSA private key, 1024 bit long modulus
  5. ...............................++++++
  6. .......................++++++
  7. e is 65537 (0x10001)
  8. ----------Java开发者需将私钥转换成PKCS8格式再做签名使用,转换方法如下:--------
  9. OpenSSL> pkcs8 -topk8 -inform PEM -in rsa_oo_private_key.pem -outform PEM -nocrypt
  10. --pkcs1转pkcs8
  11. -----BEGIN PRIVATE KEY-----
  12. MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALzHKDGu18RHHJUT
  13. 2+ufbzoq+8L41HYRzosZQ+EoCucMmosUaxX6DWB/uFPKOMsWbgrFk9qkB5sAXnR/
  14. Xwy+zQ9p6WisBY8I0NqihnBcA0MqksJcBYMXuWrlsZait4I7v5rOC1hDpz6RVVWl
  15. R2Ft2Mb/k5ckzWm1UDoBIbjF28pjAgMBAAECgYBewNwk6+yzQTpQfZJSV0ld+fs6
  16. ZulFhjSUzw6qMg4e4M2lZ49EjakvOYxMymDtVwnO8FMBWHnUzD+c293aqN6Fs/cU
  17. MK7rFDdR0GQcclezHfkL/j0xvj+y8DgYd2JiAqh/qeuwbTs4Z0o6dMlqazJ7l16R
  18. s3MnYzU8ABdK6rv9wQJBAOn4brXDH2jcHR4/PWYH1/uNU0FWHwfT9jg9KLTU8k5H
  19. m6c2K5l1eHhir9KmyZhncrPYCynC1iwZzK7ik3GZhwMCQQDOjWpvJEgE+7SLwe2D
  20. +j1vEY8kU3NR3xyZAqVz1fWkd2kW4kr0TPPchVbJBGJpOOa0wwRtf04Lb/nONZDR
  21. jiEhAkAaPlJ0stE4GtBtTxyc8C5KufxnrLhIUX8hqcKCHgybuS59X/cd/G4p2q/s
  22. Cec84AWepJID+iW5xp8N0r5FFLpvAkEAmEB9V/dybtnqt6n3HfVzG0/iJ3Cr7Il9
  23. VvwwYTYxn0211PxxK6sdhktzMTFeKRmcVVn7BYt1R9D+XhX17cHKgQJBANjpDrt1
  24. T+qYZPgGbiEonb0bmjunnMY9Dn5GOh4YDHuv5ObnZZCkNTRJQUCJPjgsF/bkVhPg
  25. dqL+gUqh3ZFVIg4=
  26. -----END PRIVATE KEY-----


生成公钥:
  1. OpenSSL> rsa -in rsa_oo_private_key.pem -pubout -out rsa_public_key.pem
  2. writing RSA key
  3. OpenSSL> quit openssl

退出openssl 输入ls检查是否生成对应的公私钥文件
  1. [aofdapp@root-01 ~]$ ls
  2. 0219.zip backup key.pem notify notify.2 ops rsa_oo_private_key.pem rsa_public_key.pem
  3. genrsa pub_key.pem rsa_private_key.pem token
  4. [aofdapp@root-01 ~]$ vi rsa_public_key.pem
  5. -----BEGIN PUBLIC KEY-----
  6. MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8xygxrtfERxyVE9vrn286KvvC
  7. +NR2Ec6LGUPhKArnDJqLFGsV+g1gf7hTyjjLFm4KxZPapAebAF50f18Mvs0Paelo
  8. rAWPCNDaooZwXANDKpLCXAWDF7lq5bGWoreCO7+azgtYQ6c+kVVVpUdhbdjG/5OX
  9. JM1ptVA6ASG4xdvKYwIDAQAB
  10. -----END PUBLIC KEY-----



公钥、私钥     
  1. publicstatic String privatestr = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANlx8rhWlKYH54BaTuL8jRuXtssu7zr04O6KvZDTzIycvArF3ohMUcgFIQ4a+JlvN5S1sokmxLTKPr4xrS6xRnaUvIW1qXh5SXvwpBEHPpCoHXqP5zNMftxA2MH4ktPfKBtWpoKLP2DsJ4EpGRr34wP3CrchYbjlYyGdY5lvMcbHAgMBAAECgYAvzDJ0fuOyE2658iABGU7TT+gohaqkpQuEpA7DdSszhYh4PcKK52vasfXwKdGXuLDZCY+zQkhfDU35dOYCq4k3Q84cjiLVe5sFlJNucBgqlEcxrLsUkTuXzNntOWjTpWjAnfUXB7GkvT7ekpnCwqWb8qlUGHzsGioTkTOy0cfIUQJBAPuQmI0EpORqP+v/Vd6SWlxq6Be20hsT5erVpz2Ke1KczbQwRi2ogBpYRMaAmT4kWfsl2hU/hbmESG/yymWS+BMCQQDdR1uCJXSJqu7Urlg4zCa4kBk0rwYYttLJj1jL6d5kKawf9iEgoAElVlRZWWXRnyD4Nesf8n5kTlgtawz+jnT9AkEAi1aP6KwF2S6wsTsAiQNvYXkljN0Ki0z+MJCezYuCu0N2/LMwa+HE8tKpZXmdZ7oizOUuYk6I9zS6GqfUS2aYWQJBAJMjzxK0y1B77IJaSGnEPv89OrWQqNIoR/QlsNsvcWVTXJSIOzERlJF6XW5ohs8kLG1AlU/SFP+oJPRWmfZvThUCQDbM7X6PF+DHa9x2YPEWYYiiThbTGTO1mOxBt2V6GuFqnGHFIa3OeZZpv7SW+aDzTGEmrtByqxRkSd3WpeJzu0I=";
  2. public static String publicstr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCjyiajomfYD80A7tN8vdeXllTiGrSdocq1nvgceicanNb8QaoNGdAPE6AMuSqnMWs40tj/XoXQmPxNrdUmclwwLJza5Aq5PNqDiFC5QLmIFtATN/n3ymqIYnw78ME8Dv5yjYJs1xk0EL6+1wlFFrylApBWKUGE2c2m2seBY+in5wIDAQAB";

加签:   

  1. public String signWhole(String keycode, String param) {
  2. // 使用私钥加签
  3. byte[] signature = null;
  4. try {
  5. //获取privatekey
  6. byte[] keyByte = Base64.decode(keycode);
  7. KeyFactory keyfactory = KeyFactory.getInstance("RSA");
  8. PKCS8EncodedKeySpec encoderule = new PKCS8EncodedKeySpec(keyByte);
  9. PrivateKey privatekey = keyfactory.generatePrivate(encoderule);
  10. //用私钥给入参加签
  11. Signature sign = Signature.getInstance("SHA1WithRSA");
  12. sign.initSign(privatekey);
  13. sign.update(param.getBytes());
  14. signature = sign.sign();
  15. } catch (NoSuchAlgorithmException e) {
  16. e.printStackTrace();
  17. } catch (Base64DecodingException e) {
  18. // TODO Auto-generated catch block
  19. e.printStackTrace();
  20. } catch (InvalidKeySpecException e) {
  21. // TODO Auto-generated catch block
  22. e.printStackTrace();
  23. } catch (SignatureException e) {
  24. // TODO Auto-generated catch block
  25. e.printStackTrace();
  26. } catch (InvalidKeyException e) {
  27. // TODO Auto-generated catch block
  28. e.printStackTrace();
  29. }
  30. //将加签后的入参转成16进制
  31. String terminal = Hex.encodeHexStr(signature);
  32. return terminal;
  33. }

验签:
  1. public boolean verifyWhole(String param,String signature,String keycode){
  2. try {
  3. //获取公钥
  4. KeyFactory keyFactory=KeyFactory.getInstance("RSA");
  5. byte[] keyByte=Base64.decode(keycode);
  6. X509EncodedKeySpec encodeRule=new X509EncodedKeySpec(keyByte);
  7. PublicKey publicKey= keyFactory.generatePublic(encodeRule);
  8. //用获取到的公钥对 入参中未加签参数param 与 入参中的加签之后的参数signature 进行验签
  9. Signature sign=Signature.getInstance("SHA1WithRSA");
  10. sign.initVerify(publicKey);
  11. sign.update(param.getBytes());
  12. //将16进制码转成字符数组
  13. byte[] hexByte=Hex.hexStringToBytes(signature);
  14. //验证签名
  15. return sign.verify(hexByte);
  16. } catch (NoSuchAlgorithmException e) {
  17. // TODO Auto-generated catch block
  18. e.printStackTrace();
  19. } catch (Base64DecodingException e) {
  20. // TODO Auto-generated catch block
  21. e.printStackTrace();
  22. } catch (InvalidKeySpecException e) {
  23. // TODO Auto-generated catch block
  24. e.printStackTrace();
  25. } catch (SignatureException e) {
  26. // TODO Auto-generated catch block
  27. e.printStackTrace();
  28. } catch (InvalidKeyException e) {
  29. // TODO Auto-generated catch block
  30. e.printStackTrace();
  31. }
  32. return false;
  33. }
原文地址:https://blog.csdn.net/qq_23974323/article/details/77678491
正文到此结束
Loading...