source: comparacioncriptosistemas/rsa/main.cpp @ fafd156

interfaz
Last change on this file since fafd156 was fafd156, checked in by aaraujo <aaraujo@…>, 8 years ago

Creado nuevo proyecto Qt para ejecutar las repeticiones de experimentos del algoritmo RSA.

  • Property mode set to 100644
File size: 5.8 KB
Line 
1#include <QCoreApplication>
2
3#include <QTime>
4#include <QElapsedTimer>
5#include <QFile>
6#include <QTextStream>
7
8#include <iostream>
9
10#include "crypto++/rsa.h"
11#include "crypto++/elgamal.h"
12#include "crypto++/osrng.h"
13#include <crypto++/files.h>
14
15
16
17/**
18 * Programa de Cryptopp para realizar estimaciones de ejecuciones del
19 * algoritmo RSA
20 *
21 * https://www.cryptopp.com/wiki/RSA_Cryptography
22 *
23 *
24 * Es necesario instalar los siguientes paquetes:
25 * libcrypto++9 y libcrypto++-dev
26 *
27 */
28
29using namespace CryptoPP;
30
31int main(int argc, char *argv[])
32{
33    QCoreApplication a(argc, argv);
34    //return a.exec();
35
36
37    ///////////////////////////////////////
38    // Pseudo Random Number Generator
39    AutoSeededRandomPool rng;
40
41    ///////////////////////////////////////
42    // Generate Parameters
43    //InvertibleRSAFunction params;
44
45    //QTime timer;
46    QElapsedTimer timer;
47
48    // prefijo del nombre del archivo con el texto a cifrar
49    QString messageFile = "message";
50
51    // iterar por el número de archivos (10)
52    for (int i = 1; i <= 2; i++)
53    {
54        messageFile.append(QString::number(i));
55
56        qDebug("generar archivo...");
57        // generar registros en archivo de texto
58        QString fileName = "registro-rsa-";
59        fileName.append(messageFile+"-");
60        fileName.append(QDateTime::currentDateTime().toString("dd.MM.yy.hh.mm.ss"));
61        fileName.append(".txt");
62
63        messageFile.append(".txt");
64
65        std::string s;
66        CryptoPP::FileSource file( qPrintable(messageFile), true, new StringSink( s ) );
67
68        //std::cout << s ;//<< std::endl;
69        //std::cout << s.size() << std::endl;
70
71        // archivo de salida de resultados
72        QFile registerFile(fileName);
73        if (registerFile.open(QFile::WriteOnly))
74        {
75            // flujo para el archivo de salida de resultados
76            QTextStream outFile(&registerFile);
77
78
79            // linea que mantiene los valores de tiempo
80            QString line;
81
82            // iterar 50 veces el proceso de cifrado y descifrado del texto
83            for (int j = 0; j < 50; j++)
84            {
85
86                qDebug("*************************************************");
87                InvertibleRSAFunction params;
88
89                timer.start();
90                params.GenerateRandomWithKeySize(rng, 4096);
91
92                int runtime = timer.elapsed(); //gets the runtime in ms
93                qDebug(qPrintable("key generation: "+QString::number(runtime)+" ms"));
94
95                line.append(QString::number(runtime));
96                line.append(" ");
97
98                ///////////////////////////////////////
99                // Create Keys
100                RSA::PrivateKey privateKey(params);
101                RSA::PublicKey publicKey(params);
102
103                SecByteBlock plaintext( (const unsigned char *) s.data(), s.size() );
104
105
106                ////////////////////////////////////////////////
107                // Encrypt
108                RSAES_OAEP_SHA_Encryptor encryptor( publicKey );
109
110                // Now that there is a concrete object, we can validate
111                assert( 0 != encryptor.FixedMaxPlaintextLength() );
112
113                //qDebug("encryptor.FixedMaxPlaintextLength(): %zu", encryptor.FixedMaxPlaintextLength());
114
115                // vale la pena leer la siguiente pregunta:
116                // https://stackoverflow.com/questions/2033809/im-using-crypto-for-rsa-encryption-my-plain-text-exceeds-fixedmaxplaintextle
117                //
118                // para RSA mas de 470 bytes hace que el asser que sigue falle
119                assert( plaintext.size() <= encryptor.FixedMaxPlaintextLength() );
120
121                // Create cipher text space
122                size_t ecl = encryptor.CiphertextLength( plaintext.size() );
123                assert( 0 != ecl );
124                SecByteBlock ciphertext( ecl );
125
126                timer.start();
127                encryptor.Encrypt( rng, plaintext, plaintext.size(), ciphertext );
128                runtime = timer.elapsed(); //gets the runtime in ms
129                qDebug(qPrintable("RSA encryption time: "+QString::number(runtime)+" ms"));
130
131                line.append(QString::number(runtime));
132                line.append(" ");
133
134
135                ////////////////////////////////////////////////
136                // Decrypt
137                RSAES_OAEP_SHA_Decryptor decryptor( privateKey );
138
139                // Now that there is a concrete object, we can check sizes
140                assert( 0 != decryptor.FixedCiphertextLength() );
141                assert( ciphertext.size() <= decryptor.FixedCiphertextLength() );
142
143                // Create recovered text space
144                size_t dpl = decryptor.MaxPlaintextLength( ciphertext.size() );
145                assert( 0 != dpl );
146                SecByteBlock recovered( dpl );
147
148                timer.start();
149                DecodingResult result = decryptor.Decrypt( rng, ciphertext, ciphertext.size(), recovered );
150                runtime = timer.elapsed(); //gets the runtime in ms
151                qDebug(qPrintable("RSA decryption time: "+QString::number(runtime)+" ms"));
152
153                line.append(QString::number(runtime));
154                line.append(" ");
155
156                // More sanity checks
157                assert( result.isValidCoding );
158                assert( result.messageLength <= decryptor.MaxPlaintextLength( ciphertext.size() ) );
159
160                // At this point, we can set the size of the recovered
161                //  data. Until decryption occurs (successfully), we
162                //  only know its maximum size
163                recovered.resize( result.messageLength );
164
165                // SecByteBlock is overloaded for proper results below
166                assert( plaintext == recovered );
167
168                std::cout << "Recovered plain text" << std::endl;
169
170
171                outFile << line << endl;
172                line = "";
173
174
175            }
176            messageFile = "message";
177        }
178
179    }
180
181    qDebug("salida");
182}
Note: See TracBrowser for help on using the repository browser.