使用Caesar Cipher加密大数字

时间:2014-11-05 23:27:08

标签: java encryption

现在我有一个Caesar Cipher的代码,但是当我尝试使用非常大的数字加密文本时遇到了一个问题。 例如1000。

static String encrypt(String plaintext) {
    StringBuilder ciphertext = new StringBuilder(plaintext);
    for (int i = 0; i < ciphertext.length(); i++) {
        ciphertext.setCharAt(i, encrypt(ciphertext.charAt(i)));
    }
    return ciphertext.toString();
}

static String decrypt(String plaintext) {
    StringBuilder ciphertext = new StringBuilder(plaintext);
    for (int i = 0; i < ciphertext.length(); i++) {
        ciphertext.setCharAt(i, decrypt(ciphertext.charAt(i)));
    }
    return ciphertext.toString();
}

static char encrypt(char c) {
    return (char) ('!' + (c - '!' + 1000) % ('~' - '!' + 1));
}

static char decrypt(char c) {
    return (char) ('!' + (c - '!' - 1000) % ('~' - '!' + 1));
}

让我说我在加密中输入“abc123”,使用1000作为我的密钥,我得到了一堆未知字符。请记住,我不希望它只使用ASCII代码循环通过a-z而是符号。

任何帮助都会很棒!

1 个答案:

答案 0 :(得分:1)

在Java中,模数的结果与被除数的符号相同。因此,当你计算c - '!' - 1000时,你会得到一个负值,在模数之后,它仍然是负数。当你添加'!'时,你将计算出一个小于'!'的值,这对于一个char来说是不可见的或下溢的。

static char decrypt(char c) {
    char d = '~' - '!' + 1;
    int x = (c - '!' - 1000) % d;
    if (x < 0) x += d;
    return (char)('!' + x);
}

以下是您遇到的问题的讨论。

How does java do modulus calculations with negative numbers?

相关问题