Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ROT-13 function in java?

Tags:

java

rot13

Is there already a rot13() and unrot13() implementation as part of one of the standard Java libraries? Or do I have to write it myself and "reinvent the wheel"?

It might look something like this:

int rot13 ( int c ) { 
  if ( (c >= 'A') && (c <= 'Z') ) 
    c=(((c-'A')+13)%26)+'A';

  if ( (c >= 'a') && (c <= 'z') )
    c=(((c-'a')+13)%26)+'a';

  return c; 
}
like image 292
Regex Rookie Avatar asked Jan 24 '12 02:01

Regex Rookie


People also ask

What is ROT13 Python?

Explanation of ROT13 AlgorithmROT13 cipher refers to the abbreviated form Rotate by 13 places. It is a special case of Caesar Cipher in which shift is always 13. Every letter is shifted by 13 places to encrypt or decrypt the message.

What is the encryption key for ROT13?

Introduction. The ROT13 cipher is a substitution cipher with a specific key where the letters of the alphabet are offset 13 places. I.e. all 'A's are replaced with 'N's, all 'B's are replaced with 'O's, and so on. It can also be thought of as a Caesar cipher with a shift of 13.

What is ROT13 used for?

ROT13 ("rotate by 13 places", usually hyphenated ROT-13) is a simple Caesar cipher used for obscuring text by replacing each letter with the letter thirteen places down the alphabet.

What is ROT13 Caesar cipher?

ROT13 ("rotate by 13 places", sometimes hyphenated ROT-13) is a simple letter substitution cipher that replaces a letter with the 13th letter after it in the alphabet. ROT13 is a special case of the Caesar cipher which was developed in ancient Rome.


2 Answers

Might as well contribute my function to save other developers the valuable seconds

public static String rot13(String input) {
   StringBuilder sb = new StringBuilder();
   for (int i = 0; i < input.length(); i++) {
       char c = input.charAt(i);
       if       (c >= 'a' && c <= 'm') c += 13;
       else if  (c >= 'A' && c <= 'M') c += 13;
       else if  (c >= 'n' && c <= 'z') c -= 13;
       else if  (c >= 'N' && c <= 'Z') c -= 13;
       sb.append(c);
   }
   return sb.toString();
}
like image 99
georgiecasey Avatar answered Sep 22 '22 14:09

georgiecasey


I don't think it's part of Java by default, but here's an example of how you can implement it;

public class Rot13 { 

    public static void main(String[] args) {
        String s = args[0];
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if       (c >= 'a' && c <= 'm') c += 13;
            else if  (c >= 'A' && c <= 'M') c += 13;
            else if  (c >= 'n' && c <= 'z') c -= 13;
            else if  (c >= 'N' && c <= 'Z') c -= 13;
            System.out.print(c);
        }
        System.out.println();
    }

}

Source: http://introcs.cs.princeton.edu/java/31datatype/Rot13.java.html

like image 26
Chris Thompson Avatar answered Sep 19 '22 14:09

Chris Thompson