在C ++中反转乘法运算符

时间:2019-02-04 20:29:26

标签: c++ multiplication

我正在尝试撤消应用程序的反序列化程序,并且我基本上已经完成了,但是我一直陷在这个问题上。不论出于何种原因,该应用程序都通过将4字节数字乘以编码键(或与此相关的解码键)来进行解码

int decoded_number = (encode_key * encoded_number);

这可用于解码其数字,但是,我对编码数字更感兴趣,因此可以序列化数据。我尝试通过将解码后的数字与编码键相乘来对数字进行编码

int encoded_number = (encode_key * decoded_number);

但是,当我将其与原始编码数字进行比较时,它是完全不同的。我还尝试过对数字进行暴力编码,并且可以工作,但是要花很多时间才能生成数字,这在序列化大量数字时不可行。

for (int i = INT_MIN; i < INT_MAX; i++){
  if (i * encode_key == decoded_number)
    return i; /* "i" is the encoded number */
}

在这一点上,我不知道还有什么尝试。我的代码如下:

#include <iostream>
using namespace std;

int encode_key = -381784151; /* Key I took from the application */
int encoded_numbers[2] = {-810310503, 1520670208}; /* Numbers I took from the app */

int bruteforce(int decoded_number){
    for (int i = -2147483648; i < 2147483647; i++){ /* min and max int*/
        if (encode_key * i == decoded_number){ /* brute comparison */
            return i;
        }
    }
}

int main()
{
    for (int i = 0; i < 2; i++){
        int encoded_number = encoded_numbers[i];
        int decoded_number = encode_key * encoded_number;
        int attempt_encode = encode_key * decoded_number;
        int brute_encode = bruteforce(decoded_number);

        cout << "STARTING WITH NUMBER" << i+1 << "\n";
        cout << "Encoded Number: " << encoded_number << "\n";
        cout << "Decoded Number: " << decoded_number << "\n";
        cout << "Attempt to Re-Encode (FAIL): " << attempt_encode << "\n";
        cout << "Bruteforce Encode (SLOW!): " << brute_encode << "\n\n";
    }
    return 0;
}

Click here to run the code in your browser

1 个答案:

答案 0 :(得分:1)

感谢@EricPostpischil提供了一个很好的答案。要逆转乘法,您所需要做的就是将解码后的数字乘以key的乘法逆。这是采用该解决方案的代码示例。

#include <iostream>
using namespace std;

int encode_key = -381784151;
int encoded_numbers[2] = {-810310503, 1520670208};

int getinverse(int key){
    for (int i = -2147483648; i < 2147483647; i++){ /* min and max int*/
        if (key * i == 1){ /* brute comparison */
            return i;
        }
    }
}

int main()
{
    int inverse = getinverse(encode_key); /* Grab the multiplicative inverse of encode_key */

    for (int i = 0; i < 2; i++){
        int encoded_number = encoded_numbers[i];
        int decoded_number = encode_key * encoded_number;
        int attempt_encode = inverse * decoded_number; /* multiply inverse and decoded_number */

        cout << "STARTING WITH NUMBER" << i+1 << "\n";
        cout << "Encoded Number: " << encoded_number << "\n";
        cout << "Decoded Number: " << decoded_number << "\n";
        cout << "Attempt to Re-Encode (CORRECT!): " << attempt_encode << "\n\n";
    }
    return 0;
}