繁体   English   中英

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

[英]How to perform asymmetric encryption with 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());
}

阅读一些教程后,我将此代码编写为非对称加密。

#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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM