PKCS7Encoder.java 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * 对企业微信发送给企业后台的消息加解密示例代码.
  3. *
  4. * @copyright Copyright (c) 1998-2014 Tencent Inc.
  5. */
  6. // ------------------------------------------------------------------------
  7. package com.caimei365.wechat.utils;
  8. import java.nio.charset.Charset;
  9. import java.util.Arrays;
  10. /**
  11. * 提供基于PKCS7算法的加解密接口.
  12. */
  13. public class PKCS7Encoder {
  14. static Charset CHARSET = Charset.forName("utf-8");
  15. static int BLOCK_SIZE = 32;
  16. /**
  17. * 获得对明文进行补位填充的字节.
  18. *
  19. * @param count 需要进行填充补位操作的明文字节个数
  20. * @return 补齐用的字节数组
  21. */
  22. public static byte[] encode(int count) {
  23. // 计算需要填充的位数
  24. int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);
  25. if (amountToPad == 0) {
  26. amountToPad = BLOCK_SIZE;
  27. }
  28. // 获得补位所用的字符
  29. char padChr = chr(amountToPad);
  30. String tmp = new String();
  31. for (int index = 0; index < amountToPad; index++) {
  32. tmp += padChr;
  33. }
  34. return tmp.getBytes(CHARSET);
  35. }
  36. /**
  37. * 删除解密后明文的补位字符
  38. *
  39. * @param decrypted 解密后的明文
  40. * @return 删除补位字符后的明文
  41. */
  42. public static byte[] decode(byte[] decrypted) {
  43. int pad = (int) decrypted[decrypted.length - 1];
  44. if (pad < 1 || pad > 32) {
  45. pad = 0;
  46. }
  47. return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
  48. }
  49. /**
  50. * 将数字转化成ASCII码对应的字符,用于对明文进行补码
  51. *
  52. * @param a 需要转化的数字
  53. * @return 转化得到的字符
  54. */
  55. public static char chr(int a) {
  56. byte target = (byte) (a & 0xFF);
  57. return (char) target;
  58. }
  59. }