I have a code where I must implement an interface, and the purpose is to take a string like mycookisred and therein insert random characters between each from the original word. That could hinder, in this case, e.g. meynciovoksidswrbendn. Another example, for the sake of completeness: the mycleverpassword string could become mxyschlmezvievrppeaysisvwcoorydc.
I know my code isn't exactly right for that purpose, but can someone please help or guide me on what to do from this starting point?
import java.util.Random;
public class password implements Encryptable
{
private String message;
private boolean encrypted;
private int shift;
private Random generator;
public password(String msg)
{
message = msg;
encrypted = false;
generator = new Random();
shift = generator.nextInt(10) + 5;
}
public void encrypt()
{
if (!encrypted)
{
String masked = "";
for ( int index = 0; index < message.length(); index++)
masked = masked + (char)(message.charAt(index) +shift);
message = masked;
encrypted = true;
}
}
public String decrypt()
{
if (!encrypted)
{
String unmasked = "";
for ( int index = 0; index < message.length(); index++)
unmasked = unmasked + (char)(message.charAt(index) - shift);
message = unmasked;
encrypted = false;
}
return message;
}
public boolean isEncrypted()
{
return encrypted;
}
public String toString()
{
return message;
}
}
public class passwordTest
{
public static void main(String[] args)
{
password hide = new password("my clever password");
System.out.println(hide);
hide.encrypt();
System.out.println(hide);
hide.decrypt();
System.out.println(hide);
}
}
public interface Encryptable
{
public void encrypt();
public String decrypt();
}
Just use this to randomize and normalize the String:
private String randomize(String s) {
String re = "";
int len = s.length();
for(int i = 0; i < len - 1; i++) {
char c = s.charAt(i);
re += c;
re += (char) (generator.nextInt('z' - 'a') + 'a');
}
re += s.charAt(len - 1);
return re;
}
private String normalize(String s) {
String re = "";
for(int i = 0; i < s.length(); i+=2) {
re += s.charAt(i);
}
return re;
}
And a Class should start with an upper case character. You don't need to, but for example Eclipse will cry.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With