com.fastchar.pay.wx.FastWxPKCS7 Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of fastchar-pay Show documentation
Show all versions of fastchar-pay Show documentation
FastChar-Pay is a FastChar plugin.
The newest version!
package com.fastchar.pay.wx;
import com.fastchar.utils.FastBase64Utils;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* @author 沈建(Janesen)
* @date 2021/2/19 10:32
*/
public class FastWxPKCS7 {
private static final Charset CHARSET = StandardCharsets.UTF_8;
private static final int BLOCK_SIZE = 32;
/**
* 获得对明文进行补位填充的字节.
*
* @param count
* 需要进行填充补位操作的明文字节个数
* @return 补齐用的字节数组
*/
private 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);
}
/**
* 删除解密后明文的补位字符
*
* @param decrypted
* 解密后的明文
* @return 删除补位字符后的明文
*/
private static byte[] decode(byte[] decrypted) {
int pad = decrypted[decrypted.length - 1];
if (pad < 1 || pad > 32) {
pad = 0;
}
return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
}
/**
* 将数字转化成ASCII码对应的字符,用于对明文进行补码
*
* @param a
* 需要转化的数字
* @return 转化得到的字符
*/
private static char chr(int a) {
byte target = (byte) (a & 0xFF);
return (char) target;
}
/**
* 解密数据
*/
public static String decrypt(String encryptedData, String sessionKey, String iv) {
try {
FastWxAES aes = new FastWxAES();
byte[] resultByte = aes.decrypt(FastBase64Utils.decodeToBytes(encryptedData),
FastBase64Utils.decodeToBytes(sessionKey), FastBase64Utils.decodeToBytes(iv));
if (null != resultByte && resultByte.length > 0) {
return new String(decode(resultByte));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}