| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- import java.util.Arrays;
- import java.util.List;
-
- public class ROT13 {
- private int rotate;
- private int encryptShift = 26;
- private boolean encrypt;
-
- public boolean isEncrypt() {
- return encrypt;
- }
-
- public void setEncrypt(boolean encrypt) {
- this.encrypt = encrypt;
- }
-
- ROT13(Character cs, Character cf) {
- rotate = (int)(cs) - (int)(cf);
- }
-
- ROT13() {
- }
-
- public int getRotate() {
- return rotate;
- }
-
- public String crypt(String text){
- return encrypt(text);
- }
-
- public String crypt(String text, int rotate) throws UnsupportedOperationException {
- List<String> textList = Arrays.asList(text.split(" "));
- StringBuilder builder = new StringBuilder();
-
- for (String s: textList) {
- char[] charArr = s.toCharArray();
- for (char c: charArr) {
- String strToAppend = isEncrypt() ? shiftCharEncrypt(c, rotate) : shiftCharDecrypt(c, rotate);
- builder.append(strToAppend);
- }
- builder.append(" ");
- }
- return builder.toString().trim();
- }
-
- public String encrypt(String text) {
- setEncrypt(true);
- return crypt(text, getRotate());
- }
-
- public String decrypt(String text) {
- setEncrypt(false);
- return crypt(text, getRotate() * -1);
- }
-
- public String shiftCharEncrypt(char c, int rotate){
- if (c > 64){
- return ( (c > 96 && (c + rotate) > 96) || (c <= 96 && (c + rotate) > 64) ) ?
- ( Character.toString( (char)(c + rotate) ) ) :
- ( Character.toString( (char)(c + rotate + encryptShift) ) );
- } else {
- return Character.toString(c);
- }
- }
-
- public String shiftCharDecrypt(char c, int rotate){
- if (c > 64){
- return ( (c + rotate > 122) || (c <= 90 && c + rotate > 90 ) ) ?
- ( Character.toString( (char)(c + rotate + encryptShift * -1) ) ) :
- ( Character.toString( (char)(c + rotate) ) );
- } else {
- return Character.toString(c);
- }
- }
-
- public static String rotate(String s, Character c) {
- int rotateBy = (int)(c) - (int)(s.charAt(0));
- char[] charArr = s.toCharArray();
- char[] returnChar = new char[charArr.length];
-
- int x = 0;
- for (int i = rotateBy; i < returnChar.length; i++) {
- returnChar[x] = (char)( (int)(charArr[i]));
- x++;
- }
-
- for (int i = 0; i < rotateBy; i++) {
- returnChar[x] = (char)( (int)(charArr[i]));
- x++;
- }
- return String.copyValueOf(returnChar);
- }
-
- }
|