Some crypto for starters

ROT13.java 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import java.util.Arrays;
  2. import java.util.List;
  3. public class ROT13 {
  4. private int rotate;
  5. private int encryptShift = 26;
  6. private boolean encrypt;
  7. public boolean isEncrypt() {
  8. return encrypt;
  9. }
  10. public void setEncrypt(boolean encrypt) {
  11. this.encrypt = encrypt;
  12. }
  13. ROT13(Character cs, Character cf) {
  14. rotate = (int)(cs) - (int)(cf);
  15. }
  16. ROT13() {
  17. }
  18. public int getRotate() {
  19. return rotate;
  20. }
  21. public String crypt(String text){
  22. return encrypt(text);
  23. }
  24. public String crypt(String text, int rotate) throws UnsupportedOperationException {
  25. List<String> textList = Arrays.asList(text.split(" "));
  26. StringBuilder builder = new StringBuilder();
  27. for (String s: textList) {
  28. char[] charArr = s.toCharArray();
  29. for (char c: charArr) {
  30. String strToAppend = isEncrypt() ? shiftCharEncrypt(c, rotate) : shiftCharDecrypt(c, rotate);
  31. builder.append(strToAppend);
  32. }
  33. builder.append(" ");
  34. }
  35. return builder.toString().trim();
  36. }
  37. public String encrypt(String text) {
  38. setEncrypt(true);
  39. return crypt(text, getRotate());
  40. }
  41. public String decrypt(String text) {
  42. setEncrypt(false);
  43. return crypt(text, getRotate() * -1);
  44. }
  45. public String shiftCharEncrypt(char c, int rotate){
  46. if (c > 64){
  47. return ( (c > 96 && (c + rotate) > 96) || (c <= 96 && (c + rotate) > 64) ) ?
  48. ( Character.toString( (char)(c + rotate) ) ) :
  49. ( Character.toString( (char)(c + rotate + encryptShift) ) );
  50. } else {
  51. return Character.toString(c);
  52. }
  53. }
  54. public String shiftCharDecrypt(char c, int rotate){
  55. if (c > 64){
  56. return ( (c + rotate > 122) || (c <= 90 && c + rotate > 90 ) ) ?
  57. ( Character.toString( (char)(c + rotate + encryptShift * -1) ) ) :
  58. ( Character.toString( (char)(c + rotate) ) );
  59. } else {
  60. return Character.toString(c);
  61. }
  62. }
  63. public static String rotate(String s, Character c) {
  64. int rotateBy = (int)(c) - (int)(s.charAt(0));
  65. char[] charArr = s.toCharArray();
  66. char[] returnChar = new char[charArr.length];
  67. int x = 0;
  68. for (int i = rotateBy; i < returnChar.length; i++) {
  69. returnChar[x] = (char)( (int)(charArr[i]));
  70. x++;
  71. }
  72. for (int i = 0; i < rotateBy; i++) {
  73. returnChar[x] = (char)( (int)(charArr[i]));
  74. x++;
  75. }
  76. return String.copyValueOf(returnChar);
  77. }
  78. }