-1

我正在尝试在 Ubuntu 12.04 下使用 Crypto++ 实现 RSA 算法,我设法在一个程序中实现了加密和解密。有什么办法可以让我将加密和解密分开吗?我想要的是当我调用加密部分时,它会创建一个密文作为输出,然后当我调用解密部分时,它会将加密中的密文作为输入,如果我先调用解密部分,那么它将创建一条错误消息。

这是加密和解密的代码:

#include <iostream>
using std::cout;
using std::endl;

#include <iomanip>
using std::hex;

#include <string>
using std::string;

#include "rsa.h"
using CryptoPP::RSA;

#include "integer.h"
using CryptoPP::Integer;

#include "osrng.h"
using CryptoPP::AutoSeededRandomPool;

int main(int argc, char** argv)
{

    // Pseudo Random Number Generator
    AutoSeededRandomPool rng;

    ///////////////////////////////////////
    // Generate Parameters
    CryptoPP::InvertibleRSAFunction params;
    params.GenerateRandomWithKeySize(rng, 3072);

    ///////////////////////////////////////
    // Generated Parameters
    const Integer& n = params.GetModulus();
    const Integer& p = params.GetPrime1();
    const Integer& q = params.GetPrime2();
    const Integer& d = params.GetPrivateExponent();
    const Integer& e = params.GetPublicExponent();

    cout << endl;

    ///////////////////////////////////////
    // Create Keys
    RSA::PrivateKey privateKey(params);
    RSA::PublicKey publicKey(params);
    /////////////////////////////////////////////////////////

    string message, recovered;
    Integer m, c, r;

    cout << endl;
    cout << "RSA Algorithm" << endl;
    cout << "message: " ;
    std::cin >> message;

    // Treat the message as a big endian array
    m = Integer((const byte *)message.data(), message.size());
    cout << "plaintext: " << hex << m << endl << endl;

    cout << "ENCRYPTION" << endl;
    // Encrypt
    c = publicKey.ApplyFunction(m);
    cout << "cipherthext: " << hex << c << endl << endl;

    cout << "DECRYPTION" << endl;
    // Decrypt
    r = privateKey.CalculateInverse(rng, c);
    cout << "plaintext: " << hex << r << endl;

    // Round trip the message
    size_t req = r.MinEncodedSize();
    recovered.resize(req);
    r.Encode((byte *)recovered.data(), recovered.size());

    cout << "recovered: " << recovered << endl; 

    return 0;
}

我很感激任何帮助。谢谢你。

4

1 回答 1

0

You can either

  1. Write two programs, each with their own main.
  2. Use the argvyou send into main to tell it what you want it to do.

For option 2, there is another question here. In essence, after checking the arg count, argc, and remembering argv[0] is your program, you could say

if(strcmp(argv[1], "ENCRYPTION")==0)
{
//... do ENCRYPTION
}...
于 2013-07-24T15:45:34.670 回答