0% found this document useful (0 votes)
5 views8 pages

information security

The document contains multiple Java programs demonstrating various string and cryptographic operations. It includes bitwise operations on strings, rail fence cipher for string rearrangement, MD5 hashing, DES and RSA encryption/decryption, Diffie-Hellman key exchange, and AES encryption. Each program is executed with sample inputs, showcasing their respective functionalities.

Uploaded by

Mahindra Kumar
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)
5 views8 pages

information security

The document contains multiple Java programs demonstrating various string and cryptographic operations. It includes bitwise operations on strings, rail fence cipher for string rearrangement, MD5 hashing, DES and RSA encryption/decryption, Diffie-Hellman key exchange, and AES encryption. Each program is executed with sample inputs, showcasing their respective functionalities.

Uploaded by

Mahindra Kumar
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/ 8

public class BitwiseStringOperations {

public static void main(String[] args) {


String str = "Adarsh kumar";
System.out.println("Original String: " + str);

StringBuilder andResult = new StringBuilder();


StringBuilder orResult = new StringBuilder();
StringBuilder xorResult = new StringBuilder();

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


andResult.append((char) (ch & 127));
orResult.append((char) (ch | 127));
xorResult.append((char) (ch ^ 127));
}

System.out.println("AND result with 127: " + andResult.toString());


System.out.println("OR result with 127: " + orResult.toString());
System.out.println("XOR result with 127: " + xorResult.toString());
}
}

PS C:\Users\ADARSH\Desktop\cf> & 'C:\Program Files\Java\jdk-21\bin\java.exe'


'-XX:+ShowCodeDetailsInExceptionMessages' '-cp'

'C:\Users\ADARSH\AppData\Roaming\Code\User\workspaceStorage\d8a4d4e5d6a30892978430a025a0
bf4
0\redhat.java\jdt_ws\cf_fa686e5a\bin' 'BitwiseStringOperations'

Original String: Adarsh kumar


AND result with 127: Adarsh kumar
OR result with 127: A•arsh••••••
XOR result with 127: -
import java.util.*;

public class Main {


public static void main(String[] args) {
// Input string
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();

List<String> v = new ArrayList<>();


v.add(""); // Initialize first rail
v.add(""); // Initialize second rail

// Distribute characters to rails


for (int i = 0; i < str.length(); i++) {
v.set(i % 2, v.get(i % 2) + str.charAt(i));
}

// Print combined rails


System.out.println("Combined Rails:");
for (String rail : v) {
System.out.print(rail);
}
System.out.println();

// Interleaved (original-like) format


System.out.println("Interleaved format:");
for (int i = 0; i < v.get(0).length(); i++) {
for (int j = 0; j < 2; j++) {
if (i < v.get(j).length()) {
System.out.print(v.get(j).charAt(i));
}
}
}
System.out.println();
}
}
PS C:\Users\adarsh\Desktop\cf> & 'C:\Program Files\Java\jdk-21\bin\java.exe'
'-XX:+ShowCodeDetailsInExceptionMessages' '-cp'

'C:\Users\adarsh\AppData\Roaming\Code\User\workspaceStorage\d8a4d4e5d6a30892978430a025a0bf4
0\redhat.java\jdt_ws\cf_fa686e5a\bin' 'Main'
Enter a string: Adarsh
Combined Rails:
Arh
das
Interleaved format:
Adarsh
import java.util.*; public class
MD5HashCalculator { public static void
main(String[] args) {
Scanner scanner = new Scanner(System.in); // Scanner object for user input
// Prompt user to enter the text
System.out.print("Enter text to hash: ");
String text = scanner.nextLine(); // Fixed: using nextLine() instead of nextInt()
try {
String md5Hash = calculateMD5(text); // Call the hashing function
System.out.println("MD5 Hash: " + md5Hash); // Print the result
} catch (NoSuchAlgorithmException e) {
System.out.println("MD5 Algorithm not found."); // In case algorithm is not available
}

scanner.close(); // Close the scanner to avoid resource leak


}

// Function to calculate MD5 hash public static String calculateMD5(String text)


throws NoSuchAlgorithmException {
// Get an instance of MD5 MessageDigest
MessageDigest md = MessageDigest.getInstance("MD5");

// Convert string to bytes using UTF-8 encoding and compute hash


byte[] hashBytes = md.digest(text.getBytes(StandardCharsets.UTF_8));

// Convert the byte array into a positive BigInteger


BigInteger number = new BigInteger(1, hashBytes);

// Convert the BigInteger to a hex string


StringBuilder hashText = new StringBuilder(number.toString(16));

// Pad with leading zeros to ensure 32-character


length while (hashText.length() < 32) {
hashText.insert(0, '0');
}

return hashText.toString(); // Return the final MD5 hash


}
}

