package com.library.TopUp.mefont;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.FileInputStream;
import java.net.URLDecoder;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class MetfoneRSAUtils {

    final static String pripath = "/com/library/TopUp/mefont/keys/ePayTest.pri";
    final static String pubpath = "/com/library/TopUp/mefont/keys/ePayTest.pub";

    public static String encryptRSA(String plainData) {
        try {
            String path = MetfoneRSAUtils.class.getResource("/").toString();
            path = path.substring(6, path.length() - 1);
            path = URLDecoder.decode(path) + pubpath;

            FileInputStream fis = new FileInputStream(path);
            byte[] byteKeyFromFile = new byte[fis.available()];
            fis.read(byteKeyFromFile);
            fis.close();
            X509EncodedKeySpec keySpec = new
                    X509EncodedKeySpec(byteKeyFromFile);
            KeyFactory factory = KeyFactory.getInstance("RSA");
            PublicKey pubKey = factory.generatePublic(keySpec);
            // Mã hoá dữ liệu
            Cipher c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            c.init(Cipher.ENCRYPT_MODE, pubKey);
            byte encryptedByte[] = c.doFinal(plainData.getBytes());
            String encrypted = Base64.encodeBase64String(encryptedByte);
            return encrypted;
        } catch (Exception ex) {
            System.out.println(ex.getLocalizedMessage());
        }
        return null;
    }

    public static String decryptRSA(String encryptedData) {
        try {
            String path = MetfoneRSAUtils.class.getResource("/").toString();
            path = path.substring(6, path.length() - 1);
            path = URLDecoder.decode(path) + pripath;

            FileInputStream fis = new FileInputStream(path);
            byte[] byteKeyFromFile = new byte[fis.available()];
            fis.read(byteKeyFromFile);
            fis.close();
            PKCS8EncodedKeySpec keySpec = new
                    PKCS8EncodedKeySpec(byteKeyFromFile);
            KeyFactory factory = KeyFactory.getInstance("RSA");
            PrivateKey priKey = factory.generatePrivate(keySpec);
            // Giải mã dữ liệu
            Cipher c2 = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            c2.init(Cipher.DECRYPT_MODE, priKey);
            String decrypted = new
                    String(c2.doFinal(Base64.decodeBase64(encryptedData)));
            return decrypted;
        } catch (Exception ex) {
            System.out.println(ex.getLocalizedMessage());
        }
        return null;
    }

    public static void main(String[] args) {

        String token = "lF4inzg0SYpt7VekJEhCRYi/hLaPtxgGpflBo5ocWv7lZT09tD+zP8cqTICzTqT8R4raZ3USzv" +
                "nyi6tBcE6hNtdoXa8Cq6ub8AZbyoMB0RMWyPbcaKvnbX34kLRnskUECjEKsBRNpYEVP1rNcSVc+" +
                "xmDGC7PtcYV+kIRDp5Dmqhcb/7wOHkqyUemTbvhmgb6wgLXE4pdB6NyJZ7JAbfZ5DiIgyGQ7EK4" +
                "7hdb4bGn1/15+M4C3OlpOcp7PuFzBuDO1HRkoLXeayFhMKoLHBj1s0wWaFHbPQIYxpCBFW6lzdO" +
                "6rVVuhA1YoaoKNZOnYk9fVZ+vQUj5nY2i4yH8u4GJKw==";

        String token2 = "iljUgme83Rj3dCvhFHwFdBB+DXkPpmxTjSFGlsjJJeXQRmQRP62lO9lNYGBkz827TPOjrycRg0BuPLH4I497iuMo7LUMt0mg3C7B3ejRkgcqWoiQxaSjB79mQa8lip/w6Q9S74Wwim/tDw/horrQ/a50+sTe+UYuHh1hjwnr61KQwieNDRFC3rYxeA5WkwpMCVQMHWfTqK3mPjXHqJgoMySUekg0NCbYQYmqWsgetakUuSlaKmrjpK90WfjOsnIeuTWEYHh+tlrI3VVIGF/Pknw6xzLOG+rTi1IZ7RkuHKh8nbiR4uLDkXpvGiiL1Hiq3H2Sz897MZKs1HeqWdrMng==";

//        System.out.println(System.getProperty("user.dir"));


        String str = decryptRSA(token2);

        String encryptText = str + "|" + "298315";

        String retStr = encryptRSA(encryptText);

        System.out.println("解密后的数据：" + str);
        System.out.println("加上PIN加密的数据：" + retStr);


    }
}
