Java Encryption - Decryption Code

package myLib;


import java.io.UnsupportedEncodingException;

import java.security.GeneralSecurityException;

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

import java.security.SecureRandom;

import javax.crypto.Cipher;

import javax.crypto.NoSuchPaddingException;

import javax.crypto.spec.IvParameterSpec;

import javax.crypto.spec.SecretKeySpec;

import javax.xml.bind.DatatypeConverter;

import org.apache.xml.security.exceptions.Base64DecodingException;


/**

 *

 * @author Mohit Kumar Gupta

 */

public class CryptoAES256 {


   public static void main(String[] args) {

        try {

            String passP = "Bar12345Barjhggfh12345"; // 128 bit key

            String encryptedString = encrypt(passP, "Hello Mohit");

            System.out.println("EncryptedString= " + encryptedString);

            String decryptedString = decrypt(passP, encryptedString);

            System.out.println("DecryptedString= " + decryptedString);

//        System.out.println(decrypt(key, initVector,

//                encrypt(key, initVector, "Hello World")));


            String passPhase = "Bar1234";

            String value = "Hello Mohit 1 2 3 4 5 6";

            String enc = encrypt(passPhase, value);

            String dec = decrypt(passPhase, enc);

            System.out.println(enc);

            System.out.println(dec);

        } catch (Exception e) {

            e.printStackTrace();

        }

    }


    private static SecretKeySpec getKeySpec(String passphrase) throws NoSuchAlgorithmException, UnsupportedEncodingException {

        MessageDigest digest = MessageDigest.getInstance("SHA-256");

        return new SecretKeySpec(digest.digest(passphrase.getBytes("UTF-8")), "AES");

    }


    private static Cipher getCipher() throws NoSuchPaddingException, NoSuchAlgorithmException {

        return Cipher.getInstance("AES/CBC/PKCS5PADDING");

    }


    public static String encrypt(String passphrase, String value) throws GeneralSecurityException, UnsupportedEncodingException {

        byte[] initVector = new byte[16];

        SecureRandom.getInstanceStrong().nextBytes(initVector);

        Cipher cipher = getCipher();

        cipher.init(Cipher.ENCRYPT_MODE, getKeySpec(passphrase), new IvParameterSpec(initVector));

        byte[] encrypted = cipher.doFinal(value.getBytes());

        return DatatypeConverter.printBase64Binary(initVector)

                + DatatypeConverter.printBase64Binary(encrypted);

    }


    public static String decrypt(String passphrase, String encrypted) throws GeneralSecurityException, UnsupportedEncodingException, Base64DecodingException {

        byte[] initVector = DatatypeConverter.parseBase64Binary(encrypted.substring(0, 24));

        Cipher cipher = getCipher();

        cipher.init(Cipher.DECRYPT_MODE, getKeySpec(passphrase), new IvParameterSpec(initVector));

        byte[] original = cipher.doFinal(DatatypeConverter.parseBase64Binary(encrypted.substring(24)));

        return new String(original);

    }

}


How to make Eggless Chocolate Cake in Home in microwave

 Ingredients:

1> 1 glass wheat floor
2> 2 tbs sooji
3> 3 tbs coca powder
4> 1 tbs baking powder
5> 0.25 tbs baking soda
6> 0.75 glass sugar
7> 2 spoon refined oil
8> 1pc leamon
9> 1 tbs vanila essence

Procedure to prepare cake:

I> Prepration of dry mixture
1> Sheve (chal le chalni se) Wheat floor, coca powder, baking powder, sooji and keep the mixture in dry vessel.

II> Prepration of fluid:
1> Powder sugar in mixi
2> In a pot add milk, powdered sugar, refine oil and mix them well.

III> Greese microwave pot with oil and kept asside

IV> Mixing dry mixture and fluid, and setting it to microwave pot and keeping in microwave:
1> To the fluid pot, add dry mixture and mix them well so that there is no lumps
2> If you want mix them in Mixi Jar to form a smooth paste
3> To that paste, add vanila essence, lemon and mix well
4> Add baking soda and mix well and quickly pour mixture in microwave pot
5> Then by hammering microwave pot to ground in downward side, remove air bubbles as much as possible
6> Quickly keep microwave pot in microwave
7> Set microwave mode and power to 9000 and set timer to 7minutes (around).

V> Complition of cooking of cake
1>When timer is about 6 minute, check if cake is dry and cooked by pausing microwave and pricing a knife in the centre of cake in microwave pot.
2> If cake is cooked, knife will come out dry else, again cook for next 30 second and repeat step V.1 above.
3> Finally turn of microwave and let cake remain inside it for next 5-10 minutes
4> Bring out cake and let it cool

SERVE THE CAKE.

You can also decorate cake as you want.

Debian Server Useful Commands (Dynamic Post, updated very frequently, for notes use)

For System Restart: sudo reboot

============================================

For Using 7z:

To install 7z-full:

sudo apt-get update
sudo apt-get install p7zip-full

To add a files file to 7z archive:

7z a <7z-archive-file-name>.7z {files to be archived}

e.g 7z a Apache-NetBeans-12.0-bin-windows-x64.exe.7z Apache-NetBeans-12.0-bin-windows-x64.exe


==============================================

To send a running process in background in terminal

Ctrl+z
bg

Now to bring back that process in forground

fg

To start a command directly in background

Type command &
e.g 7z a Apache-NetBeans-12.0-bin-windows-x64.exe.7z Apache-NetBeans-12.0-bin-windows-x64.exe &

To view processes running in background

jobs


How to do settings for Mobile Device Compatibility in Blogger / Fix Blogger Issue "Viewport not set to "device-width"

Steps:

1> Go to blogger.com (login to your account)
2> Select themes -> There in MyThemes, in click three dots
3> Click Mobile Device Settings
4> In <Do you want to show Desktop or Mobile theme on mobile devices?>, choose Mobile Device
5> In configure Mobile View, select your appropriate Theme Category of your choice -> Then choose desired theme
6> Thats all, Your Blogger is now compatible in Mobile Devices and Your Shouldn't Get any Error Message from Google Search Console as below:

Top Issues

The following issues were found on your site:

Viewport not set to "device-width"

Text too small to read

Clickable elements too close together

How to add your domain / url / blog to Google Search Engine or console

Hey, I would like to discuss how to add your domain / url / blog to Google Search Engine or console:

2> verify your domain/url/blog that you are actual owner of it
3> in inpect your url box in the top centre of page, add your url, and press enter
4> then you can press <Test Live Url> button to check if URL is accessable in internet
5> you can then press <Request Indexing> link to get your URL indexed in google search engine
6> upon submittion of submitting request, your URL will be verified to exist, and queued in Google Search Engine indexing task (i.e crawl queue) which may take from sometime to somedays.
7> After your URL is indexed in Google Search Engine, more your site gets visited, more the chance that it will appare in Google Search.
8> For enhanced search you can also try paid service of Google Search

Series: My Database Concepts - JDBC vs JPA / Hibernate

Lot of times questions arise in mind that what to use pure JDBC or JPA/Hibernate.

Well, if performance is compared JDBC is much faster and uses less memory than Hibernate.

But if you plan to work safely, in a less error prone manner while writing Database code, you will need to you Hibernate.

So, finally in my opinion, if you are confidence enough that if you can write JDBC codes properly, have good knowledge of JDBC, you should use JDBC.
Also, if you think you will be able to learn SQL / JDBC properly if you don't know yet, and want to create some JAVA Database project, in this case also you can use JDBC.

But if you don't want to waste too much of time in learning JDBC and writing proper codes and spend time upon testing those codes, use JPA/ Hibernate. But in this case you will need few byes of memory extra, and also performance will be downgraded by a bit in comparison with JDBC.

Note: when these points are considered, following points are important to note:
1> In JDBC you can use DBCP or any other .jar file for connection pooling.
2> You are always using prepared statements / callable statements while using JDBC.
3> When using JPA / Hibernate, it also converts JPQL / HQL to relevant SQL codes for executing SQL statements.

Draft of Java code to save NSE Historical Data in file System instead of Database, Just For TRY! Not yet tested at all

package entitity;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.stream.Stream;

