Skip to content

Instantly share code, notes, and snippets.

@benfb
Created December 2, 2012 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save benfb/4190531 to your computer and use it in GitHub Desktop.
Save benfb/4190531 to your computer and use it in GitHub Desktop.
Vigenere
public class Vigenere
{
//declare instance variables for text and keyword
private String pt = "";
private String key = "";
Vigenere(){ //default constructor
pt = "";
key = "";
}
//initialization constructor
Vigenere(String txt, String keyw){
pt = txt;
key = keyw;
}
//modifier method for text
public void setText(String txt)
{
pt = txt;
}
//modifier method for keyword
public void setKeyword(String keyw)
{
key = keyw;
}
//accessor method for text
public String getText()
{
return pt;
}
//accessor method for keyword
public String getKey()
{
return key;
}
//encrypt method
public String encrypt()
{
String l = key;
for(int k = 0;k < pt.length()-key.length(); k++)
{
l = l + l.charAt(k); //makes sure that the key fits the length of the message
}
String s = "";
for(int i = 0; i < pt.length(); i++) //runs some complicated math that is difficult to describe on the string
{
char a = pt.charAt(i);
int x = a - 65;
char b = l.charAt(i);
int y = b - 65;
char z = (char)(((x + y) % 26) + 65);
s = s + z;
}
return s;
}
//decrypt method
public String decrypt()
{
String l = key;
for(int k = 0; k < pt.length() - key.length(); k++) //makes sure that the key gets repeated until it's as long as the message
{
l = l + l.charAt(k);
}
String encrypt = encrypt();
String s = "";
for(int i = 0; i < encrypt.length(); i++) //does the reverse of that complicated math I mentioned earlier
{
char a = encrypt.charAt(i);
int x = a - 65;
char b = l.charAt(i);
int y = b - 65;
int z = (x - y);
if(z < 0)
z = z + 26;
z = z + 65;
char h = (char)z;
s = s + h;
}
return s;
}
//equals() method
public boolean equals(Vigenere v)
{
boolean equal = pt.equals(v.getText()) && key.equals(v.getKey()); //creates new boolean to see if they're equal
System.out.println(equal);
return equal;
}
//toString() method
public String toString()
{
return "" + pt + key; //toString!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment