Secret
Typer | Posted on | |
import java.util.Random;
public class SecretTest {
public static void main(String[] args) {
Secret hush = new Secret("What happened yesterday?");
System.out.println("Original Message: " + hush);
hush.encrypt();
System.out.println("Encrypted Message: " + hush);
hush.decrypt();
System.out.println("Unencrypted Message: " + hush);
}
}
//
interface Encryptable {
public void encrypt();
public String decrypt();
}
class Secret implements Encryptable {
private String message;
private boolean encrypted;
private int shift;
private Random generator;
public Secret(String message) {
this.message = message;
this.encrypted = false;
this.generator = new Random();
this.shift = this.generator.nextInt(10) + 5;
}
public void encrypt() {
if (!encrypted) {
String masked = "";
for (int i = 0; i < message.length(); i++) {
masked = masked + (char) (message.charAt(i) + shift);
}
message = masked;
encrypted = true;
}
}
public String decrypt() {
if (encrypted) {
String unmasked = "";
for (int i = 0; i < message.length(); i++) {
unmasked = unmasked + (char) (message.charAt(i) - shift);
}
message = unmasked;
encrypted = false;
}
return message;
}
public boolean isEncrypted() {
return encrypted;
}
@Override
public String toString() {
return message;
}
}