不同程序中的加密和解密

Encryption and Decryption in Different Program

本文关键字:加密 解密 程序      更新时间:2023-10-16

我正试图在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;
}

我感谢你的帮助。非常感谢。

您可以选择

  1. 编写两个程序,每个程序都有自己的主程序
  2. 使用您发送到main的argv来告诉它您希望它做什么。

对于备选方案2,这里还有另一个问题。本质上,在检查了arg计数argc并记住argv[0]是您的程序之后,您可以说

if(strcmp(argv[1], "ENCRYPTION")==0)
{
//... do ENCRYPTION
}...