import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import java.util.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 
 * OpenSSL equivalent for AES encryption with and without PBKDF2 and key-obtention iteration (-iter)
 * 
 * References:
 * 
 *
 */
public class AesStringEncryptor {
	
	private static final byte[] SALTED_MAGIC = "Salted__".getBytes();
	
	private final String pbeAlgorithm;
	private final String digestAlgorithm;
	private final int keyLengthInByte;
	
	
	private String encryptionPassword = "";
	private int keyObtentionIterations = 10000; // 10000 is openssl's default
	

	/**
	 * 
	 * @param pbeAlgorithm - "AES/CBC/PKCS5Padding", "AES/ECB/PKCS5Padding"
	 * @param digestAlgorithm - "SHA-256", "MD5"
	 * @param keyLengthInBit - 128, 256
	 * @throws NoSuchPaddingException 
	 * @throws NoSuchAlgorithmException 
	 */
	public AesStringEncryptor(String pbeAlgorithm, String digestAlgorithm, int keyLengthInBit) throws NoSuchAlgorithmException, NoSuchPaddingException {
		super();
		this.pbeAlgorithm = pbeAlgorithm;
		this.digestAlgorithm = digestAlgorithm;
		this.keyLengthInByte = keyLengthInBit / 8;	
	}
	


	public String getEncryptionPassowrd() {
		return encryptionPassword;
	}

	public void setEncryptionPassowrd(String encryptionPassowrd) {
		this.encryptionPassword = encryptionPassowrd;
	}

	
	public int getKeyObtentionIterations() {
		return keyObtentionIterations;
	}

	public void setKeyObtentionIterations(int keyObtentionIterations) {
		this.keyObtentionIterations = keyObtentionIterations;
	}

	public String encryptString(String clearText, String password) 
			throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException {
		return this.encryptString(clearText, password, false, -1);
	}
	
	public String encryptString(String clearText) 
			throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException {
		return this.encryptString(clearText, this.encryptionPassword);
	}
	
	public String encryptStringWithPBKDF2(String clearText, String password, int hashIterations) 
			throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException {   
	    return this.encryptString(clearText, password, true, hashIterations);
	}
	
	private String encryptString(String clearText, String password, boolean pbkdf2, int hashIterations) 
			throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException {
		final byte[] salt = (new SecureRandom()).generateSeed(8);
	    final byte[] inBytes = clearText.getBytes(StandardCharsets.UTF_8);
	    	    
	    byte[] keyAndIv = new byte[0];
	    if(pbkdf2) {
	    	keyAndIv = deriveKeyAndIvWithPBKDF2(password, hashIterations, salt);
	    }else {
	    	keyAndIv = deriveKeyAndIv(password.getBytes(StandardCharsets.ISO_8859_1), salt);
	    }
	    

	    // AES-256: 32 bytes key, 16 bytes iv
	    // AES-128: 16 bytes key, 16 bytes iv
	    final byte[] keyValue = Arrays.copyOfRange(keyAndIv, 0, this.keyLengthInByte);    	    
	    final SecretKeySpec key = new SecretKeySpec(keyValue, "AES");

		Cipher cipher = Cipher.getInstance(this.pbeAlgorithm);
	    if(this.pbeAlgorithm.contains("ECB")) {
	    	cipher.init(Cipher.ENCRYPT_MODE, key);
	    }else {
	    	// CBC
	    	final byte[] iv = Arrays.copyOfRange(keyAndIv, this.keyLengthInByte, (this.keyLengthInByte + 16));
	    	cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
	    }
	    
	    byte[] data = cipher.doFinal(inBytes);
	    data =  array_concat(array_concat(SALTED_MAGIC, salt), data);
	    return Base64.getEncoder().encodeToString( data );
	}
	
	public String encryptStringWithPBKDF2(String clearText) 
			throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException {
		return this.encryptStringWithPBKDF2(clearText, encryptionPassword, keyObtentionIterations);
	}
	
