Guest User

Untitled

a guest
Jan 9th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1.  
  2. public class CipherKey {
  3.  
  4. private String key = "I LOVE ME";
  5. private String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "; // Initializing the alphabet as a String for later use
  6.  
  7.  
  8.  
  9.  
  10.  
  11. public CipherKey(){
  12.  
  13. };
  14.  
  15.  
  16.  
  17. public void setKey (String key){
  18.  
  19. boolean isValid = true;
  20.  
  21.  
  22.  
  23. for (char c : key.toCharArray()) { // Making sure its only uppercase letters and setting isValid to false if it encounters an invalid character
  24. if (((int)c > 90 || (int)c < 65) && (int)c != 32){
  25. isValid = false;
  26. }
  27. }
  28.  
  29. if(key.length() < 1){
  30. isValid = false;
  31. }
  32.  
  33. if(isValid) {
  34. this.key = key;
  35. }
  36.  
  37.  
  38. }
  39.  
  40. public String encrypt(String phrase){
  41.  
  42.  
  43. int times = (phrase.length() / this.key.length()) + 1;
  44. String k = "";
  45.  
  46.  
  47. if(phrase.length()> this.key.length()) {
  48. for (int i = 0; i < times; i++) {
  49.  
  50. k += this.key;
  51.  
  52. }
  53. } else {
  54. k = this.key;
  55. }
  56.  
  57.  
  58. String finalKey = k.substring(0, phrase.length());
  59.  
  60. String encrypted ="";
  61.  
  62.  
  63. for (int i = 0; i < phrase.length(); i++) {
  64.  
  65. if((int)((alphabet.indexOf(finalKey.toCharArray()[i]+1)+ phrase.toCharArray()[i])) > 126){
  66. encrypted += (char)((alphabet.indexOf(finalKey.toCharArray()[i])+1 + phrase.toCharArray()[i])-95);
  67. } else {
  68. encrypted += (char)(alphabet.indexOf(finalKey.toCharArray()[i])+1 + phrase.toCharArray()[i]);
  69. }
  70.  
  71. }
  72.  
  73.  
  74. return encrypted;
  75.  
  76. }
  77.  
  78.  
  79. public String decrypt ( String phrase){
  80.  
  81. int times = (phrase.length() / this.key.length()) + 1;
  82. String k = "";
  83.  
  84. if(phrase.length()>this.key.length()) {
  85. for (int i = 0; i < times; i++) {
  86.  
  87. k += this.key;
  88.  
  89. }
  90. } else {
  91. k = this.key;
  92. }
  93.  
  94.  
  95. String finalKeyDecrypt = k.substring(0, phrase.length());
  96.  
  97. String decrypted = "";
  98.  
  99.  
  100. for (int i = 0; i < phrase.length() ; i++) {
  101.  
  102.  
  103.  
  104. decrypted += (char) (phrase.toCharArray()[i] - (alphabet.indexOf(finalKeyDecrypt.toCharArray()[i])+1));
  105.  
  106.  
  107. }
  108.  
  109. return decrypted;
  110.  
  111.  
  112. }
  113.  
  114.  
  115.  
  116.  
  117.  
  118. }
Advertisement
Add Comment
Please, Sign In to add comment