Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

A) Caesar Cipher

Code :-
import java.io.*;
import java.util.*;

public class Solution{


public static final String alpha = "abcdefghijklmnopqrstuvwxyz";
public static String encrypt(String message, int shiftkey) {
message = message.toLowerCase();
String cipherText ="";
for (int i=0; i<message.length();i++) {
int charPosition = alpha.indexOf(message.charAt(i));
int keyVal = (shiftkey + charPosition) % 26;
char replaceVal = alpha.charAt(keyVal);
cipherText +=replaceVal;
}
return cipherText;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String message;
int key = 0;
System.out.print("Enter the String for Encryption: ");
message = sc.next();
System.out.println("\n\nEnter Shift Key: ");
key = sc.nextInt();
System.out.println("\nEncrypted Msg: "+ encrypt(message, key));
}
}

B) Monoalphabetic Cipher
Code :-
import java.io.*;
import java.util.*;
public class MonoCipher{
public static char p[] = {'a','b','c','d','e','f','g', 'h','i','j','k','l','m','n','o', 'p','q','r','s','t','u','v','w','x','y','z'};
public static char ch[] = {'Z','X','C','V','B','N','M',
'A','S','D','F','G','H','J','K','L','Q','W','E','R','T','Y','U','I','O','P'};
public static String doEncryption(String s){
char c[] = new char[(s.length())];
for (int i =0 ; i < s. length(); i++){
for (int j=0 ; j < 26 ; j++){
if (p[j] == s.charAt(i)){
c[i] = ch[j];
break;
}
}
}
return(new String(c));
}
public static String doDecryption(String s){
char p1[] = new char[(s.length())];
for (int i = 0 ; i < s.length() ; i++){
for ( int j = 0 ; j < 26 ; j++){
if (ch[j] == s.charAt(i)){
p1[i] = p[j];
break;
}
}
}
return (new String(p1));
}
public static void main(String[] arg){
Scanner sc = new Scanner(System.in);
System.out.print("Enter the message:");
String en = doEncryption(sc.next().toLowerCase());
System.out.println("Encypted message:" + en);
System.out.println("Decrypted message :" + doDecryption(en));
sc.close();
}
}

Vernam Cipher
Code :-
import java.lang.Math;
import java.util.*;
public class Vernam {
static String generator(String str, String key) {
int x = str.length();
for (int i = 0;; i++) {
if (x == i) {
i = 0;
}
if (key.length() == str.length()) {
break;
}
key += (key.charAt(i));
}
return key;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("ENTER THE STRING FOR ENCRYPTIION:");
String text = sc.next();
char[] arText = text.toCharArray();
System.out.print("ENTER THE KEY STRING:");
String keyword = sc.next();
String cipher = generator(text, keyword);
char[] arCipher = cipher.toCharArray();
char[] encoded = new char[text.length()];
System.out.println("ENCODED\n" +text+ "\nTO BE...");
for (int i = 0; i < arText.length; i++) {
encoded[i] = (char) (arText[i] ^ arCipher[i]);
System.out.print(encoded[i]);
}
System.out.println("\nDECODED TO BE...\n:");
for (int i = 0; i < encoded.length; i++) {
char temp = (char) (encoded[i] ^ arCipher[i]);
System.out.print(temp);
}
}
}

Playfair Cipher
Code :-
import java.awt.Point;
import java.util.Scanner;
public class PlayfairCipher {
private static char[][]charTable;
private static Point[]positions;
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
String key = prompt("ENTER AN ENCRYPTION KEY:(min length 6):",sc,6);
String txt = prompt("ENTER THE MESSAGE:",sc,1);
String jti = prompt("REPLACE J WITH I? y/n:",sc,1);
boolean changeJtoI = jti.equalsIgnoreCase("y");
createTable(key,changeJtoI);
String enc = encode(prepareText(txt,changeJtoI));
System.out.printf("%nENCODED MESSAGE:%n%s%n",enc);
System.out.printf("%nDECODED MESSASGE:%n%s%n",decode(enc));
}
private static String prompt(String promptText, Scanner sc, int minLen){
String s;
do{
System.out.print(promptText);
s=sc.nextLine().trim();
} while(s.length()<minLen);
return s;
}
private static String prepareText(String s,boolean changeJtoI) {
s= s.toUpperCase().replaceAll("[^A-Z]","");
return changeJtoI ? s.replace("J","I"): s.replace("J","");
}
private static void createTable(String key,boolean changeJtoI) {
charTable= new char[5][5];
positions = new Point[26];
String s =prepareText(key+"ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI);
int len = s.length();
for(int i=0,k=0;i<len;i++) {
char c= s.charAt(i);
if (positions[c-'A']==null) {
charTable[k / 5][k % 5] = c;
positions[c-'A'] = new Point(k % 5,k / 5);
k++;
}
}
}
private static String encode(String s){
StringBuilder sb = new StringBuilder(s);
for(int i=0;i<sb.length();i+=2) {
if(i== sb.length()-1)
sb.append(sb.length()%2 == 1?'X':"");
else if(sb.charAt(i) == sb.charAt(i+1))
sb.insert(i+1,'X');
}
return codec(sb,1);
}
private static String decode(String s){
return codec(new StringBuilder(s),4);
}
private static String codec(StringBuilder text, int direction){
int len = text.length();
for(int i=0;i<len;i+=2){
char a = text.charAt(i);
char b = text.charAt(i+1);
int row1 = positions[a-'A'].y;
int row2 = positions[b-'A'].y;
int col1 = positions[a-'A'].x;
int col2 = positions[b-'A'].x;
if (row1 == row2){
col1=(col1+direction)%5;
col2=(col2+direction)%5;
}
else if(col1==col2){
row1=(row1+direction)%5;
row2=(row2+direction)%5;
}
else{
int tmp = col1;
col1 = col2;
col2 = tmp;
}
text.setCharAt(i,charTable[row1][col1]);
text.setCharAt(i+1,charTable[row2][col2]);
}
return text.toString();
}
}

Rail Fence Cipher


Code :-
import java.util.Scanner;
public class RailFenceCipher1 {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("ENTER THE MESSAGE FOR ENCRYPTION: ");
String plainText = sc.nextLine();
System.out.println("ENTER THE DEPTH FOR ENCRYPTION: ");
int key = sc.nextInt();
String en = encryption(plainText, key);
System.out.println("\n ENCRYPTED MESSAGE IS: " + en);
System.out.println("\n DECRYPTED MESSAGE IS: " + decryption(en, key));
}
static String encryption(String text, int key)
{
String encryptedText = "";
boolean check = false;
int i, j, k = 0, row = key, col = text.length();
char[][] a = new char[row][col];
for (j = 0; j < col; j++) {
if (k == 0 || k == key - 1) {
check = !check;
}
a[k][j] = text.charAt(j);
if (check)
k++;
else
k--;
}
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
if (a[i][j] != 0)
encryptedText += a[i][j];
}
}
return encryptedText;
}
static String decryption(String text, int key)
{
String decryptedText="";
boolean check=false;
int i=0,j,row=key,col=text.length();
char[][] a=new char[row][col];
for(j=0;j<col;j++)
{
if(i==0||i==key-1)
{
check=!check;
}
a[i][j]='*';
if(check)
i++;
else
i--;
}
int index=0;
check=false;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
if(a[i][j]=='*' && index<col)
{
a[i][j]=text.charAt(index++);
}
}
}
i=0;
for(j=0;j<col;j++)
{
if(i==0||i==key-1)
{
check=!check;
}
decryptedText+=a[i][j];
if(check)
i++;
else
i--;
}
return decryptedText;
}
}

Simple Columnar
Code :-
import java.io.*;
import java.util.*;
import java.lang.*;
public class SimpleColumnar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("ENTER THE STRING FOR ENCRYPTION:");


