fork download
  1. class vigenereCipher {
  2. static String encode(String text, final String key) {
  3. String res = "";
  4. text = text.toUpperCase();
  5. for (int i = 0, j = 0; i < text.length(); i++) {
  6. char c = text.charAt(i);
  7. if (c < 'A' || c > 'Z') {
  8. continue;
  9. }
  10. res += (char) ((c + key.charAt(j) - 2 * 'A') % 26 + 'A');
  11. j = ++j % key.length();
  12. }
  13. return res;
  14. }
  15. static String decode(String text, final String key) {
  16. String res = "";
  17. text = text.toUpperCase();
  18. for (int i = 0, j = 0; i < text.length(); i++) {
  19. char c = text.charAt(i);
  20. if (c < 'A' || c > 'Z') {
  21. continue;
  22. }
  23. res += (char) ((c - key.charAt(j) + 26) % 26 + 'A');
  24. j = ++j % key.length();
  25. }
  26. return res;
  27. }
  28. public static void main(String[] args) throws java.lang.Exception {
  29. String key = "LEMON";
  30. String msg = "ATTACK AT DAWN";
  31. System.out.println("Simulating Vigenere Cipher\n");
  32. System.out.println("Input Message : " + msg);
  33. String enc = encode(msg, key);
  34. System.out.println("Encrypted Message : " + enc);
  35. System.out.println("Decrypted Message : " + decode(enc, key));
  36. }
  37. }
Success #stdin #stdout 0.16s 50316KB
stdin
Standard input is empty
stdout
Simulating Vigenere Cipher

Input Message : ATTACK AT DAWN
Encrypted Message : LXFOPVEFRNHR
Decrypted Message : ATTACKATDAWN