Created
November 14, 2014 19:18
-
-
Save gokhanaliccii/5f04a85129ffa9f9c262 to your computer and use it in GitHub Desktop.
Encryption with shift cipher algorithm.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package examples; | |
/** | |
* Created by Gökhan on 11/14/2014. | |
*/ | |
public class ShiftCipher { | |
private int key; | |
public static final int ALPHABET_LEN = 26; | |
public ShiftCipher(int key) { | |
this.key = key; | |
} | |
public String getEncryptedText(String msg) { | |
if (msg == null) return null; | |
char[] chars = msg.toCharArray(); | |
StringBuilder sb = new StringBuilder(); | |
for (char c : chars) { | |
sb.append(getEncryptedChar(c)); | |
} | |
return sb.toString(); | |
} | |
private char getEncryptedChar(char c) { | |
int base = (int) 'a'; | |
int pos = (int) c; | |
int diff = pos - base; | |
int shifted = (diff + key) % ALPHABET_LEN; | |
int result = shifted + base; | |
return (char) result; | |
} | |
public String getDecryptedText(String msg) { | |
if (msg == null) return null; | |
char[] chars = msg.toCharArray(); | |
StringBuilder sb = new StringBuilder(); | |
for (char c : chars) { | |
sb.append(getDecryptedChar(c)); | |
} | |
return sb.toString(); | |
} | |
private char getDecryptedChar(char c) { | |
int base = (int) 'a'; | |
int pos = (int) c; | |
int diff = pos - base; | |
int shifted = (diff - key); | |
if (shifted < 0) | |
shifted+= ALPHABET_LEN; | |
int result = shifted + base; | |
return (char)result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment