如何使用Botan执行非对称加密

use*_*869 0 c++ qt rsa encryption-asymmetric botan

我正在使用Botan生成哈希,用aes 256执行加密,现在我想用它执行非对称加密.阅读本页:http://botan.randombit.net/pubkey.html 我创建了一个代码来生成RSA加密的公钥和私钥,但我不明白如何加密和解密数据,有人可以帮助我吗?我正在使用Botan 1.8.8 2009-11-03.

void generatekey()
{
    LibraryInitializer init;

    std::ostringstream pub;
    std::ostringstream priv;

    int bits = 1024;

    AutoSeeded_RNG rng;

    RSA_PrivateKey key(rng, bits);
    pub << X509::PEM_encode(key);
    priv << PKCS8::PEM_encode(key);

    qDebug() << QString(pub.str().c_str());
    qDebug() << QString(priv.str().c_str());
}
Run Code Online (Sandbox Code Playgroud)

use*_*869 7

在阅读了一些教程后,我将此代码写入非对称加密.

#include <QDebug>
#include <botan/botan.h>
#include <botan/rsa.h>
#include <botan/look_pk.h>

using namespace Botan;

void encryptdata()
{
    try
    {
        QString text = "abc";

        LibraryInitializer init;

        AutoSeeded_RNG rng;

        RSA_PrivateKey key(rng, 1024);

        std::string pub = X509::PEM_encode(key);

        std::string priv = PKCS8::PEM_encode(key);

        DataSource_Memory key_pub(pub);

        DataSource_Memory key_priv(priv);

        X509_PublicKey *pub_rsa = X509::load_key(key_pub);

        PKCS8_PrivateKey *priv_rsa = PKCS8::load_key(key_priv, rng);

        PK_Encrypting_Key *enckey = dynamic_cast<PK_Encrypting_Key*>(pub_rsa);

        PK_Decrypting_Key *deckey = dynamic_cast<PK_Decrypting_Key*>(priv_rsa);

        PK_Encryptor *enc = get_pk_encryptor(*enckey, "EME1(SHA-256)");

        PK_Decryptor *dec = get_pk_decryptor(*deckey, "EME1(SHA-256)");

        QByteArray array = text.toLatin1();

        byte msgtoencrypt[array.count()];

        for (int i = 0; i < array.count(); i++)
        {
            msgtoencrypt[i] = array[i];
        }

        SecureVector<byte> ciphertext = enc->encrypt(msgtoencrypt, sizeof(msgtoencrypt), rng);

        SecureVector<byte> plaintext = dec->decrypt(ciphertext, ciphertext.size());

        QByteArray encrypted;

        for (uint i = 0; i < ciphertext.size(); i++)
        {
            encrypted[i] = ciphertext[i];
        }

        QByteArray result;

        for (uint i = 0; i < plaintext.size(); i++)
        {
            result[i] = plaintext[i];
        }

        if (array == result)
        {
            qDebug() << "Ok";
        }
        else
        {
            qDebug() << "Error";
        }

        qDebug() << QString(encrypted);
        qDebug() << QString(array);
        qDebug() << QString(result);
    }
    catch(std::exception &e)
    {
        qDebug() << e.what();
    }
}
Run Code Online (Sandbox Code Playgroud)