You are on page 1of 5

package aes;

import java.security.*;

import java.security.spec.InvalidKeySpecException;

import java.util.Scanner;

import javax.crypto.*;

import javax.crypto.spec.SecretKeySpec;

import sun.misc.*;

public class Aes {

private static final String ALGO = "AES";

private static final byte[] keyValue =

new byte[] { 'T', 'h', 'e', 'B', 'e', 's', 't',

'S', 'e', 'c', 'r','e', 't', 'K', 'e', 'y' };

static String password = "mait12345";

public static String encrypt(String Data) throws Exception {

Key key = generateKey();

Cipher c = Cipher.getInstance(ALGO);

c.init(Cipher.ENCRYPT_MODE, key);

byte[] encVal = c.doFinal(Data.getBytes());

String encryptedValue = new BASE64Encoder().encode(encVal);

return encryptedValue;

}
public static String decrypt(String encryptedData) throws Exception {

Key key = generateKey();

Cipher c = Cipher.getInstance(ALGO);

c.init(Cipher.DECRYPT_MODE, key);

byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);

byte[] decValue = c.doFinal(decordedValue);

String decryptedValue = new String(decValue);

return decryptedValue;

private static Key generateKey() throws Exception {

Key key = new SecretKeySpec(keyValue, ALGO);

return key;

public static void main(String[] args) throws Exception {

Scanner sc = new Scanner(System.in);

Scanner sc1 = new Scanner(System.in);

Scanner sc2 = new Scanner(System.in);

System.out.print("Enter the name of device : ");

String dev1 = sc.nextLine();

System.out.print("Enter the range of device between 1 and 100 : ");

int range1 = sc.nextInt();

if(range1<1||range1 >100)

System.out.println("Range not Accepted");

System.exit(0);
}

System.out.print("Enter the name of device 2 : ");

String dev2 = sc1.nextLine();

System.out.print("Enter the range of device 2 : ");

int range2 = sc.nextInt();

if(range2>range1)

System.out.println("Not in Range ");

System.exit(0);

else if(range2<1)

System.out.println("Enter only positive range");

System.exit(0);

else

System.out.println("In range, proceeding to connect..");

String passwordEnc = Aes.encrypt(password);

String passwordDec = Aes.decrypt(passwordEnc);


System.out.println("Details Entered\nDevice 1 \nName : "+dev1+"\nRange : "+range1);

System.out.println("Device 2 \nName : "+dev2+"\nRange : "+range2);

System.out.print("Enter password : ");

String pass = sc2.nextLine();

String passenc = Aes.encrypt(pass);

System.out.println("Encrypted Text : " + passwordEnc);

System.out.println("Decrypted Text : " + passwordDec);

if(passenc.equals(passwordEnc))

System.out.println("Password Match !\nDevice Connected Successfully");

else

System.out.println("Password Didnot matched!\nDevice not Connected");

You might also like