为什么Crypto++认为我的消息比实际情况更大

Why does Crypto++ think my messages are larger than they are?

本文关键字:实际情况 消息 我的 Crypto++ 为什么      更新时间:2023-10-16

我正在使用C++的Crypto++库,用磁盘上的128位消息的公钥和私钥对其进行加密。然而,当我调用我的函数时,程序终止,并显示错误消息:

抛出的实例后调用的terminate"CryptoPP::InvalidArgument"what():RSA/OAEP-MGF1(SHA-1):消息256的长度超过了该公钥的最大值214

我不知道为什么它认为我的消息是256位的,而它们显然是128位的。以下是我的代码:

std::string encryptWithBothKeys(std::string key_name1, std::string key_name2, std::string plain){
    std::string cipher1, cipher2;
    AutoSeededRandomPool rng;
    RSA::PublicKey pub_key;
    RSA::PrivateKey priv_key;
    loadPublicKey(key_name1, pub_key);
    loadPrivateKey(key_name2, priv_key);
    RSAES_OAEP_SHA_Encryptor e_pub(pub_key);
    RSAES_OAEP_SHA_Encryptor e_priv(priv_key);
    StringSource ss1(plain, true,
      new PK_EncryptorFilter(rng, e_pub,
        new StringSink(cipher1)
      )
    );
    StringSource ss2(cipher1, true,
      new PK_EncryptorFilter(rng, e_priv,
        new StringSink(cipher2)
      )
    );
    return cipher2;
}
void load(const std::string& filename, BufferedTransformation& bt){
  FileSource file(filename.c_str(), true /*pumpAll*/);
  file.TransferTo(bt);
  bt.MessageEnd();
}
void loadPrivateKey(const std::string& filename, PrivateKey& key){
  ByteQueue queue;
  load(filename, queue);
  key.Load(queue);  
}
void loadPublicKey(const std::string& filename, PublicKey& key){
  ByteQueue queue;
  load(filename, queue);
  key.Load(queue);  
}

在主函数中,我这样称呼它:

std::string encrypted_msg = encryptWithBothKeys("their.pub", "my.key", "0123456789ABCDEF");

有什么建议吗?

编辑:第一次加密后的密文大小为256。我想我需要弄清楚为什么它的尺寸越来越大。

我不知道为什么它认为我的消息是256位的,而它们显然是128位的。以下是我的代码:

这些是字节,而不是位。

您使用的RSA模数大小是多少?我猜它是一个2048位的密钥,即256字节,由于OAEP填充,剩下≈214字节。

因此,问题变成了,在期间,plaincipher1的大小是多少

StringSource ss1(plain, true,
  new PK_EncryptorFilter(rng, e_pub,
    new StringSink(cipher1)
  )
);

我猜想plain1已经足够小了。然而,当它被填充和加密时,它会扩展到256字节作为cipher1。因此,执行此操作时消息cipher1太大:

StringSource ss2(cipher1, true,
  new PK_EncryptorFilter(rng, e_priv,
    new StringSink(cipher2)
  )
);

此外,以上是否应使用PK_DecryptorFilter?你确定要再次加密吗?如果是,那么为什么要使用e_priv

使用私钥加密不是有效的加密操作。如果你想要"用私钥加密",这通常意味着你想要一个带恢复的概率签名方案(PSSR)。Crypto++提供了其中的几个。