package com.muchinfo.mtp3century.utils;


import com.muchinfo.mtp3common.utils.EncryptionUtils;
import org.apache.shiro.codec.Base64;

import javax.crypto.Cipher;
import javax.servlet.http.HttpServletRequest;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;


public class CenturyDecryptUtil {

    public static final String KEY_ALGORITHM = "RSA";

    private static final String Private_Key = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAL68qZkKchVojsojVKpjYuEVerAb\n" +
            "2v4XXfkzj8RoIsrO1laiTOXrtKMKOYKCyTlqakNr+E/G6BoAmjQpk9FoMapWrnhwubf52i3xrUdT\n" +
            "2seo8JLky9BFLuCTxx7+3y4djjT8rEuiQ6lcqbMzWtzcE2iHt6UCdEgwIzdby+FdmSF3AgMBAAEC\n" +
            "gYAzyv8ys4dvEMlVUmq3Ke27uR1rnOTGgoneFYZAixaHg8roE4JWHL8cVrZvHhyOHrtkO3leEGEO\n" +
            "ToORDok5H9X8NykuaDAOTjdrGCIky5xkREny5pTDnYsn+LIEd3EiFnmNQVFgcJ7mUvbKAXROoQzZ\n" +
            "O5BqouSsW5brd6FXW1LvwQJBAOLEpyANEZCVl81s8Yx23kVsbpZfD38HZIqCssrlfGp/riRUFE6x\n" +
            "l8KmElryUKISn8H35IhY4QBQ9um7feyRkQkCQQDXUvrlyQoY27pXYzEK3msTj1ECEpy4XLArpfAf\n" +
            "o++ehRCsDsS7yXA600enPC6z8KPTP1igGBOTb2jq8jGosj5/AkB1FpMwom7SV9tk736dR3cnI4DK\n" +
            "VdUbgwav2iJVTz75gmm5SkyeAWbZ04Qgv4NQ3ArvTX8Lw9CRqDyFnRC9CMB5AkEAkF3OYmocHvaT\n" +
            "RSv4IbVmTUL1qVIZSXK7m0gyasRbUAkfWHy+Yrl4SbiGfhXXqkVZUbVTEmOSHHPCAGRJ7zUyuQJA\n" +
            "YQWS/0qacIB46IWd7yA92PymPLM+hGyM2wFe9hnMdQK4zMpDbUxRwjxHQZ8vi57gjJ8HTbcAfibX\n" +
            "t845/ieHqA==";

    /**
     * @param json
     * @return
     */
    public static String decryptForJson(String json, HttpServletRequest request){
        String dataKey = request.getHeader("Data-Key");
        String aesKey = decryptByPrivateKey(Private_Key, dataKey);
        return EncryptionUtils.decryptForAES(json, aesKey);
    }

    public static String decryptByPrivateKey(String privateKeyString, String text) {
        try {
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decode(privateKeyString));
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] result = cipher.doFinal(Base64.decode(text));
            return new String(result);
        } catch (Exception e) {
            return null;
        }
    }

}