PS C:\Users\ad\Desktop\cf> & 'C:\Program Files\Java\jdk-21\bin\java.exe'


'-XX:+ShowCodeDetailsInExceptionMessages' '-cp'
'C:\Users\ad\AppData\Roaming\Code\User\workspaceStorage\d8a4d4e5d6a30892978430a025a0bf4
0\redhat.java\jdt_ws\cf_fa686e5a\bin' 'MD5HashCalculator'
Enter text to hash: adar
MD5 Hash: 7d1c91ed68d0ef87b8705aefba927eab
import java.util.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class SimpleDESExample {


public static void main(String[] args) throws Exception {
String key = "12345678";
String plainText = "adarsh";
System.out.println("Plain Text: " + plainText);
String encryptedText = encrypt(key, plainText);
System.out.println("Encrypted Text: " + encryptedText);
String decryptedText = decrypt(key, encryptedText);
System.out.println("Decrypted Text: " + decryptedText);
}

public static String encrypt(String key, String message) throws Exception {


SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
DESKeySpec keySpec = new DESKeySpec(key.getBytes(StandardCharsets.UTF_8));
SecretKey secretKey = keyFactory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(message.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}

public static String decrypt(String key, String encryptedMessage) throws Exception {


byte[] encryptedBytes = Base64.getDecoder().decode(encryptedMessage);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
DESKeySpec keySpec = new DESKeySpec(key.getBytes(StandardCharsets.UTF_8));
SecretKey secretKey = keyFactory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}

PS C:\Users\ad\Desktop\cf> & 'C:\Program Files\Java\jdk-21\bin\java.exe'


'-XX:+ShowCodeDetailsInExceptionMessages' '-cp'
'C:\Users\ad\AppData\Roaming\Code\User\workspaceStorage\d8a4d4e5d6a30892978430a025a0bf4
0\redhat.java\jdt_ws\cf_fa686e5a\bin' 'DESExample'
Plain Text: adarsh
Encrypted Text: 0Eny8XNfU5esozk6VrLFTw==
Decrypted Text: Adarsh
PS C:\Users\ad\Desktop\cf>
mport java.security.*;
import javax.crypto.*;
import java.util.Base64;

public class RSAExample {


public static void main(String[] args) throws Exception {
KeyPair keyPair = generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
String plainText = "adarsh";
System.out.println("Plain Text: " + plainText);
String encryptedText = encrypt(publicKey, plainText);
System.out.println("Encrypted Text: " + encryptedText);
String decryptedText = decrypt(privateKey, encryptedText);
System.out.println("Decrypted Text: " + decryptedText);
}
public static KeyPair generateKeyPair() throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
return generator.generateKeyPair();
}
public static String encrypt(PublicKey key, String message) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(message.getBytes("UTF-8"));
return Base64.getEncoder().encodeToString(encryptedBytes);
}

public static String decrypt(PrivateKey key, String encrypted) throws Exception {


byte[] bytes = Base64.getDecoder().decode(encrypted);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedBytes = cipher.doFinal(bytes);
return new String(decryptedBytes, "UTF-8");
}
}

PS C:\Users\ad\Desktop\cf> & 'C:\Program Files\Java\jdk-21\bin\java.exe'