	public String encryptStringWithPBKDF2(String clearText, String password) 
			throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException {
		return this.encryptStringWithPBKDF2(clearText, password, keyObtentionIterations);
	}
	
	public String decrypt(String encryptedBase64, String password) 
			throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException {
	    return this.decrypt(encryptedBase64, password, false, -1);
	}
	
	public String decrypt(String encryptedBase64) 
			throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException {
		return this.decrypt(encryptedBase64, this.encryptionPassword);
	}
	
	public String decryptWithPBKDF2(String encryptedBase64, String password, int hashIterations) 
			throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException {
	    
	    return this.decrypt(encryptedBase64, password, true, hashIterations);
	}
	
	private String decrypt(String encryptedBase64, String password, boolean pbkdf2, int hashIterations) 
			throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException {
	    
		final byte[] inBytes = Base64.getDecoder().decode(encryptedBase64);

	    final byte[] shouldBeMagic = Arrays.copyOfRange(inBytes, 0, SALTED_MAGIC.length);
	    if (!Arrays.equals(shouldBeMagic, SALTED_MAGIC)) {
	        throw new IllegalArgumentException("Bad magic number. Initial bytes from input do not match OpenSSL SALTED_MAGIC salt value.");
	    }

	    final byte[] salt = Arrays.copyOfRange(inBytes, SALTED_MAGIC.length, SALTED_MAGIC.length + 8);
	    
	    byte[] keyAndIv = new byte[0];
	    if(pbkdf2) {
	    	keyAndIv = deriveKeyAndIvWithPBKDF2(password, hashIterations, salt);
	    }else {
	    	keyAndIv = deriveKeyAndIv(password.getBytes(StandardCharsets.ISO_8859_1), salt);
	    }	    

	    final byte[] keyValue = Arrays.copyOfRange(keyAndIv, 0, this.keyLengthInByte);
	    final SecretKeySpec key = new SecretKeySpec(keyValue, "AES");


		Cipher cipher = Cipher.getInstance(this.pbeAlgorithm);
	    if(this.pbeAlgorithm.contains("ECB")) {
	    	cipher.init(Cipher.DECRYPT_MODE, key);
	    }else {
	    	// CBC
	    	final byte[] iv = Arrays.copyOfRange(keyAndIv, this.keyLengthInByte, (this.keyLengthInByte + 16));
	    	cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
	    }
	    
	    final byte[] clear = cipher.doFinal(inBytes, 16, inBytes.length - 16);
	    return new String(clear, StandardCharsets.UTF_8);
	}
	
	public String decryptWithPBKDF2(String encryptedBase64) 
			throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException {
		return this.decryptWithPBKDF2(encryptedBase64, this.encryptionPassword, this.keyObtentionIterations);
	}
	
	public String decryptWithPBKDF2(String encryptedBase64, String password) 
			throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException {
		return this.decryptWithPBKDF2(encryptedBase64, password, this.keyObtentionIterations);
	}
	
	private byte[] deriveKeyAndIv(final byte[] pass, final byte[] salt) throws NoSuchAlgorithmException {
		MessageDigest md = MessageDigest.getInstance(this.digestAlgorithm);
	    final byte[] passAndSalt = array_concat(pass, salt);
	    byte[] hash = new byte[0];
	    byte[] keyAndIv = new byte[0];
	    for (int i = 0; i < 3 && keyAndIv.length < 48; i++) {
	        final byte[] hashData = array_concat(hash, passAndSalt);
	        hash = md.digest(hashData);
	        keyAndIv = array_concat(keyAndIv, hash);
	    }
		return keyAndIv;
	}

	private byte[] deriveKeyAndIvWithPBKDF2(String password, int hashIterations, final byte[] salt)
			throws NoSuchAlgorithmException, InvalidKeySpecException {
		SecretKeyFactory keyFactory = null;
	    if("SHA-256".equals(this.digestAlgorithm)) {
	    	keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
	    } else {
	    	// MD5
	    	// "In addition, MD5 hash function is forbidden to be used with PBKDF2 such as PBKDF2WithHmacMD5."
	    	throw new UnsupportedOperationException("MD5 hash function is not supported with PBKDF2");
	    }
	    
	    PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, hashIterations, 48 * 8);
	    byte[] keyAndIv = keyFactory.generateSecret(keySpec).getEncoded();
		return keyAndIv;
	}
	
	private byte[] array_concat(final byte[] a, final byte[] b) {
		final byte[] c = new byte[a.length + b.length];
		System.arraycopy(a, 0, c, 0, a.length);
		System.arraycopy(b, 0, c, a.length, b.length);
		return c;
	}
	
	
	public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException {
		String encrypted = "";
		
		// echo -n plainTextToEncrypt| openssl enc -base64 -aes-256-cbc -md sha256 -pass pass:secretKey -p
		AesStringEncryptor aes256Cbc = new AesStringEncryptor("AES/CBC/PKCS5Padding", "SHA-256", 256);
		encrypted = aes256Cbc.encryptString("plainTextToEncrypt", "secretKey");
		System.out.println("Encrypted aes-256-cbc sha256: " + encrypted + " , Decrypted: " + aes256Cbc.decrypt(encrypted, "secretKey"));
		
		// echo -n plainTextToEncrypt| openssl enc -base64 -aes-256-cbc -md sha256 -pass pass:secretKey -p -pbkdf2
		encrypted = aes256Cbc.encryptStringWithPBKDF2("plainTextToEncrypt", "secretKey");
		System.out.println("Encrypted aes-256-cbc sha256 pbkdf2: " + encrypted + ", Decrypted: " + aes256Cbc.decryptWithPBKDF2(encrypted, "secretKey") );
		
		AesStringEncryptor aes128Cbc = new AesStringEncryptor("AES/CBC/PKCS5Padding", "SHA-256", 128);			
		encrypted = aes128Cbc.encryptString("plainTextToEncrypt", "secretKey");
		System.out.println("Encrypted aes-128-cbc sha256: " + encrypted + " , Decrypted: " + aes128Cbc.decrypt(encrypted, "secretKey"));
		
		encrypted = aes128Cbc.encryptStringWithPBKDF2("plainTextToEncrypt", "secretKey");
		System.out.println("Encrypted aes-128-cbc sha256 pbkdf2: " + encrypted + ", Decrypted: " + aes128Cbc.decryptWithPBKDF2(encrypted, "secretKey") );
		
		AesStringEncryptor aes256Ecb = new AesStringEncryptor("AES/ECB/PKCS5Padding", "SHA-256", 256);	
		encrypted = aes256Ecb.encryptString("plainTextToEncrypt", "secretKey");
		System.out.println("Encrypted aes-256-ecb sha256: " + encrypted + " , Decrypted: " + aes256Ecb.decrypt(encrypted, "secretKey"));
		
		// echo -n plainTextToEncrypt| openssl enc -base64 -aes-256-cbc -md md5 -pass pass:secretKey -p
		AesStringEncryptor aes256EcbMd5 = new AesStringEncryptor("AES/ECB/PKCS5Padding", "MD5", 256);	
		encrypted = aes256EcbMd5.encryptString("plainTextToEncrypt", "secretKey");
		System.out.println("Encrypted aes-256-ecb md5: " + encrypted + " , Decrypted: " + aes256EcbMd5.decrypt(encrypted, "secretKey"));

		// Not supported 
		// encrypted = aes256EcbMd5.encryptStringWithPBKDF2("plainTextToEncrypt", "secretKey");
		// System.out.println("Encrypted aes-256-ecb md5 pbkdf2: " + encrypted + " , Decrypted: " + aes256EcbMd5.decryptWithPBKDF2(encrypted, "secretKey"));

	}

} 

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.