java - 反转模数运算符以进行解密

标签 java arrays oop encryption

在学校,我有一个作业要根据以下要求加密一个四位数的整数。

A company wants to transmit data over the telephone, but they are concerned that their phones may be tapped. All of their data is transmitted as four-digit integers. They have asked you to write a method that will encrypt their data so that it may be transmitted more securely. Your method should read a four-digit integer and encrypt it as follows: Replace each digit by (the sum of that digit plus 7) modulus 10. Then, swap the second digit with the fourth. Then print the encrypted integer. Write a separate method that inputs an en-crypted four-digit integer, and decrypts it to form the original number.

四位数的加密不是问题,我把它转换成一个字符串,然后转换成一个char数组,然后根据需要单独加密数字。

我做的方法是这样的:

public int encrypt4DigitNumber(int number) throws Exception {
    String numberAsString = String.valueOf(number);
    if (numberAsString.length() != 4) {
        throw new Exception("The digit has to be 4 digits long");
    }
    int[] numbers = new int[4];

    char[] numbersAsChars = numberAsString.toCharArray();
    for (int index = 0; index < numbersAsChars.length; index++) {
        int currentNumber = Character.getNumericValue(numbersAsChars[index]);
        int numberToReplace = (currentNumber + 7) % 10;

        numbers[index] = numberToReplace;
    }

    int second = numbers[1];
    int fourth = numbers[3];

    numbers[1] = fourth;
    numbers[3] = second;

    StringBuilder encryptedNumberStringBuilder = new StringBuilder();
    for (int encryptedNumber : numbers) {
        encryptedNumberStringBuilder.append(encryptedNumber);
    }

    String encryptedNumberString = encryptedNumberStringBuilder.toString();
    return Integer.parseInt(encryptedNumberString);
}

当我必须解密加密的四位数代码时,问题就来了。

我知道我必须交换 2 个数组元素,并将 7 添加到数组中的每个数字。

我不知道该怎么做的是反转模运算符,我唯一能想到的就是将当前数字乘以 10,但这行不通。

在做了一些研究之后,我必须在某个地方搜索模数的剩余部分,但我完全不知道该怎么做。我是否还需要返回加密函数中的那些并将它们传递给解密函数?

谁能解释一下取反模运算符的过程?

最佳答案

如果您使用偏移量 7 加密从 0 到 9(= mod 10)的数字,您当然可以在解密期间从每个数字中减去偏移量,如果数字为负则环绕,但这不是很好:

int numberToReplace = currentNumber - 7;
if (numberToReplace < 0) {
    numberToReplace += 10;
}

如果加密偏移量为 7,则解密偏移量将为 3 (10 - 7)。您可以将每个数字加 3 并应用模 10 来解密它们。

int numberToReplace = (currentNumber + 3) % 10;

关于java - 反转模数运算符以进行解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39821281/

相关文章:

ios - Swift Array 在 Xcode 6.1.1 中导致索引问题

c - 获取未使用的变量警告

c++ - 打开对象的实际类型的正确方法是什么?

c# - 这是糟糕的 oop 设计吗?

java - eclipse 和 tomcat 的硬件要求

java - 来自客户端的用户输入不会发送到服务器

java - Neo4j 和 ORM( hibernate )

c++ - 无法将 vector<int> 转换为 int* 用于 bool testPIN

php - php父类(super class)如何访问其子类的 protected 方法?

java - 向局域网上的所有人广播