'-XX:+ShowCodeDetailsInExceptionMessages' '-cp'
'C:\Users\ad\AppData\Roaming\Code\User\workspaceStorage\d8a4d4e5d6a30892978430a025a0bf4
0\redhat.java\jdt_ws\cf_fa686e5a\bin' 'RSAExample'
Plain Text: adarsh
Encrypted Text:
kL1o6Ls5tT0vLp60Fv2XauVq7pt1j9hCUyFb6n70D0Up7VpBbnH2z0zIkZRRuh1AGZTfsDpNVFAsLzO68f
oKmT9j7wPZGQbnZ5SwOwzhn3L0e7OliXktw==
Decrypted Text: adarsh
import java.math.*;

public class DiffieHellman {


public static BigInteger power(BigInteger base, BigInteger exp, BigInteger mod) {
BigInteger result = BigInteger.ONE;
base = base.mod(mod);
while (exp.compareTo(BigInteger.ZERO) > 0) {
if (exp.mod(BigInteger.TWO).equals(BigInteger.ONE)) {
result = (result.multiply(base)).mod(mod);
}
exp = exp.shiftRight(1); // Divide by 2
base = (base.multiply(base)).mod(mod);
}
return result;
}

public static void main(String[] args) {


BigInteger p = BigInteger.valueOf(37); // Prime number
BigInteger g = BigInteger.valueOf(8); // Primitive root
BigInteger a = BigInteger.valueOf(11); // Alice's private key
BigInteger b = BigInteger.valueOf(22); // Bob's private key
BigInteger A = power(g, a, p); // Alice's public key
BigInteger B = power(g, b, p); // Bob's public key
BigInteger keyA = power(B, a, p); // Key computed by Alice
BigInteger keyB = power(A, b, p); // Key computed by Bob

System.out.println("Public Key of Alice: " + A);


System.out.println("Public Key of Bob: " + B);
System.out.println("Shared Secret Key (Alice): " + keyA);
System.out.println("Shared Secret Key (Bob): " + keyB);
}
}

PS C:\Users\ad\Desktop\cf> & 'C:\Program Files\Java\jdk-21\bin\java.exe'


'-XX:+ShowCodeDetailsInExceptionMessages' '-cp'
'C:\Users\ad\AppData\Roaming\Code\User\workspaceStorage\d8a4d4e5d6a30892978430a025a0bf4
0\redhat.java\jdt_ws\cf_fa686e5a\bin' 'DiffieHellman'
Public Key of Alice: 34
Public Key of Bob: 8
Shared Secret Key (Alice): 5
Shared Secret Key (Bob): 5
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESExample {


public static void main(String[] args) throws Exception {
String plaintext = "adarsh04"; // New input
String key = "ABCDEFGHIJKLMNOP"; // 16-byte AES key

byte[] keyBytes = key.getBytes();


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

// ENCRYPTION
Cipher cipherEncrypt = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipherEncrypt.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipherEncrypt.doFinal(plaintext.getBytes());
String ciphertextBase64 = Base64.getEncoder().encodeToString(encryptedBytes);

// DECRYPTION
Cipher cipherDecrypt = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipherDecrypt.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipherDecrypt.doFinal(encryptedBytes);
String decryptedText = new String(decryptedBytes);

// OUTPUT
System.out.println("Plaintext: " + plaintext);
System.out.println("Ciphertext (Base64): " + ciphertextBase64);
System.out.println("Decrypted Text: " + decryptedText);
}
}

PS C:\Users\ad\Desktop\cf> & 'C:\Program Files\Java\jdk-21\bin\java.exe'


'-XX:+ShowCodeDetailsInExceptionMessages' '-cp'
'C:\Users\ad\AppData\Roaming\Code\User\workspaceStorage\d8a4d4e5d6a30892978430a025a0bf4
0\redhat.java\jdt_ws\cf_fa686e5a\bin' 'AESExample'
Plaintext: adarsh04
Ciphertext (Base64): GdyIL/ZazkrPY4ZTkDM+NQ==
Decrypted Text: adarsh04
PS C:\Users\ad\Desktop\cf>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy