PKCS7Padding.java 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package com.izouma.dingtalk.utils.aes;
  2. import java.nio.charset.Charset;
  3. import java.util.Arrays;
  4. /*
  5. * PKCS7算法的加密填充
  6. */
  7. public class PKCS7Padding {
  8. private final static Charset CHARSET = Charset.forName("utf-8");
  9. private final static int BLOCK_SIZE = 32;
  10. /**
  11. * 填充mode字节
  12. * @param count
  13. * @return
  14. */
  15. public static byte[] getPaddingBytes(int count) {
  16. int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);
  17. if (amountToPad == 0) {
  18. amountToPad = BLOCK_SIZE;
  19. }
  20. char padChr = chr(amountToPad);
  21. String tmp = new String();
  22. for (int index = 0; index < amountToPad; index++) {
  23. tmp += padChr;
  24. }
  25. return tmp.getBytes(CHARSET);
  26. }
  27. /**
  28. * 移除mode填充字节
  29. * @param decrypted
  30. * @return
  31. */
  32. public static byte[] removePaddingBytes(byte[] decrypted) {
  33. int pad = (int) decrypted[decrypted.length - 1];
  34. if (pad < 1 || pad > BLOCK_SIZE) {
  35. pad = 0;
  36. }
  37. return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
  38. }
  39. private static char chr(int a) {
  40. byte target = (byte) (a & 0xFF);
  41. return (char) target;
  42. }
  43. }