Guest User

Untitled

a guest
Dec 17th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. public class Vigenere {
  2. private final int SIZE = 26;
  3. private final int BASE = 65;
  4. private char[][] cryptex = new char[SIZE][SIZE];
  5.  
  6. // constructors ========================================================
  7. public Vigenere() {
  8. // generate Vigenere cryptex
  9. for (int row = 0; row < SIZE; row++) {
  10. int i = 0;
  11. for (int col = 0; col < SIZE; col++) {
  12. cryptex[row][col] = (char)(('A' + row + i++) % SIZE + BASE);
  13. }
  14. }
  15. }
  16.  
  17. // getters/setters =====================================================
  18.  
  19. // methods =============================================================
  20. public char encrypt(char letter, char key) {
  21. return cryptex[letter % SIZE][key % SIZE];
  22. }
  23.  
  24. public String encrypt(String message, String key) {
  25. StringBuilder sb = new StringBuilder();
  26. message = message.toUpperCase();
  27. key = key.toUpperCase();
  28.  
  29. for (int i = 0, j = 0; i < message.length(); i++) {
  30. if (message.charAt(i) >= 'A' && message.charAt(i) <= 'Z') {
  31. sb.append(encrypt(message.charAt(i), key.charAt(j++ % key.length())));
  32. }
  33. else
  34. sb.append(message.charAt(i));
  35. }
  36.  
  37. return sb.toString();
  38. }
  39.  
  40. public char decrypt(char letter, char key) {
  41. int index = findLetter(letter, key);
  42. return cryptex[index][0];
  43. }
  44.  
  45. public String decrypt(String cipher, String key) {
  46. StringBuilder sb = new StringBuilder();
  47. cipher = cipher.toUpperCase();
  48. key = key.toUpperCase();
  49.  
  50. for (int i = 0, j = 0; i < cipher.length(); i++) {
  51. if (cipher.charAt(i) >= 'A' && cipher.charAt(i) <= 'Z') {
  52. sb.append(decrypt(cipher.charAt(i), key.charAt(j++ % key.length())));
  53. }
  54. else
  55. sb.append(cipher.charAt(i));
  56. }
  57.  
  58. return sb.toString();
  59. }
  60.  
  61. // helper methods ======================================================
  62. private int findLetter(char letter, char key) {
  63. for (int i = 0; i < SIZE; i++) {
  64. if (cryptex[i][key % SIZE] == letter)
  65. return i;
  66. }
  67. return -1;
  68. }
  69. }
Add Comment
Please, Sign In to add comment