0% found this document useful (0 votes)
36 views18 pages

Java Encryption Program Examples

The document contains an index and 6 programs related to encryption algorithms. Program 1 takes a string and XORs each character with 0. Program 2 ANDs and XORs each character with 127. Program 3 implements Caesar cipher, substitution cipher, and Hill cipher in Java. Program 4 implements the DES algorithm logic in Java. Program 5 and 6 implement the Blowfish and Rijndael algorithms respectively. The programs were submitted by a student to their professor for a lab assignment on encryption algorithms.

Uploaded by

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

Java Encryption Program Examples

The document contains an index and 6 programs related to encryption algorithms. Program 1 takes a string and XORs each character with 0. Program 2 ANDs and XORs each character with 127. Program 3 implements Caesar cipher, substitution cipher, and Hill cipher in Java. Program 4 implements the DES algorithm logic in Java. Program 5 and 6 implement the Blowfish and Rijndael algorithms respectively. The programs were submitted by a student to their professor for a lab assignment on encryption algorithms.

Uploaded by

Vishal Mishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

AJAY KUMAR GARG ENGINEERING COLLEGE

DEPARTMENT OF INFORMATION TECHNOLOGY

CNS Lab
(KIT
751A)

Submitted To Submitted By

Ms. Mrignainy Kansal Saiyam Mishra

2000270130144
INDEX

[Link]. Title Date Remarks

Write a C program that contains a string (char pointer) with


1
a value ‘Hello world’. The program should XOR each
character in this string with 0 and display the result.

Write a C program that contains a string (char pointer) with


a value ‘Hello world’. The program should AND or and
2 XOR each character in this string with 127 and display the
result.
Write a Java program to perform encryption and decryption
using the following algorithms
3
a. Ceaser cipher
b. Substitution cipher
c. Hill Cipher

4 Write a C/JAVA program to implement the DES algorithm


logic.

5 Write a C/JAVA program to implement the Blowfish


algorithm logic.

6 Write a C/JAVA program to implement the Rijndael


algorithm logic.
7

10
Program :1
AIM: Write a C program that contains a string (char pointer) with a value \Hello World’.
The program should XOR each character in this string with 0 and display the result.

PROGRAM:

#include<stdlib.h> main()
{
char str[]="Hello World"; char str1[11];
int i,len; len=strlen(str); for(i=0;i<len;i++)
{
str1[i]=str[i]^0; printf("%c",str1[i]);
}
printf("\n");
}

OUTPUT:
Hello World
Hello World
Program :2

AIM: Write a C program that contains a string (char pointer) with a value \Hello World’.
The program should AND or and XOR each character in this string with 127 and display the
result.

PROGRAM:

#include<stdio.h>
#include<stdlib.h>
void main()
{
char str[]="Hello World";
char str1[11];
char str2[11]=str[];
int i,len;
len = strlen(str);
for(i=0;i<len;i++)
{
str1[i] = str[i]&127;
printf("%c",str1[i]);
}
printf("\n");
for(i=0;i<len;i++)
{
str3[i] = str2[i]^127;
printf("%c",str3[i]);
}
printf("\n");
}

Output:
Hello
World
Hello
World
Hello
World
Program : 3

AIM: Write a Java program to perform encryption and decryption using the following
algorithms:

● Ceaser Cipher
● Substitution Cipher
● Hill Cipher

PROGRAM:

Ceaser Cipher

import [Link]; import [Link];


