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

Name: Dhir Talreja

Roll No: A115

EXPERIMENT 4

OneTimePad.java:

import java.security.SecureRandom;

public class OneTimePad {

public sta c String generateRandomKey(int length) {

SecureRandom random = new SecureRandom();

StringBuilder key = new StringBuilder(length);

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

char randomChar = (char) (random.nextInt(26) + 'a'); // Generate a random lowercase le er

key.append(randomChar);

return key.toString();

public sta c String encrypt(String plaintext, String key) {

StringBuilder ciphertext = new StringBuilder();

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

char plainChar = plaintext.charAt(i);

char keyChar = key.charAt(i);

char encryptedChar = (char) ((plainChar - 'a' + keyChar - 'a') % 26 + 'a');

ciphertext.append(encryptedChar);

return ciphertext.toString();

}
public sta c String decrypt(String ciphertext, String key) {

StringBuilder plaintext = new StringBuilder();

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

char cipherChar = ciphertext.charAt(i);

char keyChar = key.charAt(i);

char decryptedChar = (char) ((cipherChar - 'a' - (keyChar - 'a') + 26) % 26 + 'a');

plaintext.append(decryptedChar);

return plaintext.toString();

public sta c void main(String[] args) {

String plaintext = "test";

String key = generateRandomKey(plaintext.length());

System.out.println("Plaintext: " + plaintext);

System.out.println("Key: " + key);

String ciphertext = encrypt(plaintext, key);

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

String decryptedText = decrypt(ciphertext, key);

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

Code:

You might also like