package cn.qinys.platform.base.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;

/**
 * Description:
 *
 * @author tanlie
 * Date: 2024/2/21 17:38
 */
@Component
public class PasswordUtils {
    Logger logger = LoggerFactory.getLogger(PasswordUtils.class);
    private String key = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIeFJ2TK5/SjJXmlUJldiT/c8K6u3mNd692DE42YE8+gYzvY2BRvSATmIbSoJaNzC1wDMY8YJTQo0+k1KJeX7SCsR565BoX36z+F9llTzXjKfzNrUHUrbskGRt8xdh3WmxlaiZrmpZrnLIBkPndylkVQ3x9QHkE4vF5fov9upW4lAgMBAAECgYBZ5j/awiubgrqydrL/+ie5IMTc7I4EVuLHwFMxQ+gofNo3ckLtU2DwNwW3BTBqvD+V21x982OCtW7WLnhuD8+yMc16MC2bsox5UHJVnskHVaikz76KZgsmB85a5CM7sg5aRb8yX2w9JfsoIOIQiPQYYz4MHwmbM4eMToRIfsI+wQJBAPrgq5BwluYtYbJxrKlgMyDoVZ5zhADc/cl56TpsIAk9l90Siqmc/RwYIe7iMRKwihk80Xxmu+1Bv4vokHaH45UCQQCKSYN5eHN/2sGJ5Ck6p44iIzt4pn8mnXnjkiASAeJOr9qO3loU6wGExRATwKQTx5kgjHqzzBfvFDuwWliHMbxRAkEApOZqPp2SwicQMV+AkzA1SysLpAPfv0WC1xx3zbvmbsx6dohKdmRHBmFiZIdupA9AJoiQVYmderydr9OkqRR25QJADZSSmMc/cHrnLsd9VQlHaArVuE+BhSVJ5xNemuYcd2XFrOohJpS9nXBM1+O/OUIMw6mIE0gjwZLXGcaFkyFLQQJAS8SLCIKUFi08cDq0IP0JX2kWKVAHyuvnIY7/YP1o/Ls9Zzqj+VEBWDT5XaRhPV5z8GENu9P6aqqLK9dU99en1w==";

    /**
     * 解密
     *
     * @param rawData 密码的密文
     * @return
     */
    public String decryptRawData(String rawData) {
        String password = "";
        byte[] inputByte;
        try {
            inputByte = Base64.decodeBase64(rawData);
            byte[] decoded = Base64.decodeBase64(key);
            RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            password = new String(cipher.doFinal(inputByte));
        } catch (NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | InvalidKeySpecException | NoSuchAlgorithmException e) {
            e.printStackTrace();
            logger.error("解密数据失败=={}", rawData);
        }
        return password;
    }


    public boolean checkPassword(String password) {
        String regexp = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[.=#?!@$%^&+*-]).{8,}$";
        return !StringUtils.isBlank(password) && password.matches(regexp);
    }

}
