Some crypto for starters

AtbashCipher.java 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import java.io.*;
  2. import java.util.HashMap;
  3. import java.util.stream.Stream;
  4. public class AtbashCipher{
  5. private static final String abc = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
  6. private static final String cba = "ZzYyXxWwVvUuTtSsRrQqPpOoNnMmLlKkJjIiHhGgFfEeDdCcBbAa";
  7. private static final HashMap<Character, Character> key = new HashMap<>();
  8. public AtbashCipher() {
  9. createKey();
  10. }
  11. private void createKey() {
  12. char[] abcArr = abc.toCharArray();
  13. char[] cbaArr = cba.toCharArray();
  14. for (int i = 0; i < abcArr.length; i++) {
  15. key.put(abcArr[i], cbaArr[i]);
  16. }
  17. }
  18. public static String cipher(String s) {
  19. char[] charArray = s.toCharArray();
  20. for (int i = 0; i < charArray.length; i++) {
  21. if (key.containsKey(charArray[i])) {
  22. charArray[i] = key.get(charArray[i]);
  23. }
  24. }
  25. return charArrayToString(charArray);
  26. }
  27. public static String charArrayToString(char[] chars) {
  28. StringBuilder sb = new StringBuilder();
  29. for (char c: chars) {
  30. sb.append(c);
  31. }
  32. return sb.toString();
  33. }
  34. public void cipherFile(String filePathIn, String filePathOut) throws FileNotFoundException {
  35. String inFile = fileToString(filePathIn);
  36. PrintStream file = new PrintStream(new File(filePathOut));
  37. PrintStream console = System.out;
  38. System.setOut(file);
  39. String swappedChars = Stream.of(inFile)
  40. .map(AtbashCipher::cipher)
  41. .reduce("", String::concat);
  42. System.out.println(swappedChars);
  43. System.setOut(console);
  44. }
  45. private String fileToString(String filePath) throws FileNotFoundException {
  46. File file = new File(filePath);
  47. FileReader fReader = new FileReader(file);
  48. BufferedReader bufferedReader = new BufferedReader(fReader);
  49. StringBuilder sb = new StringBuilder();
  50. String line;
  51. try {
  52. while ((line = bufferedReader.readLine()) != null) {
  53. sb.append(line + "\n");
  54. }
  55. } catch (IOException e) {
  56. System.out.println("Error reading file");
  57. }
  58. return sb.toString();
  59. }
  60. }