import [Link]; import [Link];
public class CeaserCipher {

static Scanner sc=new Scanner([Link]);


static BufferedReader br = new BufferedReader(new
InputStreamReader([Link])); public static void main(String[]
args) throws IOException {
// TODO code application logic here

[Link]("Enter any String: "); String str =


[Link]();
[Link]("\nEnter the Key: "); int key
= [Link]();

String encrypted = encrypt(str, key);


[Link]("\nEncrypted String is: " +encrypted);
String decrypted = decrypt(encrypted, key);
[Link]("\nDecrypted String is: "
+decrypted); [Link]("\n");
}
public static String encrypt(String str, int key)

{
String encrypted="";
For(int i=0; i<[Link](); i++)
{

int c=[Link](i);
if ([Link](c)) {
c = c + (key % 26);

if (c > 'Z')

c = c - 26;

else if ([Link](c)) { c = c + (key % 26);

if (c > 'z')

c = c - 26;

encrypted += (char) c;
}
return encrypted;
}

public static String decrypt(String str, int key)


{ String decrypted = ""; for(int i
= 0; i < [Link](); i++) { int c = [Link](i);
if ([Link](c)) {
c = c - (key % 26);
if (c < 'A')
c = c + 26;
}

else if ([Link](c)) { c = c - (key % 26);


if (c < 'a')

}
c = c + 26;

OUTPUT:
Enter any String: Hello World
Enter the Key: 5
Encrypted String is: MjqqtBtwqi
Decrypted String is: Hello
World
Substitution Cipher

PROGRAM:

import [Link].*; import [Link].*;


public class SubstitutionCipher {
static Scanner sc = new Scanner([Link]);
static BufferedReader br = new BufferedReader(new
InputStreamReader([Link])); public static void main(String[]
args) throws IOException {
/ TODO code application logic here String a
= "abcdefghijklmnopqrstuvwxyz"; String b =
"zyxwvutsrqponmlkjihgfedcba";
[Link]("Enter any string: "); String str =
[Link]();
String decrypt = ""; char c;
for(int i=0;i<[Link]();i++)
{
c = [Link](i); int j = [Link](c);
decrypt = decrypt+[Link](j);
}
[Link]("The encrypted data is: " +decrypt);
}
}

OUTPUT:
Enter any string: aceho
The encrypted data is: zxvsl
Hill Cipher

PROGRAM:

import [Link].*;
import [Link].*;
import [Link].*;
public class HillCipher {
static float[][] decrypt = new float[3][1];
static float[][] a = new float[3][3];
static float[][] b = new float[3][3];
static float[][] mes = new float[3][1];
static float[][] res = new float[3][1];
static BufferedReader br = new BufferedReader(new
InputStreamReader([Link]));
static Scanner sc = new Scanner([Link]);
public static void main(String[] args) throws IOException {
/ TODO code application logic here
getkeymes(); for(int i=0;i<3;i++)
for(int j=0;j<1;j++)
for(int k=0;k<3;k++) {
res[i][j]=res[i][j]+a[i] [k]*mes[k][j];
}
[Link]("\nEncrypted string is : ");
for(int i=0;i<3;i++)
{ [Link]((char)(res[i] [0]%26+97));
res[i][0]=res[i][0];
}
inverse();

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

decrypt[i][j] = decrypt[i][j]+b[i][k]*res[k][j]; }
[Link]("\nDecrypted string is : ");
for(int i=0;i<3;i++){
[Link]((char)(decrypt[i] [0]% 26+97));
}

[Link]("\n");
}
public static void getkeymes() throws IOException {
[Link]("Enter 3x3 matrix for key (It should be
inversible): ");
for(int i=0;i<3;i++) for(int j=0;j<3;j++) a[i][j]= [Link]();
[Link]("\nEnter a 3 letter string: ");
String msg = [Link]();
for(int i=0;i<3;i++)
mes[i][0] = [Link](i)-97;
}
public static void inverse()
{ floatp,q;
float[][] c = a; for(int i=0;i<3;i++) for(int j=0;j<3;j++) {
//a[i][j]=[Link]();
if(i==j) b[i][j]=1;
else b[i][j]=0;
}
for(int k=0;k<3;k++)
{ for(int i=0;i<3;i++) {
p = c[i][k];
q = c[k][k];
for(int j=0;j<3;j++) { if(i!=k)
{
c[i][j] = c[i][j]*q-p*c[k][j];
b[i][j] = b[i][j]*q-p*b[k][j]; }}}} for(int i=0;i<3;i+
+) for(int j=0;j<3;j++)

{ b[i][j] = b[i][j]/c[i][i]; }
[Link](""); [Link]("\nInverse Matrix is :
"); for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) [Link](b[i][j] + " ");
[Link]("\n"); }
} }
OUTPUT:
Enter a 3 letter string: hai
Encrypted string is :fdx
Inverse Matrix is :
0.083333336 0.41666666 -0.33333334
-0.41666666 -0.083333336 0.6666667
0.5833333 -0.083333336 -0.33333334
Decrypted string is: hai
Program : 4

AIM: Write a Java program to implement the DES algorithm logic.

PROGRAM:

import [Link].*;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].BASE64Decoder;
import [Link].BASE64Encoder;
public class DES {
private static final String UNICODE_FORMAT = "UTF8";
public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
privateKeySpecmyKeySpec;
privateSecretKeyFactorymySecretKeyFactory;
private Cipher cipher;
byte[] keyAsBytes;
private String myEncryptionKey;
private String myEncryptionScheme;
SecretKey key;
static BufferedReader br = new BufferedReader(new
InputStreamReader([Link])); public DES() throws Exception {
/ TODO code application logic here myEncryptionKey

= "ThisIsSecretEncryptionKey"; myEncryptionScheme =
DESEDE_ENCRYPTION_SCHEME; keyAsBytes =
[Link](UNICODE_FORMAT); myKeySpec
= new DESedeKeySpec(keyAsBytes);
mySecretKeyFactory =
[Link](myEncryptionScheme); cipher =
[Link](myEncryptionScheme);
key = [Link](myKeySpec);
}
public String encrypt(String unencryptedString)

{ String encryptedString = null;

try {
[Link](Cipher.ENCRYPT_MODE, key);
byte[] plainText = [Link](UNICODE_FORMAT);
byte[] encryptedText = [Link](plainText);
BASE64Encoder base64encoder = new BASE64Encoder(); encryptedString
= [Link](encryptedText); } catch (Exception )
{ [Link](); } returnencryptedString; }
public String decrypt(String encryptedString)
{ String decryptedText=null;
try {
[Link](Cipher.DECRYPT_MODE, key);
BASE64Decoder base64decoder = new BASE64Decoder(); byte[]
encryptedText = [Link](encryptedString);
byte[] plainText = [Link](encryptedText);
decryptedText= bytes2String(plainText); }
catch (Exception e)
{
[Link]();
} returndecryptedText; }
private static String bytes2String(byte[] bytes)
{
StringBufferstringBuffer = new StringBuffer();
for (int i = 0; i <[Link]; i++) {
[Link]((char) bytes[i]);
} [Link]();
}
public static void main(String args []) throws Exception

{ [Link]("Enter the string: ");


DES myEncryptor= new DES();
String stringToEncrypt = [Link]();
String encrypted = [Link](stringToEncrypt);
String decrypted = [Link](encrypted);
[Link]("\nString To Encrypt: " +stringToEncrypt);
[Link]("\nEncrypted Value : "+encrypted);
[Link]("\nDecrypted Value : " +decrypted);
[Link]("");

OUTPUT:
Enter the string: Welcome
String To Encrypt: Welcome
Encrypted Value : BPQMwc0wKvg=
Decrypted Value : Welcome
Program : 5

AIM: Write a C/JAVA program to implement the Rijndael algorithm logic.


PROGRAM:

import [Link].*; import [Link].*; import


[Link].*; import [Link].*;
public class AES {
public static String asHex (byte buf[]) { StringBuffer
strbuf = new StringBuffer([Link] * 2); int i; for (i=
0; i < [Link]; i++) { if (((int) buf[i] & 0xff)
<0x10)[Link]("0");
[Link]([Link]((int) buf[i] & 0xff, 16)); }
return [Link](); }
public static void main(String[] args) throws Exception
{ String message="AES still rocks!!";

// Get the KeyGenerator


KeyGenerator kgen = [Link]("AES");
[Link](128); // 192 and 256 bits may not be available
// Generate the secret key specs. SecretKey skey =
[Link](); byte[] raw = [Link]();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// Instantiate the cipher
Cipher cipher = [Link]("AES");
[Link](Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = [Link](([Link] == 0 ?
message : args[0]).getBytes());
[Link]("encrypted string: " +
asHex(encrypted)); [Link](Cipher.DECRYPT_MODE,
skeySpec); byte[] original = [Link](encrypted);
String originalString = new String(original);
[Link]("Original string: " + originalString + " " +
asHex(original));

}
OUTPUT:

Input your message: Hello


KGRCET Encrypted text:
3ooo&&(*&*4r4
Decrypted text: Hello
KGRCET

Common questions

Powered by AI

The Java program decrypts the Caesar cipher by reversing the encryption process. It subtracts the shift key value from each character's ASCII value. If the resulting ASCII value goes below 'A' for uppercase or below 'a' for lowercase, it wraps around by adding 26. This ensures that the characters stay within their respective cases in the ASCII table .

In the C program, XOR'ing each character of the string "Hello World" with zero results in no change to the string. XOR with zero means the original value remains unchanged. Thus, the output remains 'Hello World' .

The Java program using a Substitution Cipher substitutes each character in the input string with a corresponding character from a predefined key alphabet ('zyxwvutsrqponmlkjihgfedcba'). This effectively reverses the position of letters in the input according to the key mappings, creating an encrypted message which can likewise be decrypted if the key is known .

The Hill Cipher Java program requires inputs to match the specific size of the key matrix, usually 3x1, as it performs matrix multiplication for encryption. This demand for input size becomes essential because non-conforming input would lead to erroneous computations or an inability to apply the matrix transformation, severely impacting the encrypt-ability of the text .

Using a fixed encryption key in a Java DES implementation poses significant security risks since it becomes predictable and vulnerable to brute-force attacks. Security can be compromised because once the key is intercepted or deduced, all encrypted communications can be decrypted without authorization. Key rotation and secure key storage are necessary to mitigate such vulnerabilities .

The Rijndael algorithm, implemented as AES in Java, involves generating a secure secret key and using this key to initialize a cipher for encryption and decryption. The algorithm applies multiple rounds of permutations and substitutions on the plaintext to produce ciphertext, ensuring high security due to its complexity and use in secure data transmissions .

The XOR operation is computationally efficient as it involves simple bitwise manipulation, thus can be executed quickly and with low resource utilization. However, XOR alone has limited cryptographic strength due to its predictability (e.g., XOR'ing with the same key reverts to the original), making it insufficient for secure encryption without additional cryptographic techniques .

In Hill cipher, encryption involves multiplying the plaintext vector by a key matrix. For decryption, the key matrix must be invertible. The inverse matrix is used to reverse the encryption process, by multiplying the encrypted message vector with it. Without a correct inverse, the original message cannot be recovered .

In the Java implementation of the DES algorithm, the key is crucial for both encryption and decryption. It initializes the cipher object to either Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE. The key ensures that only someone with the correct key can successfully decrypt the message back to its original form after encryption .

When applying an AND operation with 127, each character's ASCII value is masked, affecting only the 8th bit, and generally leaving the lower bits unchanged. With XOR operation, each character's bits are toggled based on the 127 value, altering the original ASCII significantly. The AND operation might result in lower ASCII output whereas XOR can randomize the characters more substantially .

You might also like