JAVA实现caesar凯撒加密算法
public class caesar {
public static final string source = "abcdefghijklmnopqrstuvwxyz";
public static final int len = source.length();
/**
* @param args
*/
public static void main(string[] args) {
string result = caesarencryption("newyork");
system.out.println("encryption result:" + result);
system.out.println("decryption result:" + caesardecryption(result));
}
//encryption
public static string caesarencryption(string s) {
stringbuilder sb = new stringbuilder();
if (s == null || s.length() < 1) {
system.out.println("you input nothing.");
return null;
}
if (!isalp(s)) {
system.out.println("input abc... only");
return null;
}
s = s.tolowercase();
int len = s.length();
for (int j = 0; j < len; j++) {
char c = s.charat(j);
int a = source.indexof(c);
if (a == len -1) a = -1;
if (a == len -2) a = -2;
if (a == len - 3) a = -3;
sb.append(source.charat(a + 3));
}
return sb.tostring();
}
//decryption
public static string caesardecryption(string s) {
stringbuilder sb = new stringbuilder();
if (s == null || s.length() < 1) {
system.out.println("you input nothing.");
return null;
}
if (!isalp(s)) {
system.out.println("input abc... only");
return null;
}
s = s.tolowercase();
for (int i = 0; i < s.length(); i++) {
char c = s.charat(i);
int a = source.indexof(c);
if (a == 2) a = len + 2;
if (a == 1) a = len + 1;
if (a == 0) a = len;
sb.append(source.charat(a - 3));
}
return sb.tostring();
}
public static boolean isalp(string s) {
string p = "^[a-za-z]+$";
pattern pattern = pattern.compile(p);
matcher matcher = pattern.matcher(s);
if (matcher.find()) {
return true;
}
return false;
}
}