Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

cryptography - Simple caesar cipher in java

Hey I'm making a simple caesar cipher in Java using the formula [x-> (x+shift-1) mod 127 + 1] I want to have my encrypted text to have the ASCII characters except the control characters(i.e from 32-127). How can I avoid the control characters from 0-31 applying in the encrypted text. Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How about something like this:

public String applyCaesar(String text, int shift)
{
    char[] chars = text.toCharArray();
    for (int i=0; i < text.length(); i++)
    {
        char c = chars[i];
        if (c >= 32 && c <= 127)
        {
            // Change base to make life easier, and use an
            // int explicitly to avoid worrying... cast later
            int x = c - 32;
            x = (x + shift) % 96;
            if (x < 0) 
              x += 96; //java modulo can lead to negative values!
            chars[i] = (char) (x + 32);
        }
    }
    return new String(chars);
}

Admittedly this treats 127 as a non-control character, which it isn't... you may wish to tweak it to keep the range as [32, 126].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...