public class HD implements Serializable {
public static void main(String args[]) {
String csvFilePath = "D:\\nseEquityHistoricalDataCsv\\20200116\\"
+ "Quote-Equity-INFRATEL-EQ-14-03-2020-to-14-06-2020.csv";
String dbPath = "D:\\javaWebServers\\ApacheTomEE\\nseeq\\";
String hdTablePath = dbPath + "hd.tb", hdLogPath = dbPath + "hd.lg";

try (Stream<String> stream1 = Files.lines(Paths.get(csvFilePath));
Stream<String> stream2 = Files.lines(Paths.get(csvFilePath))) {
String[] headerLineArr = stream1.findFirst().get().toString().replaceAll("\"", "").split(",");
for (Integer i = 0; i < headerLineArr.length; i++) {
headerLineArr[i] = headerLineArr[i].trim();
}
stream2.skip(1).forEach(e -> {
HD hd = new HD("INFRATEL", headerLineArr, e.replaceAll("\"", ""));
System.out.println(hd.toString());
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

LocalDate d;
String s;
String series;
Double pc, o, h, l, ltp, c;
Long v;
Double turnover;
Double _52WH, _52WL;
Long noOfTrades;
Boolean delFlag = false;

private static final DateTimeFormatter dft = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
private static final Integer logFileHeapSize = 512;

public HD(String s, String[] headerLineArr, String line) {
String[] lineArr = line.replaceAll("\"\"", "").split(",");
HashMap<String, String> row = new HashMap<String, String>();
for (Integer i = 0; i < headerLineArr.length; i++) {
row.put(headerLineArr[i], lineArr[i].trim());
}
// this.d=LocalDate.parse(row.get("Date"),dft);
this.d = LocalDate.parse(lineArr[0], dft);
this.s = s;
this.series = row.get("series");
this.pc = Double.valueOf(row.get("PREV. CLOSE"));
this.o = Double.valueOf(row.get("OPEN"));
this.h = Double.valueOf(row.get("HIGH"));
this.l = Double.valueOf(row.get("LOW"));
this.ltp = Double.valueOf(row.get("ltp"));
this.c = Double.valueOf(row.get("close"));
this.v = Long.valueOf(row.get("VOLUME"));
this.turnover = Double.valueOf(row.get("VALUE"));
this._52WH = Double.valueOf(row.get("52W H"));
this._52WL = Double.valueOf(row.get("52W L"));
this.noOfTrades = Long.valueOf(row.get("No of trades"));
}
    
        //default constructor and other constructers omitted for brevity
// getters and setters omitted for brevity

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((d == null) ? 0 : d.hashCode());
result = prime * result + ((s == null) ? 0 : s.hashCode());
result = prime * result + ((series == null) ? 0 : series.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
HD other = (HD) obj;
if (d == null) {
if (other.d != null)
return false;
} else if (!d.equals(other.d))
return false;
if (s == null) {
if (other.s != null)
return false;
} else if (!s.equals(other.s))
return false;
if (series == null) {
if (other.series != null)
return false;
} else if (!series.equals(other.series))
return false;
return true;
}

@Override
public String toString() {
// omitted for brevity
}

public static void deFragmentTable(String filePath) throws IOException, ClassNotFoundException {
// set names of logFile and tmp file
String logFilePath = filePath.substring(0, filePath.length() - 2) + "lg";
if (Files.size(Paths.get(logFilePath)) < logFileHeapSize * 1000000) {
return;
}
String tmpPath = filePath.subSequence(0, filePath.length() - 2) + "tmp";
// read form tb file in a set
FileInputStream fis = new FileInputStream(filePath);
ObjectInputStream ois = new ObjectInputStream(fis);
HashSet<HD> set = (HashSet<HD>) ois.readObject();
ois.close();
// update set from log file to latest values
ois = new ObjectInputStream(new FileInputStream(logFilePath));
while (true) {
try {
HD obj = (HD) ois.readObject();
set.remove(obj);
set.add(obj);
} catch (EOFException e) {
break;
}
}
// write set to tmp file
File fileTmp = new File(tmpPath, "w");
fileTmp.createNewFile();
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileTmp))) {
oos.writeObject(set);
}
// deletes old table file and log file, them rename tmp file to table file
Files.delete(Paths.get(filePath));
Files.delete(Paths.get(logFilePath));
new File(tmpPath).renameTo(new File(filePath));
}
public static void insert(String filePath, HD obj) throws Exception {
HD prevObj = getLatestPrevObject(filePath, obj);
// if object don't exists in filePath, write object in file path
if (prevObj==null) {
writeObjectInFilePath(filePath, prevObj);
} else {
// if object in deleated status in logPath, write object in logPath
if (prevObj.getDelFlag()) {
writeObjectInLogPath(filePath, prevObj);
} else {
// if object not in deleated status in filePath, throw onject already exists
// exception
throw new Exception("Object already exists");
}
}
}

public static void update(String filePath, HD obj) throws Exception {
HD prevObj = getLatestPrevObject(filePath, obj);
// if object exists and not in deleated state
if(prevObj!=null && !prevObj.getDelFlag()) {
writeObjectInLogPath(filePath, prevObj);
}else {
// throw object not exists exception
throw new Exception("object not available for update as it don't exists");
}
}
public static void delete(String filePath,HD obj) throws Exception {
HD prevObj = getLatestPrevObject(filePath, obj);
// if object exists and not in deleated state
if(prevObj!=null && !prevObj.getDelFlag()) {
prevObj.setDelFlag(true);
writeObjectInLogPath(filePath, prevObj);
}else {
// throw object not exists exception
throw new Exception("object not available for deletion as it don't exists");
}
}

public static HD findObjectInFilePath(String filePath, HD obj) throws IOException, ClassNotFoundException {
HD prevObj = null;
// check if object already exists in filePath
Boolean objectFoundInFilePath = false;
File file = new File(filePath);
file.createNewFile();
ObjectInputStream isFilePath = new ObjectInputStream(new FileInputStream(file));
while (!objectFoundInFilePath) {
try {
HD obj2 = (HD) isFilePath.readObject();
if (obj.equals(obj2)) {
prevObj = obj2;
objectFoundInFilePath = true;
}
} catch (EOFException e) {
break;
}
}
isFilePath.close();
return prevObj;
}

public static void updateLatestObjectInLogPath(String filePath, HD prevObj)
throws IOException, ClassNotFoundException {
// if object exists in filePath, get this final object in logPath
String logFilePath = filePath.substring(0, filePath.length() - 2) + "lg";
File logFile = new File(logFilePath);
logFile.createNewFile();
ObjectInputStream isLogPath = new ObjectInputStream(new FileInputStream(logFilePath));
while (true) {
try {
HD obj2 = (HD) isLogPath.readObject();
if (prevObj.equals(obj2)) {
prevObj = obj2;
}
} catch (EOFException e) {
break;
}
}
isLogPath.close();
}

public static HD getLatestPrevObject(String filePath, HD obj) throws ClassNotFoundException, IOException {
HD prevObj = findObjectInFilePath(filePath, obj);
if (prevObj == null) {
return null;
} else {
updateLatestObjectInLogPath(filePath, prevObj);
return prevObj;
}
}
public static void writeObjectInFilePath(String filePath,HD obj) throws FileNotFoundException, IOException {
File file=new File(filePath);
ObjectOutputStream osFilePath = new ObjectOutputStream(new FileOutputStream(file));
osFilePath.writeObject(obj);
osFilePath.close();
}
public static void writeObjectInLogPath(String filePath,HD obj) throws IOException, ClassNotFoundException {
String logFilePath = filePath.substring(0, filePath.length() - 2) + "lg";
ObjectOutputStream osLogPath = new ObjectOutputStream(new FileOutputStream(logFilePath));
osLogPath.writeObject(obj);
osLogPath.close();
deFragmentTable(filePath);
}
}

Regarding site Free Browser Tool (https://free-browser-tools.mohitkrgupta.dev) (discussion with google search AI)

Various discussions with Google Search AI regarding site  Free Browser Tool are as below: site free-browser-tools.mohitkrgupta.dev what doe...