FeiShuEventDataDecrypter.java 2.02 KB
package com.pipihelper.project.feishu.utils;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;


/**
 * @Description: TODO
 * @author: charles
 * @date: 2022年03月31日 10:03
 */
public class FeiShuEventDataDecrypter {

    private byte[] keyBs;

    public FeiShuEventDataDecrypter(String key) {
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            // won't happen
        }
        keyBs = digest.digest(key.getBytes(StandardCharsets.UTF_8));
    }
    public String decrypt(String base64) throws Exception {
        byte[] decode = Base64.getDecoder().decode(base64);
        Cipher cipher = Cipher.getInstance("AES/CBC/NOPADDING");
        byte[] iv = new byte[16];
        System.arraycopy(decode, 0, iv, 0, 16);
        byte[] data = new byte[decode.length - 16];
        System.arraycopy(decode, 16, data, 0, data.length);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBs, "AES"), new IvParameterSpec(iv));
        byte[] r = cipher.doFinal(data);
        if (r.length > 0) {
            int p = r.length - 1;
            for (; p >= 0 && r[p] <= 16; p--) {
            }
            if (p != r.length - 1) {
                byte[] rr = new byte[p + 1];
                System.arraycopy(r, 0, rr, 0, p + 1);
                r = rr;
            }
        }
        return new String(r, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) throws Exception {
        FeiShuEventDataDecrypter d = new FeiShuEventDataDecrypter("kudryavka");
        System.out.println(d.decrypt("5QyoWWZ3QI5xbQ6Q/niQRVUS+nxnOLk+EEoWJbwPoi1+tQvl92BzKwfS8vFc/ubRHJ4VmOROpjA8TZieBLBWBmh5IcphCVIh5ciPSgjMY5wKRA26G+LN2VvldyO8hUwm7z9XGCNpM7Cbdi/qWmQEC9AmFxdVlSaR0H8m15TVVLVKOHZt9yFCa8s4hy7Q2kG/")); //hello world
    }
}