package org.springblade.common.utils.encryption;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.digest.SM3;

import java.io.File;
import java.io.InputStream;


/**
 * @author weiweiw
 * SM3加解密
 */
public class Sm3Util {

    private static final String SALT = "2cc0c5f9f1749f1632efa9f63e902323";

    public static String encrypt(String data) {
        try {
            // 与前端的处理方式完全一致：字符串拼接 + SM3哈希
            String dataWithSalt = SALT + data;
            SM3 sm3 = SmUtil.sm3();
            return sm3.digestHex(dataWithSalt);
        } catch (Exception e) {
            throw new RuntimeException("SM3 encryption failed", e);
        }
    }

    // 其他方法也需要相应修改
    public static String encrypt(InputStream data) {
        // 对于流数据，需要先读取内容再拼接
        try {
            String content = IoUtil.readUtf8(data);
            String dataWithSalt = SALT + content;
            SM3 sm3 = SmUtil.sm3();
            return sm3.digestHex(dataWithSalt);
        } catch (Exception e) {
            throw new RuntimeException("SM3 encryption failed", e);
        }
    }

    public static String encrypt(File dataFile) {
        try {
            String content = FileUtil.readUtf8String(dataFile);
            String dataWithSalt = SALT + content;
            SM3 sm3 = SmUtil.sm3();
            return sm3.digestHex(dataWithSalt);
        } catch (Exception e) {
            throw new RuntimeException("SM3 encryption failed", e);
        }
    }

    public static void main(String[] args) {
        System.out.println(Sm3Util.encrypt("pageNum=1&pageSize=10"));
    }

}
