简体   繁体   English

凯撒移位密码java

[英]caesar shift cipher java

I'm trying to implement a basic Caesar Shift Cipher for Java to shift all the letters by 13. Here's my code so far. 我正在尝试为Java实现基本的Caesar Shift Cipher,以将所有字母都移位13。这是到目前为止的代码。

    public static String cipher(String sentence){
    String s = "";
    for(int i = 0; i < sentence.length(); i++){
        char c = (char)(sentence.charAt(i) + 13);
        if (c > 'z')
            s += (char)(sentence.charAt(i) - 13);
        else
            s += (char)(sentence.charAt(i) + 13);
    }
    return s;
}

However, the program also changes the values of numbers and special characters and I don't want that. 但是,该程序还会更改数字和特殊字符的值,我不希望这样。

String sentence = "abc123";

returns "nop>?@" 返回“ nop>?@”

Is there a simple way to avoid the special characters and only focus on letters? 有没有一种简单的方法来避免特殊字符而只关注字母?

Edit: I should mention I want to keep all the other bits. 编辑:我应该提到我想保留所有其他位。 So "abc123" would return "nop123". 因此,“ abc123”将返回“ nop123”。

In the following example I encrypt just the letters (more precisely AZ and az) and added the possibility to use any offset: 在以下示例中,我仅加密字母(更准确地说是AZ和az),并添加了使用任何偏移量的可能性:

public static String cipher(String sentence, int offset) {
  String s = "";
  for(int i = 0; i < sentence.length(); i++) {
    char c = (char)(sentence.charAt(i));
    if (c >= 'A' && c <= 'Z') {     
      s += (char)((c - 'A' + offset) % 26 + 'A');
    } else if (c >= 'a' && c <= 'z') {
      s += (char)((c - 'a' + offset) % 26 + 'a');
    } else {
      s += c;
    }
  }
  return s;
}

Here some examples: 这里有一些例子:

cipher("abcABCxyzXYZ123", 1)   // output: "bcdBCDyzaYZA123"
cipher("abcABCxyzXYZ123", 2)   // output: "cdeCDEzabZAB123"
cipher("abcABCxyzXYZ123", 13)  // output: "nopNOPklmKLM123"

Note: Due to your code, I assumed that you just want to handle/encrypt the "ordinary" 26 letters. 注意:由于您的代码,我假设您只想处理/加密“普通” 26个字母。 Which means letters like eg the german 'ü' ( Character.isLetter('ü') will return true) remain unencrypted. 这意味着像德国的“ü”这样的字母( Character.isLetter('ü')将返回true)仍未加密。

Problem is that you add 13 as a fixed number, and that will for some letters (in second half of alphabet mostly and digits) produce characters that aren't letters. 问题是您将13添加为固定数字,这将对某些字母(大部分在字母的后半部分和数字)产生不是字母的字符。

You could solve this by using array of letters and shifting through those characters. 您可以通过使用字母数组并在这些字符之间移动来解决此问题。 (similar for digits) So something like this (数字相似)所以像这样

List<Character> chars = ... // list all characters, separate lists for upper/lower case
char c = chars.get((chars.indexOf(sentence.charAt(i)) + 13)%chars.size());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM