package com.xxxxx.loan.domain.encryption;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.util.Date;
import java.util.Iterator;

import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.bcpg.HashAlgorithmTags;
import org.bouncycastle.openpgp.PGPCompressedData;
import org.bouncycastle.openpgp.PGPCompressedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedData;
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedDataList;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPLiteralDataGenerator;
import org.bouncycastle.openpgp.PGPObjectFactory;
import org.bouncycastle.openpgp.PGPOnePassSignature;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyEncryptedData;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPSignatureGenerator;
import org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator;
import org.bouncycastle.openpgp.PGPUtil;
import org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator;
import org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilder;
import org.bouncycastle.openpgp.operator.bc.BcPGPDataEncryptorBuilder;
import org.bouncycastle.openpgp.operator.bc.BcPublicKeyDataDecryptorFactory;
import org.bouncycastle.openpgp.operator.bc.BcPublicKeyKeyEncryptionMethodGenerator;
import org.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator;
import org.bouncycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder;
import org.bouncycastle.util.io.Streams;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import lombok.extern.log4j.Log4j2;

@Log4j2
@Component
public class Main {
	
	@Value("${fs.pgp.private.key}")
	private String privateKeyPath;

	private static final int DEFAULT_BUFFER_SIZE = 16 * 1024;
	
	public String decryptRequest(String data, String publiKey) throws Exception {
		InputStream inputStream = PGPUtil.getDecoderStream(new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)));
		InputStream privateKey = new BufferedInputStream(new FileInputStream(privateKeyPath));
		InputStream publicKey = new BufferedInputStream(new FileInputStream(publiKey));

		byte[] decryptedBytes = decryptAndVerify(inputStream, privateKey, publicKey);
		return new String(decryptedBytes);
	}
	
	public static final byte[] decryptAndVerify(InputStream is, InputStream verifyKey, InputStream decryptKey)
			throws Exception {
		PGPObjectFactory pgpF = new PGPObjectFactory(is, new BcKeyFingerprintCalculator());
		PGPEncryptedDataList enc = (PGPEncryptedDataList) pgpF.nextObject();

		Iterator<?> it = enc.getEncryptedDataObjects();

		PGPPrivateKey sKey = null;
		PGPPublicKeyEncryptedData pbe = null;

		while (sKey == null && it.hasNext()) {
			pbe = (PGPPublicKeyEncryptedData) it.next();
			sKey = findPrivateKey(verifyKey, pbe.getKeyID());
		}

		InputStream clear = pbe.getDataStream(new BcPublicKeyDataDecryptorFactory(sKey));
		PGPObjectFactory plainFact = new PGPObjectFactory(clear, new BcKeyFingerprintCalculator());
		PGPCompressedData compressedData = null;
		Object message = plainFact.nextObject();
		ByteArrayOutputStream actualOutput = new ByteArrayOutputStream();

		while (message != null) {
			if (message instanceof PGPCompressedData) {
				compressedData = (PGPCompressedData) message;
				plainFact = new PGPObjectFactory(compressedData.getDataStream(), new BcKeyFingerprintCalculator());
				message = plainFact.nextObject();
			} else if (message instanceof PGPLiteralData) {
				Streams.pipeAll(((PGPLiteralData) message).getInputStream(), actualOutput);
			}
			message = plainFact.nextObject();
		}
		actualOutput.close();
		byte[] outputBytes = actualOutput.toByteArray();
		return outputBytes;
	}
	
	public static PGPPrivateKey findPrivateKey(InputStream keyIn, long keyID)
			throws IOException, PGPException, NoSuchProviderException {
		char[] pass = "".toCharArray();
		PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn),
				new JcaKeyFingerprintCalculator());
		PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);
		if (pgpSecKey == null) {
			return null;
		}

		return pgpSecKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(pass));
	}
	
	public String encrypt(String data, String publicKey) throws Exception {
		InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
		ByteArrayOutputStream out = encryptAndSign(dataStream, publicKey, privateKeyPath);
		return new String(out.toByteArray());
	}
	
	public static final ByteArrayOutputStream encryptAndSign(InputStream is, String publicKeyFile, String privateKeyFile)
			throws Exception {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		char[] pass = "".toCharArray();

		InputStream encryptKeyInput = new FileInputStream(publicKeyFile);
		PGPSecretKey pgpSec = null;
		try {
			pgpSec = readSecretKey(new FileInputStream(privateKeyFile));

			PGPPrivateKey signingKey = pgpSec
					.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(pass));
			String userid = (String) pgpSec.getPublicKey().getUserIDs().next();
			BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.AES_256);
			dataEncryptor.setSecureRandom(new SecureRandom());

			PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor);
			PGPPublicKey pgpPublicKey = readPublicKey(encryptKeyInput);
			encryptedDataGenerator.addMethod((new BcPublicKeyKeyEncryptionMethodGenerator(pgpPublicKey)));
			OutputStream finalOut = new BufferedOutputStream(new ArmoredOutputStream(out), DEFAULT_BUFFER_SIZE);
			OutputStream encOut = encryptedDataGenerator.open(finalOut, new byte[1 << 16]);

			PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
			OutputStream compressedOut = new BufferedOutputStream(compressedDataGenerator.open(encOut));

			PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
					new BcPGPContentSignerBuilder(pgpSec.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA256));

			signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, signingKey);
			PGPSignatureSubpacketGenerator subpacketGenerator = new PGPSignatureSubpacketGenerator();
			subpacketGenerator.setSignerUserID(false, userid);
			signatureGenerator.setHashedSubpackets(subpacketGenerator.generate());
			PGPOnePassSignature onePassSignature = signatureGenerator.generateOnePassVersion(false);
			onePassSignature.encode(compressedOut);
			PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator(true);
			OutputStream literalOut = literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY, "", new Date(),
					new byte[1 << 16]);
			byte[] buffer = new byte[1 << 16];
			int bytesRead = 0;
			while ((bytesRead = is.read(buffer)) != -1) {
				literalOut.write(buffer, 0, bytesRead);
				signatureGenerator.update(buffer, 0, bytesRead);
				literalOut.flush();
			}
			literalOut.close();
			literalDataGenerator.close();
			signatureGenerator.generate().encode(compressedOut);
			compressedOut.close();
			compressedDataGenerator.close();
			encOut.close();
			encryptedDataGenerator.close();
			finalOut.close();
			is.close();
		} catch (Exception e) {
			log.error("Encrypting payload error {}", e);
		}
		return out;
	}
	
	public static PGPSecretKey readSecretKey(InputStream input) throws IOException, PGPException {
		PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(input),
				new JcaKeyFingerprintCalculator());

		Iterator<?> keyRingIter = pgpSec.getKeyRings();
		while (keyRingIter.hasNext()) {
			PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRingIter.next();
			Iterator<?> keyIter = keyRing.getSecretKeys();
			while (keyIter.hasNext()) {
				PGPSecretKey key = (PGPSecretKey) keyIter.next();
				if (key.isSigningKey()) {
					return key;
				}
			}
		}
		throw new IllegalArgumentException("Can't find signing key in key ring.");
	}
	
	private static PGPPublicKey readPublicKey(InputStream input) throws IOException, PGPException {
		PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input),
				new JcaKeyFingerprintCalculator());
		Iterator<?> keyRingIter = pgpPub.getKeyRings();
		while (keyRingIter.hasNext()) {
			PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next();
			Iterator<?> keyIter = keyRing.getPublicKeys();
			while (keyIter.hasNext()) {
				PGPPublicKey key = (PGPPublicKey) keyIter.next();
				if (key.isEncryptionKey()) {
					return key;
				}
			}
		}
		throw new IllegalArgumentException("Can't find encryption key in key ring.");
	}
	
	public static void main(String[] args) throws Exception {
		PgpEncryptDecrypt pgp = new PgpEncryptDecrypt();
//		String enc = pgp.encrypt("{\n"
//				+ "\"ovdId\": \"XXXXXXXX\",\n"
//				+ "\"ovdType\": \"PAN\",\n"
//				+ "\"customerId\": \"999999999\"\n"
//				+ "}", "/Users/C999999/Desktop/app/online/loan/file/idfc.pgp.key");
//		
//		System.out.println(enc);
		System.out.println(pgp.decryptRequest("-----BEGIN PGP MESSAGE-----\n"
				+ "Version: BCPG v1.61\n"
				+ "\n"
				+ "hQGMA/VxZ/SICerdAQv+MQ27gCauMutFQ6LStJqbanOfisoNqEzIU6mpFWPEwOnK\n"
				+ "Yzc6n7yy3NydJBfTVqV5TdVVPY5mlkCx43bMsQXyNuof37ZWzEfJ5ISqktiAWJ1I\n"
				+ "igeCh4fW8KYgHB2wiKmeqLVk2hSH3qVK3AQg9oE6V/jCTcF4wyb8aOBRP7CiiHMK\n"
				+ "thBGKUe5n5O/WrUS1XA6QXMcO96XKmkV48swew2ksPvCQ4ed1V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vNb9D6g5IFkwlq1IDsaq5maEiHhQommZ\n"
				+ "wWGUkv2VwdOZdSbKVGC1EoWe2Q04SzGlXVczM9iYempHrgy01JctkkN2jSrYbc8j\n"
				+ "t6XdJ7WF/91/ePxDQ79qZwUXZ/tuho6Oe1LPHnw65clwkDJOfn5RNOPC3g3B2Nj4\n"
				+ "0TGnkwNYGkV+3u6G3yI/jImitu5s/0k9Y9mF7zZLZhgHXpHZiYzbirNoz6hY4+CL\n"
				+ "P2LJrlEj6bplbFc2anyL1KqmSvQaLd6MOmZLEYv6D80gEhOGAqDkPIL9govpiKRD\n"
				+ "+id0oTFVOes7K1wTTNzGcc5qPjc3t10mw8xjfjkXbjY4HVBGDqtWIC1MImhjwBqe\n"
				+ "CRXIF3d7NHD3yJjlZqBdgUs0RW3oXEvlGpGhOPF2thBZpZG8o0M24m6xqmvo5fQ2\n"
				+ "PY+t6PiZ+PnBKCmZy6/iszzD3XmiKmwIAVVVKwdm4uJ1saAeSTyZDyqgMBZ0ZbjU\n"
				+ "jVTOPwRHfXbmljiuSyNpNGKX1V5VoQ1smKU9CQw9Rby8CxBOMiJwIW3RawVWIuWp\n"
				+ "8S7jjFW0i68UquJJ7FBXe3MVH7BWHNSWf70OFtgphfDCZ/fNgT9hrGG9q9p2s/c/\n"
				+ "90uvGzb6Jvdu4X8swypv0eAQMcrQPj6aaMFBdaOE8Z/2Aq2fm48CpS2hnb7dbrEZ\n"
				+ "2yRA8yQsN2JHf772DEhp5K/EKZ1lLyCNEC7NXc75YE72tKKUBxjQsuWmwdUFF2Y1\n"
				+ "MIbAmHCMO85qBVEYjfqjsyjgmYAdQjzz2glgXwvVwAT4KPq7Co7+msU=\n"
				+ "=IDVG\n"
				+ "-----END PGP MESSAGE-----\n"
				+ "", "publickeypath"));
	}
	
} 

