package com.das.common.utils;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.logging.log4j.util.Strings;

import javax.crypto.Cipher;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;
import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

/**
 * @author Administrator
 */
public class TokenUtils {
    private static final String TOKEN_NAME = "token";

    public static final String getToken(HttpServletRequest request) {
        String token = request.getHeader(TOKEN_NAME);
        if (StrUtil.isNotBlank(token)) {
            return token;
        }
        token = request.getParameter(TOKEN_NAME);
        if (StrUtil.isNotBlank(token)) {
            return token;
        }
        return null;
    }

    public static final String decodePassword(String encPassword) {
        try{
            String privateKeyText = ResourceUtil.readStr("classpath:rsakey/usp_private_pkcs8.pem", Charset.defaultCharset());
            byte[] keyBytes = Base64.getDecoder().decode(privateKeyText);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] buffer = Base64.getMimeDecoder().decode(encPassword);
            byte[] rawBytes = cipher.doFinal(buffer);
            String rawText = new String(rawBytes, "UTF-8");
            return rawText;
        }
        catch (Exception ex){
            return Strings.EMPTY;
        }
    }
}
