package com.pinelabs.utils;

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

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

public class RSAKeyReader {

    public static PublicKey getRSAPublicKeyInfo() throws GeneralSecurityException, IOException {
        String keyFile = System.getProperty("KEY_FILE");
        String publicKeyInfo = System.getProperty("KEY_INFO");
        if (Boolean.parseBoolean(keyFile)){
            String publicKeyContent = new String(Files.readAllBytes(Paths.get(publicKeyInfo)));
            publicKeyContent= publicKeyContent.replaceAll("\\n", "").replaceAll("\\r", "")
                    .replace("-----BEGIN PUBLIC KEY-----", "")
                    .replace("-----END PUBLIC KEY-----", "");
            return getRSAPublicKey(publicKeyContent);
        }else {
            String publicKeyContent =  publicKeyInfo.replaceAll("\\n", "").replaceAll("\\r", "")
                    .replace("-----BEGIN PUBLIC KEY-----", "")
                    .replace("-----END PUBLIC KEY-----", "");
            return getRSAPublicKey(publicKeyContent);
        }
    }

    private static PublicKey getRSAPublicKey(String publicKeyContent) throws IOException, GeneralSecurityException {
        KeyFactory kf = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyContent));
        return kf.generatePublic(x509EncodedKeySpec);
    }

}