Java online compiler

Write, Run & Share Java code online using OneCompiler's Java online compiler for free. It's one of the robust, feature-rich online compilers for Java language, running the Java LTS version 17. Getting started with the OneCompiler's Java editor is easy and fast. The editor shows sample boilerplate code when you choose language as Java and start coding.

Taking inputs (stdin)

OneCompiler's Java online editor supports stdin and users can give inputs to the programs using the STDIN textbox under the I/O tab. Using Scanner class in Java program, you can read the inputs. Following is a sample program that shows reading STDIN ( A string in this case ).

import java.util.Scanner;
class Input {
    public static void main(String[] args) {
    	Scanner input = new Scanner(System.in);
    	System.out.println("Enter your name: ");
    	String inp = input.next();
    	System.out.println("Hello, " + inp);
    }
}

Adding dependencies

OneCompiler supports Gradle for dependency management. Users can add dependencies in the build.gradle file and use them in their programs. When you add the dependencies for the first time, the first run might be a little slow as we download the dependencies, but the subsequent runs will be faster. Following sample Gradle configuration shows how to add dependencies

apply plugin:'application'
mainClassName = 'HelloWorld'

run { standardInput = System.in }
sourceSets { main { java { srcDir './' } } }

repositories {
    jcenter()
}

dependencies {
    // add dependencies here as below
    implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
}

About Java

Java is a very popular general-purpose programming language, it is class-based and object-oriented. Java was developed by James Gosling at Sun Microsystems ( later acquired by Oracle) the initial release of Java was in 1995. Java 17 is the latest long-term supported version (LTS). As of today, Java is the world's number one server programming language with a 12 million developer community, 5 million students studying worldwide and it's #1 choice for the cloud development.

Syntax help

Variables

short x = 999; 			// -32768 to 32767
int   x = 99999; 		// -2147483648 to 2147483647
long  x = 99999999999L; // -9223372036854775808 to 9223372036854775807

float x = 1.2;
double x = 99.99d;

byte x = 99; // -128 to 127
char x = 'A';
boolean x = true;

Loops

1. If Else:

When ever you want to perform a set of operations based on a condition If-Else is used.

if(conditional-expression) {
  // code
} else {
  // code
}

Example:

int i = 10;
if(i % 2 == 0) {
  System.out.println("i is even number");
} else {
  System.out.println("i is odd number");
}

2. Switch:

Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.

switch(<conditional-expression>) {    
case value1:    
 // code    
 break;  // optional  
case value2:    
 // code    
 break;  // optional  
...    
    
default:     
 //code to be executed when all the above cases are not matched;    
} 

3. For:

For loop is used to iterate a set of statements based on a condition. Usually for loop is preferred when number of iterations is known in advance.

for(Initialization; Condition; Increment/decrement){  
    //code  
} 

4. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while(<condition>){  
 // code 
}  

5. Do-While:

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {
  // code 
} while (<condition>); 

Classes and Objects

Class is the blueprint of an object, which is also referred as user-defined data type with variables and functions. Object is a basic unit in OOP, and is an instance of the class.

How to create a Class:

class keyword is required to create a class.

Example:

class Mobile {
    public:    // access specifier which specifies that accessibility of class members 
    string name; // string variable (attribute)
    int price; // int variable (attribute)
};

How to create a Object:

Mobile m1 = new Mobile();

How to define methods in a class:

public class Greeting {
    static void hello() {
        System.out.println("Hello.. Happy learning!");
    }

    public static void main(String[] args) {
        hello();
    }
}

Collections

Collection is a group of objects which can be represented as a single unit. Collections are introduced to bring a unified common interface to all the objects.

Collection Framework was introduced since JDK 1.2 which is used to represent and manage Collections and it contains:

  1. Interfaces
  2. Classes
  3. Algorithms

This framework also defines map interfaces and several classes in addition to Collections.

Advantages:

  • High performance
  • Reduces developer's effort
  • Unified architecture which has common methods for all objects.
CollectionDescription
SetSet is a collection of elements which can not contain duplicate values. Set is implemented in HashSets, LinkedHashSets, TreeSet etc
ListList is a ordered collection of elements which can have duplicates. Lists are classified into ArrayList, LinkedList, Vectors
QueueFIFO approach, while instantiating Queue interface you can either choose LinkedList or PriorityQueue.
DequeDeque(Double Ended Queue) is used to add or remove elements from both the ends of the Queue(both head and tail)
MapMap contains key-values pairs which don't have any duplicates. Map is implemented in HashMap, TreeMap etc.