package cn.reghao.bnt.web.admin.service;

import cn.reghao.jutil.jdk.security.RandomString;
import cn.reghao.jutil.jdk.security.RsaCryptor;
import cn.reghao.bnt.web.admin.model.dto.RsaPubkey;
import cn.reghao.bnt.web.util.CacheKeys;
import com.github.benmanes.caffeine.cache.Cache;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * @author reghao
 * @date 2023-02-20 11:09:03
 */
@Service
public class PubkeyService {
    private final Cache<String, Object> caffeineCache;

    public PubkeyService(Cache<String, Object> caffeineCache) {
        this.caffeineCache = caffeineCache;
    }

    public RsaPubkey getPubkey() throws NoSuchAlgorithmException {
        String pubkey = (String) caffeineCache.getIfPresent(CacheKeys.getRsaPubkeyKey());
        if (pubkey == null) {
            Map<String, String> rsaKeyPair = RsaCryptor.genKeyPair();
            String prikey = rsaKeyPair.get("prikey");
            pubkey = rsaKeyPair.get("pubkey");

            caffeineCache.put(CacheKeys.getRsaPubkeyKey(), pubkey);
            caffeineCache.put(CacheKeys.getRsaPrikeyKey(), prikey);
        }

        String r = RandomString.getString(16);
        long timeout = 300;
        caffeineCache.put(CacheKeys.getPubkeyRKey(), r);
        return new RsaPubkey(pubkey, r);
    }

    public String decrypt(String cipherText) throws Exception {
        String prikey = (String) caffeineCache.getIfPresent(CacheKeys.getRsaPrikeyKey());
        if (prikey == null) {
            String msg = "私钥不存在";
            throw new Exception(msg);
        }

        String r = (String) caffeineCache.getIfPresent(CacheKeys.getPubkeyRKey());
        if (r == null) {
            String msg = "当前会话已过期, 请刷新页面后重新登入. 或者检查浏览器是否禁用了 cookie";
            throw new Exception(msg);
        }

        String plainText = RsaCryptor.decrypt(cipherText, prikey);
        return plainText.replace(r, "");
    }
}