String text = sc.nextLine();
System.out.print("ENTER KEY(not repeated):");
String key = sc.nextLine();
String line=System.getProperty("line.separator");
sc.useDelimiter(line);
String en = encryptCT(key,text).toUpperCase();
System.out.println("ENCRYPTED TEXT:"+en);
System.out.println("DECRYPTED TEXT:"+decryptCT(key,en));
}
public static String encryptCT(String key,String text)
{
int[] arrange = arrangeKey(key);
int lenkey = arrange.length;
int lentext = text.length();
int row = (int) Math.ceil((double) lentext/lenkey);
char[][] grid = new char[row][lenkey];
int z = 0;
for(int x=0;x<row;x++){
for(int y=0;y<lenkey;y++){
if(lentext==z){
grid[x][y] = RandomAlpha();
z--;
}else{
grid[x][y] = text.charAt(z);
}
z++;
}
}
for(int i=0;i<row;i++)
{
for(int j=0;j<lenkey;j++)
{
System.out.print(grid[i][j]+"");
}
System.out.println();
}
String enc = "";
for(int x=0;x<lenkey;x++){
for(int y=0;y<lenkey;y++){
if(x==arrange[y]){
for(int a=0;a<row;a++){
enc =enc +grid[a][y];
}
}
}
}return enc;
}
public static String decryptCT(String key,String text){
int[] arrange= arrangeKey(key);
int lenkey = arrange.length;
int lentext = text.length();
int row = (int) Math.ceil((double) lentext/lenkey);
String regex = "(?<=\\G.{" +row+ "})";
String[] get = text.split(regex);
char[][] grid = new char[row][lenkey];
for (int x= 0;x<lenkey;x++){
for (int y=0;y<lenkey;y++){
if(arrange[x]==y){
for(int z=0;z<row;z++){
grid[z][y] = get[arrange[y]].charAt(z);
}
}
}
}
String dec = "";
for(int x=0;x<row;x++){
for(int y=0;y<lenkey;y++){
dec = dec + grid[x][y];
}
}
return dec;
}

public static char RandomAlpha(){


Random r = new Random();
return ' ';
}
public static int[] arrangeKey(String key){
String[] keys = key.split("");
Arrays.sort(keys);
int[] num = new int [key.length()];
for(int x=0;x<keys.length;x++){
for(int y=0;y<key.length();y++){
if(keys[x].equals(key.charAt(y)+"")){
num[y] = x;
break;
}
}
}
return num;
}
}

DES Algorithm
Code :-
import java.util.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
import java.security.*;
import java.security.spec.*;
class DES {
public static void main(String[] args) throws IOException, NoSuchAlgorithmException,
InvalidKeyException,InvalidKeySpecException,NoSuchPaddingException,IllegalBlockSizeException,
BadPaddingException{
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\n");
System.out.print("ENTER THE STRING FOR ENCRYPTION:");
String message = sc.next();
byte[] myMessage = message.getBytes();
KeyGenerator Mygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = Mygenerator.generateKey();
Cipher myCipher = Cipher.getInstance("DES");
myCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
byte[] myEncryptedBytes = myCipher.doFinal(myMessage);
myCipher.init(Cipher.DECRYPT_MODE, myDesKey);
byte[] myDecryptedBytes = myCipher.doFinal(myEncryptedBytes);
String encrypteddata = new String(myEncryptedBytes);
String decrypteddata = new String(myDecryptedBytes);
System.out.println("ENCRYPTED MESSAGE IS:"+ encrypteddata);
System.out.println("DECRYPTED MESSAGE IS:"+ decrypteddata);
}
}

AES Algorithm
Code :-
import java.util.logging.*;
import java.util.*;
import java.io.*;
import java.security.Key;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
public class AES {
private byte[]keyValue;
public AES(String key)
{
keyValue = key.getBytes();

}
public static void main(String[] args)
{
try
{
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\n");
System.out.print("ENTER THE MESSAGE FOR ENCRYPTION:");
String message = sc.next();
///System.out.print("ENTER A KEY OF 128 BITS(16 CHARACTERS):");
///String key = sc.next();
///String stringKey = keytotring();
AES aes = new AES("abcdefghijklmnop");
String endata = aes.encrypt(message);
System.out.println("ENCRYPTED MESSAGE IS:"+endata);
String decdata = aes.decrypt(endata);
System.out.println("DECRYPTED MESSAGE IS:"+decdata);
}
catch(Exception ex)
{
Logger.getLogger(AES.class.getName()).log(Level.SEVERE,null,ex);

}
}
public String encrypt(String Data)throws Exception
{
Key key= generateKey();
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.ENCRYPT_MODE,key);
byte[] encVal = c.doFinal(Data.getBytes());
String encryptedValue = new sun.misc.BASE64Encoder().encode(encVal);
return encryptedValue;
}
public String decrypt(String encryptedData) throws Exception
{
Key key = generateKey();
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.DECRYPT_MODE,key);
byte[] decodedValue = new sun.misc.BASE64Decoder().decodeBuffer(encryptedData);
byte[] decVal = c.doFinal(decodedValue);
String dencryptedValue = new String(decVal);
return dencryptedValue;
}
private Key generateKey()throws Exception
{
Key key = new SecretKeySpec(keyValue,"AES");
return key;
}
}

RSA ALgo
Code :-
import java.util.*;
import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.*;
import java.util.Base64;
public class RSA {
private PrivateKey privateKey;
private PublicKey publicKey;
public RSA()
{
try{
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(1024);
KeyPair pair = generator.generateKeyPair();
privateKey = pair.getPrivate();
publicKey = pair.getPublic();
}catch(Exception ignored){
}
}
public String encrypt(String message)throws Exception
{
byte[] messageToBytes = message.getBytes();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(messageToBytes);
return encode(encryptedBytes);
}

private String encode(byte[] data)


{
return Base64.getEncoder().encodeToString(data);
}

public String decrypt(String encryptedMessage) throws Exception


{
byte[] encryptedBytes = decode(encryptedMessage);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedMessage = cipher.doFinal(encryptedBytes);
return new String(decryptedMessage,"UTF8");
}

private byte[] decode(String data)


{
return Base64.getDecoder().decode(data);
}

public static void main(String[] args)


{
RSA rsa = new RSA();
try{
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\n");
System.out.print("ENTER THE STRING FOR ENCRYPTION:");
String message = sc.next();
String encryptedMessage = rsa.encrypt(message);
String decryptedMessage = rsa.decrypt(encryptedMessage);
System.out.println("\nENCRYPTED MESSAGE IS:\n"+encryptedMessage);
System.out.println("\nDECRYPTED MESSAGE IS:"+decryptedMessage);
}catch(Exception ignored){}
}
}

Diffie hellman
Code :-
import java.util.*;
class DiffieHellman
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter modulo(p)");
int p=sc.nextInt();
System.out.println("Enter primitive root of "+p);
int g=sc.nextInt();
System.out.println("Choose 1st secret no(Alice)");
int a=sc.nextInt();
System.out.println("Choose 2nd secret no(BOB)");
int b=sc.nextInt();
int A= (int)Math.pow(g,a)%p;
int B = (int)Math.pow(g,b)%p;
int S_A= (int)Math.pow(B,a)%p;
int S_B = (int)Math.pow(A,b)%p;
if(S_A==S_B){
System.out.println("ALice and Bob can communicate with each other!!!");
System.out.println("They share a secret no = "+S_A);
}
else
{
System.out.println("ALice and Bob cannot communicate with each other!!!");
}
}
}

MD5
Code :-
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;
public class MD5{
public static String getMD5(String input)throws NoSuchAlgorithmException{
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger num = new BigInteger(1,messageDigest);
String hashText = num.toString(16);
while(hashText.length()<32);
{
hashText ="0"+hashText;
}
return hashText;
}
public static void main(String[] args)throws NoSuchAlgorithmException{
Scanner sc = new Scanner(System.in);
System.out.println("Enter string for MD5: ");
String s = sc.nextLine();
System.out.println("Your hash code generated by MD5 is : " + getMD5(s));
}
}

HMAC -SHAI
Code :-
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.Formatter;
import java.util.Scanner;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class hmacshal{
private static String toHexString(byte[] bytes){
Formatter formatter = new Formatter();
for(byte b : bytes){
formatter.format("%02x",b);
}
return formatter.toString();
}
public static String calculate(String data,String key)throws
SignatureException,NoSuchAlgorithmException,InvalidKeyException{
SecretKeySpec signingeKey = new SecretKeySpec(key.getBytes(),"HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingeKey);
return toHexString(mac.doFinal(data.getBytes()));
}
public static void main(String[] args)throws
SignatureException,NoSuchAlgorithmException,InvalidKeyException{
Scanner sc= new Scanner(System.in);
System.out.println("Enetr data to encrypte: ");
String data = sc.nextLine();
System.out.println("Eneter key to encryption : ");
String key = sc.nextLine();
String mdigest= calculate(data,key);
System.out.println("Message Digest / Hash Value after applying HMAC_SHAI : "+mdigest);
}
}

You might also like