0% found this document useful (0 votes)
16 views2 pages

Experiment 4

The document describes code for implementing a one-time pad encryption algorithm. It includes methods to generate a random key of a given length, encrypt a plaintext by combining it with a key, and decrypt a ciphertext by combining it with the same key.
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)
16 views2 pages

Experiment 4

The document describes code for implementing a one-time pad encryption algorithm. It includes methods to generate a random key of a given length, encrypt a plaintext by combining it with a key, and decrypt a ciphertext by combining it with the same key.
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/ 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