Export and Require in Node JS

  • Everything you write in node is a module
  • You can export a function is a module using “module.exports”
  • You can use a exported module using “require”
  • Example below

MathsDemo.js

function add(a, b){
    return a+b;
}
function subtract(a,b){
    return a-b;
}
module.exports.add = add;

ExecuteMaths.js

mathObject = require("./MathsDemo.js");
var output =  mathObject.add(10,20);
console.log('Result is : '+output);

Output :

Example : Writing data to a file

const fs = require('fs');
fs.writeFile('myfile', 'Hello World', (error)=>{
    if(error) {
        console.log('Error while saving data');
    }
});

Example : Taking user input and storing data to file

const readline = require('readline'); //Read Line API
const fs = require('fs'); //File System API

const wirteToFile = (data) => {
    fs.writeFile('myfile', `${data}`, error => {
        if(error) {
            console.log('Data has been saved');
        }
    });
};

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('Enter data ', (data) => {
  wirteToFile(data);
  rl.close();
});

When to use Node JS

Node is good at following work :

  • Non-Blocking
    • After making an api call, it does not wait for the response of that API, instead it writes a call back which handles the event of getting data from API and puts it list of events that it has to execute one by one.
  • Event-Driven
    • Waits for a event to happen and executes the event
  • Data-intensive
    • When lots of data has to be handled but not processed
  • I/O intensive
    • Waiting for lots of Input and Output devices together

Node is not good for follow work :

  • Data Calculation of large amount
  • Processor Intensive
  • Blocking Operations

Example Applications :

  • WebServers
    • Because of event driven model
  • APIs fronting NO SQL DB
  • Command Line utilities
  • Build Tooling

Download Node JS and change version using NVM

On Ubuntu :

  • You can download using Ubuntu repository
--Check the repository available node version using command
sudo apt-cache show nodejs
--Install nodejs using below command
sudo apt install nodejs

All the steps are mentioned in below url

https://github.com/nodesource/distributions/blob/master/README.md

Node Version Manager (NVM)

  • There are many tools available on internet to manage node versions
  • We are going to use NVM in our case
  • Below is the link for documentation
    https://github.com/nvm-sh/nvm#installing-and-updating
  • Run below command to install nvm
----download using below command
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.1/install.sh | bash
----reload the bashrc
source ~/.bashrc
----List of node version
nvm list-remote
----Install a node version
nvm install v14.15.1
----List of installed node version installed on your system
nvm list
----Change the node version using nvm
nvm use v14.15.1
----Check node version
node -v
----Change Back to system version of nodejs
nvm use system

What is Node JS

Node JS is a JavaScript runtime build on Chrome’s V8 JavaScript engine

  • Java Script is a language which runs on web browser.
  • Web Browsers uses Java Script Engines implemented inside it to run the Java Script.
  • One of the JavaScript engine is V8 which is implemented inside Chromebrowser.
  • Node JS uses the same V8 engine but instead of running it on web browser it run it on the operating system itself.
  • Just like WebBrowser gives JavaScript access to the web page DOM, Node JS gives access to the operating system’s file system, processes, memory, I/O, network

Defining Primitive DataTypes

You can indicate a var as a number, boolean or String using the below command.

var a : number;
var b : boolean;
var c : String;
var d : number|boolean //number or boolean can be stored in this variable
a = 10;
b = true;
c= "Hello World";
d=true;

If you assign a incorrect type to a variable then TypeScript compilation will fail
Example : Below

var a : number;
var b : boolean;
var c : String;

a = 10;
b = true;
c= 20;

Compilation of above code will give you error :

PGP Encryption and Decryption Snippet

Converting public key to PGPpublickey in java:

(new JcaPGPKeyConverter().getPGPPublicKey(PGPPublicKey.RSA_GENERAL, <PublicKey object>, new Date()))

Converting Privatekey to PGPPrivatekey in java:

(new JcaPGPKeyConverter().getPGPPrivateKey(<PublicKey object>, <PrivateKey object>))

Certificate extenstions:

Application would support .CER or *.CRT certificate extensions

Encryption :

	public static void rsaEncryptFile(OutputStream out, String fileName,  PGPPublicKey encKey, boolean armor,
			boolean withIntegrityCheck)  {
		
		try {
			Security.addProvider(new BouncyCastleProvider());

			if (armor) {
				out = new ArmoredOutputStream(out);
				
			}

			ByteArrayOutputStream bOut = new ByteArrayOutputStream();
		

			PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);

			PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY,new File(fileName));
			

			comData.close();

			JcePGPDataEncryptorBuilder c = new JcePGPDataEncryptorBuilder(PGPEncryptedData.AES_256)
					.setWithIntegrityPacket(withIntegrityCheck).setSecureRandom(new SecureRandom()).setProvider("BC");

			PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(c);

			JcePublicKeyKeyEncryptionMethodGenerator d = new JcePublicKeyKeyEncryptionMethodGenerator(encKey)
					.setProvider(new BouncyCastleProvider()).setSecureRandom(new SecureRandom());

			cPk.addMethod(d);

			
			byte[] bytes = bOut.toByteArray();

			OutputStream cOut = cPk.open(out, bytes.length); 
			
			  cOut.write((bytes));
//			  bw.write(Base64.getEncoder().encodeToString(bytes));
//			  FileUtils.copyFile(new File("D:\\Development_Docs\\PGP\\Bulk\\plain-text-common.pgp"), cOut);
			
			  
			  
			  cOut.close();
			  out.close();
			 // bw.close();
			
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}

Decryption :

	@SuppressWarnings("unchecked")
	public void rsaDecryptFile(InputStream in, OutputStream out, PGPPrivateKey priK)  {
		try {
			Security.addProvider(new BouncyCastleProvider());
			
			in = org.bouncycastle.openpgp.PGPUtil.getDecoderStream(in);
			PGPObjectFactory pgpF = new PGPObjectFactory(in);
			PGPEncryptedDataList enc;
			Object o = pgpF.nextObject();
			//
			// the first object might be a PGP marker packet.
			//
			if (o instanceof PGPEncryptedDataList) {
				enc = (PGPEncryptedDataList) o;
			} else {
				enc = (PGPEncryptedDataList) pgpF.nextObject();
			}

			//
			// find the secret key
			//
			Iterator<PGPPublicKeyEncryptedData> it = enc.getEncryptedDataObjects();
			PGPPrivateKey sKey = null;
			PGPPublicKeyEncryptedData pbe = null;

			while (sKey == null &amp;&amp; it.hasNext()) {
				pbe = it.next();
//				sKey = findSecretKey(pubK, pbe.getKeyID(), priK);
				sKey = priK;
				

			}

			if (sKey == null) {
				throw new IllegalArgumentException("Secret key for message not found.");
			}

			
			
			
			PublicKeyDataDecryptorFactory b = new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC")
					.setContentProvider("BC").build(sKey);

			InputStream clear = pbe.getDataStream(b);
			PGPObjectFactory plainFact = new PGPObjectFactory(clear);

			Object message = plainFact.nextObject();
			System.out.println("Secret key info 3:: " + pbe.getKeyID() + new Date());
			if (message instanceof PGPCompressedData) {
				PGPCompressedData cData = (PGPCompressedData) message;
				PGPObjectFactory pgpFact = new PGPObjectFactory(cData.getDataStream());

				message = pgpFact.nextObject();
			}
			
			if (message instanceof PGPLiteralData) {
				PGPLiteralData ld = (PGPLiteralData) message;
				InputStream unc = ld.getInputStream();
				int ch;
				

				
				/*
				 * while ((ch = unc.read()) >= 0) { out.write(ch); }
				 */
				 

				FileUtils.copyInputStreamToFile(unc, new File("D:\\Development_Docs\\PGP\\Bulk\\target.txt"));

				
			} else if (message instanceof PGPOnePassSignatureList) {
				throw new PGPException("Encrypted message contains a signed message - not literal data.");
			} else {
				throw new PGPException("Message is not a simple encrypted file - type unknown.");
			}
			

			if (pbe.isIntegrityProtected()) {
				if (!pbe.verify()) {
					throw new PGPException("Message failed integrity check");
				}
			}
			
			
		}catch (PGPException e) {
			// TODO: handle exception
			e.printStackTrace();
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		
	}

Verifying Digital Signature

package bouncyCastle;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Signature;

public class VerifyingDigitalSignature {
	public static void main(String args[]) throws Exception {
		
		// Creating KeyPair generator object
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA","BC");

		// Initializing the key pair generator
		keyPairGen.initialize(2048);

		// Generate the pair of keys
		KeyPair pair = keyPairGen.generateKeyPair();

		// Getting the privatekey from the key pair
		PrivateKey privKey = pair.getPrivate();

		// Creating a Signature object
		Signature sign = Signature.getInstance("SHA256withDSA");

		// Initializing the signature
		sign.initSign(privKey);
		byte[] bytes = "Hello how are you".getBytes();

		// Adding data to the signature
		sign.update(bytes);

		// Calculating the signature
		byte[] signature = sign.sign();

		// Initializing the signature
		sign.initVerify(pair.getPublic());
		sign.update(bytes);

		// Verifying the signature
		boolean bool = sign.verify(signature);

		if (bool) {
			System.out.println("Signature verified");
		} else {
			System.out.println("Signature failed");
		}
	}

}