content: /**
   * 对公众平台发送给公众账号的消息加解密示例代码.
   * 
   * @copyright Copyright (c) 1998-2014 Tencent Inc.
   */
  
  // ------------------------------------------------------------------------
  
  package com.soecode.wxtools.util.crypto;
  
  import java.nio.charset.Charset;
  import java.util.Arrays;
  
  public class PKCS7Encoder {
  
  	private static final Charset CHARSET = Charset.forName("utf-8");
  	private static final int BLOCK_SIZE = 32;
  
  	public static byte[] encode(int count) {
  		// 计算需要填充的位数
  		int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);
  		if (amountToPad == 0) {
  			amountToPad = BLOCK_SIZE;
  		}
  		// 获得补位所用的字符
  		char padChr = chr(amountToPad);
  		String tmp = new String();
  		for (int index = 0; index < amountToPad; index++) {
  			tmp += padChr;
  		}
  		return tmp.getBytes(CHARSET);
  	}
  
  	public static byte[] decode(byte[] decrypted) {
  		int pad = (int) decrypted[decrypted.length - 1];
  		if (pad < 1 || pad > 32) {
  			pad = 0;
  		}
  		return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
  	}
  
  	public static char chr(int a) {
  		byte target = (byte) (a & 0xFF);
  		return (char) target;
  	}
  
  }
  