Some crypto for starters

ROT13.java 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import static java.lang.Character.isLowerCase;
  2. import static java.lang.Character.isUpperCase;
  3. import static java.lang.Character.toLowerCase;
  4. public class ROT13 {
  5. Character cs;
  6. Character cf;
  7. ROT13(Character cs, Character cf) {
  8. this.cs= cs;
  9. this.cf=cf;
  10. }
  11. ROT13() {
  12. this.cs='a';
  13. this.cf='m';
  14. }
  15. public String crypt(String text) throws UnsupportedOperationException {
  16. return encrypt(encrypt(text));
  17. }
  18. public String encrypt(String text) {
  19. String result = "";
  20. int rotator = cf-cs;
  21. boolean isUppercase = false;
  22. for(int i=0; i<text.length(); i++){
  23. isUppercase = Character.isUpperCase(text.charAt(i));
  24. int temp = Character.toLowerCase(text.charAt(i));
  25. if (temp<97|temp>122){
  26. } else if(temp+rotator < 122){
  27. temp = (int)text.charAt(i)+rotator;
  28. } else {
  29. temp = 96 + ((temp+rotator)-122);
  30. }
  31. if(isUppercase){temp=Character.toUpperCase(temp);}
  32. result+= (char)temp;
  33. }
  34. return result;
  35. }
  36. public String decrypt(String text) {
  37. String result = "";
  38. int rotator = cf-cs;
  39. boolean isUppercase = false;
  40. for(int i=0; i<text.length(); i++){
  41. isUppercase = Character.isUpperCase(text.charAt(i));
  42. int temp = Character.toLowerCase(text.charAt(i));
  43. if (temp<97|temp>122){
  44. } else if(temp-rotator > 97){
  45. temp = (int)text.charAt(i)-rotator;
  46. } else {
  47. temp = 122 - (96-(temp-rotator));
  48. }
  49. if(isUppercase){temp=Character.toUpperCase(temp);}
  50. result+= (char)temp;
  51. }
  52. return result;
  53. }
  54. public static String rotate(String s, Character c) {
  55. String result = "";
  56. String reference = s+s;
  57. int rotator = Character.toLowerCase(c)-'a';
  58. boolean isUppercase = false;
  59. for(int i=0; i<s.length(); i++){
  60. Character temp = reference.charAt(i+rotator);
  61. result+= temp;
  62. }
  63. return result;
  64. }
  65. }