0% found this document useful (0 votes)
4 views

Crypto

The document contains Java implementations of various encryption algorithms, including Caesar Cipher, Playfair Cipher, Vigenere Cipher, AES, DES, Hill Cipher, RSA, and Diffie-Hellman. Each algorithm is presented with its respective code, demonstrating how to encrypt and decrypt messages using different techniques. The document serves as a comprehensive guide for understanding and implementing these cryptographic methods.

Uploaded by

Sujjal Minhas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Crypto

The document contains Java implementations of various encryption algorithms, including Caesar Cipher, Playfair Cipher, Vigenere Cipher, AES, DES, Hill Cipher, RSA, and Diffie-Hellman. Each algorithm is presented with its respective code, demonstrating how to encrypt and decrypt messages using different techniques. The document serves as a comprehensive guide for understanding and implementing these cryptographic methods.

Uploaded by

Sujjal Minhas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

CEASER CIPHER

import java.util.Scanner;

class one {

public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";

public static String encryptData(String inputStr, int shiftKey) {

inputStr = inputStr.toLowerCase();

String encryptStr = "";

for (int i = 0; i < inputStr.length(); i++) {

int pos = ALPHABET.indexOf(inputStr.charAt(i));

int encryptPos = (shiftKey + pos) % 26;

char encryptChar = ALPHABET.charAt(encryptPos);

encryptStr += encryptChar;

return encryptStr;

public static String decryptData(String inputStr, int shiftKey) {

inputStr = inputStr.toLowerCase();

String decryptStr = "";

for (int i = 0; i < inputStr.length(); i++) {

int pos = ALPHABET.indexOf(inputStr.charAt(i));

int decryptPos = (pos - shiftKey) % 26;

if (decryptPos < 0) {

decryptPos = ALPHABET.length() + decryptPos;

char decryptChar = ALPHABET.charAt(decryptPos);


decryptStr += decryptChar;

return decryptStr;

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter a string for encryption using Caesar Cipher:");

String inputStr = sc.nextLine();

System.out.println("Enter the value by which each character in theplaintext message gets

shifted:");

int shiftKey = Integer.valueOf(sc.nextLine());

System.out.println( encryptData(inputStr,

shiftKey));System.out.println(

decryptData(encryptData(inputStr, shiftKey), shiftKey));

sc.close();

PLAYFAIR

import java.util.Scanner;

public class two {

static int SIZE = 30;

static void toLowerCase(char plain[], int ps) {

for (int i = 0; i < ps; i++) {

if (plain[i] > 64 && plain[i] < 91)


plain[i] += 32;

static int removeSpaces(char[] plain, int ps) {

int count = 0;

for (int i = 0; i < ps; i++) {

if (plain[i] != '\u0000') {

plain[count++] = plain[i];

return count;

static void generateKeyTable(char key[], int ks, char keyT[][]) {

int[] dicty = new int[26];

for (int i = 0; i < ks; i++) {

if (key[i] != 'j') {

dicty[key[i] - 97] = 2;

dicty['j' - 97] = 1;

int i = 0, j = 0;

for (int k = 0; k < ks; k++) {


if (dicty[key[k] - 97] == 2) {

dicty[key[k] - 97] -= 1;

keyT[i][j] = key[k];

j++;

if (j == 5) {

i++;

j = 0;

for (int k = 0; k < 26; k++) {

if (dicty[k] == 0) {

keyT[i][j] = (char) (k + 97);

j++;

if (j == 5) {

i++;

j = 0;

static void search(char keyT[][], char a, char b, int arr[]) {

if (a == 'j') a = 'i';
if (b == 'j') b = 'i';

for (int i = 0; i < 5; i++) {

for (int j = 0; j < 5; j++) {

if (keyT[i][j] == a) {

arr[0] = i;

arr[1] = j;

} else if (keyT[i][j] == b) {

arr[2] = i;

arr[3] = j;

static int mod5(int a) {

return (a % 5);

static int prepare(char str[], int ptrs) {

for (int i = 0; i < ptrs - 1; i += 2) {

if (str[i] == str[i + 1]) {

for (int j = ptrs; j > i + 1; j--) {

str[j] = str[j - 1];

}
str[i + 1] = 'x';

ptrs++;

if (ptrs % 2 != 0) {

str[ptrs++] = 'x';

return ptrs;

static void encrypt(char str[], char keyT[][], int ps) {

int[] a = new int[4];

for (int i = 0; i < ps; i += 2) {

search(keyT, str[i], str[i + 1], a);

if (a[0] == a[2]) {

str[i] = keyT[a[0]][mod5(a[1] + 1)];

str[i + 1] = keyT[a[0]][mod5(a[3] + 1)];

} else if (a[1] == a[3]) {

str[i] = keyT[mod5(a[0] + 1)][a[1]];

str[i + 1] = keyT[mod5(a[2] + 1)][a[1]];

} else {

str[i] = keyT[a[0]][a[3]];

str[i + 1] = keyT[a[2]][a[1]];

}
}

static void encryptByPlayfairCipher(char str[], char key[]) {

int ps, ks;

char[][] keyT = new char[5][5];

ks = key.length;

ks = removeSpaces(key, ks);

toLowerCase(key, ks);

ps = str.length;

toLowerCase(str, ps);

ps = removeSpaces(str, ps);

ps = prepare(str, ps);

generateKeyTable(key, ks, keyT);

encrypt(str, keyT, ps);

static void strcpy(char[] arr, String s) {

for (int i = 0; i < s.length(); i++) {

arr[i] = s.charAt(i);

public static void main(String[] args) {

System.out.println("SUJJAL MINHAS");

System.out.println("22BCB0092");
Scanner scanner = new Scanner(System.in);

String input1 = scanner.nextLine();

String input2 = scanner.nextLine();

char[] str = new char[SIZE];

char[] key = new char[SIZE];

strcpy(str, input1);

strcpy(key, input2);

int ps = input1.length();

int ks = input2.length();

char[] originalStr = new char[SIZE];

strcpy(originalStr, input1);

int modifiedLength = prepare(originalStr, ps);

encryptByPlayfairCipher(str, key);

String result = String.valueOf(str).toUpperCase();

System.out.println(result);

String modifiedString = String.valueOf(originalStr, 0, modifiedLength);

if (modifiedString.charAt(modifiedString.length() - 1) != 'x') {

modifiedString += "x";

System.out.println(modifiedString.toLowerCase());

}
}

Vigenere

import java.util.*;

public class three {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

String pt = sc.nextLine().toUpperCase();

String keyword = sc.nextLine().toUpperCase();

String encryptedText = encrypt(pt, keyword);

System.out.println(encryptedText);

System.out.println(pt);

private static String encrypt(String plaintext, String keyword) {

StringBuilder cipher = new StringBuilder();

for (int i = 0, j = 0; i < plaintext.length(); i++) {

char currentChar = plaintext.charAt(i);

if (Character.isAlphabetic(currentChar)) {

int shift = keyword.charAt(j % keyword.length()) - 'A';

char encryptedChar = (char) ((currentChar + shift - 'A') % 26 + 'A');

cipher.append(encryptedChar);

j++;

} else {

cipher.append(currentChar);

}}
return cipher.toString();

AES

import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import javax.crypto.spec.SecretKeySpec;

import java.util.Base64;

import java.util.Scanner;

public class bcb92 {

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

Scanner scanner = new Scanner(System.in);

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

String message = scanner.nextLine();

System.out.print("Enter Key (16 characters): ");

String keyInput = scanner.nextLine();

byte[] keyBytes = keyInput.getBytes();

SecretKey secretKey = new SecretKeySpec(keyBytes, "AES");

Cipher cipher = Cipher.getInstance("AES");

byte[][] roundKeys = generateRoundKeys(secretKey.getEncoded());

for (int i = 0; i < roundKeys.length; i++) {

System.out.println("RoundKey" + i + ": " +

Base64.getEncoder().encodeToString(roundKeys[i]));
}

cipher.init(Cipher.ENCRYPT_MODE, secretKey);

byte[] encryptedBytes = cipher.doFinal(message.getBytes());

String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);

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

cipher.init(Cipher.DECRYPT_MODE, secretKey);

byte[] decryptedBytes =

cipher.doFinal(Base64.getDecoder().decode(encryptedText));

String decryptedText = new String(decryptedBytes);

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

private static byte[][] generateRoundKeys(byte[] key) {

byte[][] roundKeys = new byte[11][16];

roundKeys[0] = key;

for (int i = 1; i < 11; i++) {

roundKeys[i] = new byte[16];

for (int j = 0; j < 16; j++) {

roundKeys[i][j] = (byte) (roundKeys[i - 1][j] ^ (j * i));

return roundKeys;

}
DES

import java.util.Base64;

import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.DESKeySpec;

import javax.crypto.Cipher;

import javax.crypto.SecretKey;

import java.util.Scanner;

public class des {

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

Scanner scanner = new Scanner(System.in);

System.out.println("SUJJAL MINHAS");

System.out.println("22BCB0092");

System.out.println("Enter a secret key (8 characters): ");

String key = scanner.nextLine();

System.out.print("Enter the plaintext: ");

String plaintext = scanner.nextLine();

DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

Cipher cipher = Cipher.getInstance("DES");

cipher.init(Cipher.ENCRYPT_MODE, secretKey);

byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes());

String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);

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


cipher.init(Cipher.DECRYPT_MODE, secretKey);

byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));

String decryptedText = new String(decryptedBytes);

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

scanner.close();

HILL CIPHER

import java.util.Scanner;

public class hill {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

String plaintext = sc.nextLine().toLowerCase();

String key = sc.nextLine().toLowerCase();

int keySize = sc.nextInt();

sc.close();

plaintext = formatPlaintext(plaintext, keySize);

int[][] keyMatrix = generateKeyMatrix(key, keySize);

StringBuilder encryptedText = new StringBuilder();

for (int i = 0; i < plaintext.length(); i += keySize) {


int[] messageVector = new int[keySize];

for (int j = 0; j < keySize; j++) {

messageVector[j] = plaintext.charAt(i + j) - 'a';

int[] cipherVector = multiplyKeyAndMessage(keyMatrix, messageVector, keySize);

for (int val : cipherVector) {

encryptedText.append((char) (val + 'a'));

System.out.println(encryptedText.toString());

System.out.println(plaintext);

static String formatPlaintext(String plaintext, int keySize) {

if (plaintext.length() % keySize != 0) {

int padding = keySize - (plaintext.length() % keySize);

plaintext += "x".repeat(padding);

return plaintext;

static int[][] generateKeyMatrix(String key, int keySize) {

int[][] matrix = new int[keySize][keySize];

int k = 0;
for (int i = 0; i < keySize; i++) {

for (int j = 0; j < keySize; j++) {

matrix[i][j] = key.charAt(k++) - 'a';

return matrix;

static int[] multiplyKeyAndMessage(int[][] keyMatrix, int[] messageVector, int keySize) {

int[] result = new int[keySize];

for (int i = 0; i < keySize; i++) {

for (int j = 0; j < keySize; j++) {

result[i] += keyMatrix[i][j] * messageVector[j];

result[i] = (result[i] % 26 + 26) % 26;

return result;

RSA

import java.math.BigInteger;

import java.util.Scanner;

public class rsa {


public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int p = scanner.nextInt();

int q = scanner.nextInt();

scanner.nextLine();

String message = scanner.nextLine();

int n = p * q;

int phi = (p - 1) * (q - 1);

int e = findE(phi);

int d = findD(e, phi);

System.out.println(e);

System.out.println(d);

String encrypted = encrypt(message, e, n);

System.out.println(encrypted);

String decrypted = decrypt(encrypted, d, n);

System.out.println(decrypted);

private static int findE(int phi) {

for (int e = 2; e < phi; e++) {

if (gcd(e, phi) == 1) {
return e;

return 2;

private static int findD(int e, int phi) {

int d = 1;

while ((d * e) % phi != 1) {

d++;

return d;

private static int gcd(int a, int b) {

if (b == 0) return a;

return gcd(b, a % b);

private static String encrypt(String message, int e, int n) {

StringBuilder encrypted = new StringBuilder();

for (char ch : message.toCharArray()) {

BigInteger charValue = BigInteger.valueOf((int) ch);

BigInteger encryptedChar = charValue.modPow(BigInteger.valueOf(e),

BigInteger.valueOf(n));
encrypted.append((char) encryptedChar.intValue()); // Convert back to char

return encrypted.toString();

private static String decrypt(String encrypted, int d, int n) {

StringBuilder decrypted = new StringBuilder();

for (char ch : encrypted.toCharArray()) {

BigInteger charValue = BigInteger.valueOf((int) ch);

BigInteger decryptedChar = charValue.modPow(BigInteger.valueOf(d),

BigInteger.valueOf(n));

decrypted.append((char) decryptedChar.intValue());

return decrypted.toString();

DIFFIE HELLMAN

import java.math.BigInteger;

import java.util.Scanner;

public class diffie{

public static void main (String[] args){

System.out.println("SUJJAL MINHAS");

System.out.println("22BCB0092");

Scanner scanner = new Scanner(System.in);

int prime = scanner.nextInt();

int generator= scanner.nextInt();


int privateA = scanner.nextInt();

int privateB = scanner.nextInt();

int publicA = modPow(generator, privateA, prime);

int publicB = modPow(generator, privateB, prime);

int secretA = modPow(publicB, privateA, prime);

int secretB = modPow(publicA, privateB, prime);

System.out.println(publicA);

System.out.println(publicB);

System.out.println(secretA);

System.out.println(secretB);

if(secretA == secretB){

System.out.println("Both 'A' and 'B'secret keys are matched. Message shared

securely");

}else{

System.out.println("Both 'A' and 'B'secret keys are not matched.");

public static int modPow(int base, int exp,int mod){

return BigInteger.valueOf(base).modPow(BigInteger.valueOf(exp),
BigInteger.valueOf(mod)).intValue();

ELGAMAL

import java.math.BigInteger;

import java.security.SecureRandom;

import java.util.Scanner;

public class elgamal {

static SecureRandom random = new SecureRandom();

static BigInteger power(BigInteger base, BigInteger exp, BigInteger mod) {

return base.modPow(exp, mod);

static BigInteger generatePrime(int bitLength) {

return BigInteger.probablePrime(bitLength, random);

static BigInteger generateKey(BigInteger q) {

BigInteger key;

do {

key = new BigInteger(q.bitLength(), random);

} while (key.compareTo(BigInteger.TWO) < 0 || key.compareTo(q) >= 0);

return key;
}

static BigInteger[] encrypt(String message, BigInteger q, BigInteger h, BigInteger g) {

BigInteger k = generateKey(q);

BigInteger s = power(h, k, q);

BigInteger p = power(g, k, q);

BigInteger[] encryptedMessage = new BigInteger[message.length() + 1];

encryptedMessage[0] = p;

for (int i = 0; i < message.length(); i++) {

encryptedMessage[i + 1] = s.multiply(BigInteger.valueOf((int)

message.charAt(i))).mod(q);

return encryptedMessage;

static String decrypt(BigInteger[] encryptedMessage, BigInteger key, BigInteger q) {

BigInteger p = encryptedMessage[0];

BigInteger s = power(p, key, q);

BigInteger sInverse = s.modInverse(q);

StringBuilder decryptedMessage = new StringBuilder();

for (int i = 1; i < encryptedMessage.length; i++) {


decryptedMessage.append((char)

encryptedMessage[i].multiply(sInverse).mod(q).intValue());

return decryptedMessage.toString();

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

String message = scanner.nextLine();

BigInteger q = generatePrime(64);

BigInteger g = new BigInteger(q.bitLength(), random).mod(q);

BigInteger key = generateKey(q);

BigInteger h = power(g, key, q);

System.out.println("Generated Prime (q): " + q);

System.out.println("Generator (g): " + g);

System.out.println("Public Key (h): " + h);

BigInteger[] encryptedMessage = encrypt(message, q, h, g);

System.out.println("Encrypted Message: ");

for (BigInteger val : encryptedMessage) {

System.out.print(val + " ");


}

System.out.println();

String decryptedMessage = decrypt(encryptedMessage, key, q);

System.out.println("Decrypted Message: " + decryptedMessage);

ELLIPTIC CURVE

import java.math.BigInteger;

import java.util.Scanner;

public class ECCEncryption {

static int a, b, p;

static int[] G = new int[2];

static int[] Pm = new int[2];

static int[] Pb = new int[2];

static int k;

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter a, b, p: ");

a = sc.nextInt();

b = sc.nextInt();

p = sc.nextInt();
System.out.print("Enter Generator point G (x y): ");

G[0] = sc.nextInt();

G[1] = sc.nextInt();

System.out.print("Enter Plaintext message point Pm (x y): ");

Pm[0] = sc.nextInt();

Pm[1] = sc.nextInt();

System.out.print("Enter Bob's public key Pb (x y): ");

Pb[0] = sc.nextInt();

Pb[1] = sc.nextInt();

System.out.print("Enter random integer k: ");

k = sc.nextInt();

sc.close();

int[] kG = scalarMultiply(k, G); // Compute k * G (C1)

int[] kPb = scalarMultiply(k, Pb); // Compute k * Pb

int[] C2 = pointAddition(Pm, kPb); // Compute C2 = Pm + kPb

System.out.println("Ciphertext:");

System.out.println("C1 = (" + kG[0] + ", " + kG[1] + ")");

System.out.println("C2 = (" + C2[0] + ", " + C2[1] + ")");

static int[] pointAddition(int[] P, int[] Q) {

if (P[0] == Q[0] && P[1] == Q[1]) return pointDoubling(P);

int lambda = modDivide(Q[1] - P[1], Q[0] - P[0], p);

int xR = (lambda * lambda - P[0] - Q[0]) % p;

int yR = (lambda * (P[0] - xR) - P[1]) % p;


return new int[]{(xR + p) % p, (yR + p) % p};

static int[] pointDoubling(int[] P) {

int lambda = modDivide(3 * P[0] * P[0] + a, 2 * P[1], p);

int xR = (lambda * lambda - 2 * P[0]) % p;

int yR = (lambda * (P[0] - xR) - P[1]) % p;

return new int[]{(xR + p) % p, (yR + p) % p};

static int[] scalarMultiply(int k, int[] P) {

int[] R = {0, 0};

int[] Q = P;

while (k > 0) {

if ((k & 1) == 1) R = (R[0] == 0 && R[1] == 0) ? Q : pointAddition(R, Q);

Q = pointDoubling(Q);

k >>= 1;

return R;

static int modDivide(int a, int b, int p) {

a = (a % p + p) % p;

b = (b % p + p) % p;

int inv = BigInteger.valueOf(b).modInverse(BigInteger.valueOf(p)).intValue();

return (a * inv) % p;

}
CHINESE REMAINDER THEOREM

import java.util.*;

public class ChineseRemainderTheorem {

private static int modInverse(int a, int m) {

int m0 = m, t, q;

int x0 = 0, x1 = 1;

if (m == 1) return 0;

while (a > 1) {

q = a / m;

t = m;

m = a % m;

a = t;

t = x0;

x0 = x1 - q * x0;

x1 = t;

if (x1 < 0) x1 += m0;

return x1;

}
public static int findX(int[] num, int[] rem, int k) {

int prod = 1;

for (int i = 0; i < k; i++) {

prod *= num[i];

int result = 0;

for (int i = 0; i < k; i++) {

int pp = prod / num[i];

result += rem[i] * modInverse(pp, num[i]) * pp;

return (result % prod + prod) % prod;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

List<Integer> num = new ArrayList<>();

List<Integer> rem = new ArrayList<>();

while (scanner.hasNextInt()) {

int r = scanner.nextInt();

int n = scanner.nextInt();

num.add(n);

rem.add(r);
}

scanner.close();

int[] numArray = num.stream().mapToInt(i -> i).toArray();

int[] remArray = rem.stream().mapToInt(i -> i).toArray();

int x = findX(numArray, remArray, num.size());

System.out.println(x);

EXTENDED EUCLIDEAN ALGO

import java.util.*;

public class ExtendedEuclideanAlgorithm {

public static int modInverse(int a, int m) {

int m0 = m, t, q;

int x0 = 0, x1 = 1;

if (m == 1) return 0;

while (a > 1) {

q = a / m;

t = m;

m = a % m;

a = t;
t = x0;

x0 = x1 - q * x0;

x1 = t;

if (x1 < 0) x1 += m0;

return x1;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

int a = scanner.nextInt();

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

int m = scanner.nextInt();

scanner.close();

int inverse = modInverse(a, m);

System.out.println("Modular Multiplicative Inverse: " + inverse);

}
RC4

import java.util.Scanner;

public class rc4 {

private byte[] S = new byte[256];

public void initializeKey(byte[] key) {

int keyLength = key.length;

byte[] T = new byte[256];

for (int i = 0; i < 256; i++) {

S[i] = (byte) i;

T[i] = key[i % keyLength];

int j = 0;

for (int i = 0; i < 256; i++) {

j = (j + S[i] + (T[i] & 0xFF)) & 0xFF;

swap(S, i, j);

private void swap(byte[] array, int i, int j) {

byte temp = array[i];

array[i] = array[j];
array[j] = temp;

public byte[] generateKeystream(int length) {

byte[] keystream = new byte[length];

int i = 0, j = 0;

for (int k = 0; k < length; k++) {

i = (i + 1) & 0xFF;

j = (j + (S[i] & 0xFF)) & 0xFF;

swap(S, i, j);

keystream[k] = (byte) ((S[(S[i] + S[j]) & 0xFF]) & 0x07); // Ensure 3-bit values

return keystream;

public byte[] encryptDecrypt(byte[] input, byte[] keystream) {

byte[] output = new byte[input.length];

for (int i = 0; i < input.length; i++) {

output[i] = (byte) ((input[i] ^ keystream[i]) & 0x07); // Ensure 3-bit result

return output;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


System.out.println("Tanisha Tripathy-22BCB0017");

String line = scanner.nextLine().trim();

String[] plainTextInput = line.isEmpty() ? new String[0] : line.split(" ");

byte[] plainText = new byte[plainTextInput.length];

for (int i = 0; i < plainTextInput.length; i++) {

plainText[i] = (byte) (Integer.parseInt(plainTextInput[i]) & 0x07);

line = scanner.nextLine().trim();

String[] keyInput = line.isEmpty() ? new String[0] : line.split(" ");

byte[] key = new byte[keyInput.length];

for (int i = 0; i < keyInput.length; i++) {

key[i] = (byte) (Integer.parseInt(keyInput[i]) & 0x07);

if (scanner.hasNextInt()) {

int numBits = scanner.nextInt();

scanner.nextLine();

rc4 rc4 = new rc4();

rc4.initializeKey(key);

byte[] keystream = rc4.generateKeystream(plainText.length);

byte[] encryptedText = rc4.encryptDecrypt(plainText, keystream);

byte[] decryptedText = rc4.encryptDecrypt(encryptedText, keystream);

System.out.println(to3BitBinaryString(plainText));
System.out.println(to3BitBinaryString(key));

System.out.println(toDecimalString(keystream));

System.out.println(to3BitBinaryString(encryptedText));

System.out.println(to3BitBinaryString(decryptedText));

scanner.close();

private static String to3BitBinaryString(byte[] array) {

StringBuilder binaryString = new StringBuilder();

for (byte b : array) {

binaryString.append(String.format("%03d", Integer.parseInt(Integer.toBinaryString(b & 0x07))));

return binaryString.toString();

private static String toDecimalString(byte[] array) {

StringBuilder decimalString = new StringBuilder();

for (byte b : array) {

decimalString.append((b & 0x07)).append(" ");

return decimalString.toString().trim();

}
FERMETS THEOREM

import java.util.Scanner;

public class FermatModularInverse {

public static int powerMod(int base, int exp, int mod) {

int result = 1;

base = base %mod;

while (exp > 0) {

if ((exp & 1) == 1) // Ifexp is odd, multiply base with result

result = (result * base) % mod;

exp =exp>>1; //Divide exp by 2

base = (base * base) % mod;// Square thebase

return result;

public static int modInverse(int a, int m) {

return powerMod(a, m- 2, m);

public static void main(String[] args) {

Scanner sc = newScanner(System.in);

System.out.println("Enter number and prime modulus:");

int a = sc.nextInt();

int m= sc.nextInt();

System.out.println("Modular Inverse of " + a + " mod" + m + " is: " + modInverse(a, m));

You might also like