Skip to content

Instantly share code, notes, and snippets.

@gokhanaliccii
Created November 14, 2014 19:18
Show Gist options
  • Save gokhanaliccii/5f04a85129ffa9f9c262 to your computer and use it in GitHub Desktop.
Save gokhanaliccii/5f04a85129ffa9f9c262 to your computer and use it in GitHub Desktop.
Encryption with shift cipher algorithm.
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