1 | #include<qfile.h>
|
---|
2 | #include<qfileinfo.h>
|
---|
3 | #include"qca.h"
|
---|
4 | #include<stdio.h>
|
---|
5 |
|
---|
6 | //#define USE_FILE
|
---|
7 |
|
---|
8 | QCA::RSAKey readKeyFile(const QString &name)
|
---|
9 | {
|
---|
10 | QCA::RSAKey k;
|
---|
11 | QFile f(name);
|
---|
12 | if(!f.open(IO_ReadOnly)) {
|
---|
13 | printf("Unable to open %s\n", name.latin1());
|
---|
14 | return k;
|
---|
15 | }
|
---|
16 | QByteArray der = f.readAll();
|
---|
17 | f.close();
|
---|
18 | printf("Read %s [%d bytes]\n", name.latin1(), der.size());
|
---|
19 |
|
---|
20 | if(!k.fromDER(der)) {
|
---|
21 | printf("%s: Error importing DER format.\n", name.latin1());
|
---|
22 | return k;
|
---|
23 | }
|
---|
24 | char *yes = "yes";
|
---|
25 | char *no = "no";
|
---|
26 | printf("Successfully imported %s (enc=%s, dec=%s)\n",
|
---|
27 | name.latin1(),
|
---|
28 | k.havePublic() ? yes : no,
|
---|
29 | k.havePrivate() ? yes : no);
|
---|
30 |
|
---|
31 | printf("Converting to DER: %d bytes\n", k.toDER().size());
|
---|
32 | printf("Converting to PEM:\n%s\n", k.toPEM().latin1());
|
---|
33 | return k;
|
---|
34 | }
|
---|
35 |
|
---|
36 | int main(int argc, char **argv)
|
---|
37 | {
|
---|
38 | QCA::init();
|
---|
39 | QCString cs = (argc >= 2) ? argv[1] : "hello";
|
---|
40 |
|
---|
41 | if(!QCA::isSupported(QCA::CAP_RSA))
|
---|
42 | printf("RSA not supported!\n");
|
---|
43 | else {
|
---|
44 | #ifdef USE_FILE
|
---|
45 | QCA::RSAKey pubkey = readKeyFile("keypublic.der");
|
---|
46 | if(pubkey.isNull())
|
---|
47 | return 1;
|
---|
48 | QCA::RSAKey seckey = readKeyFile("keyprivate.der");
|
---|
49 | if(seckey.isNull())
|
---|
50 | return 1;
|
---|
51 | #else
|
---|
52 | QCA::RSAKey seckey = QCA::RSA::generateKey(1024);
|
---|
53 | if(seckey.isNull())
|
---|
54 | return 1;
|
---|
55 | QCA::RSAKey pubkey = seckey;
|
---|
56 | #endif
|
---|
57 | // encrypt some data
|
---|
58 | QByteArray a(cs.length());
|
---|
59 | memcpy(a.data(), cs.data(), a.size());
|
---|
60 |
|
---|
61 | QCA::RSA op;
|
---|
62 | op.setKey(pubkey);
|
---|
63 | QByteArray result;
|
---|
64 | if(!op.encrypt(a, &result)) {
|
---|
65 | printf("Error encrypting.\n");
|
---|
66 | return 1;
|
---|
67 | }
|
---|
68 | QString rstr = QCA::arrayToHex(result);
|
---|
69 | printf(">rsa(\"%s\") = [%s]\n", cs.data(), rstr.latin1());
|
---|
70 |
|
---|
71 | // now decrypt it
|
---|
72 | op.setKey(seckey);
|
---|
73 | QByteArray dec;
|
---|
74 | if(!op.decrypt(result, &dec)) {
|
---|
75 | printf("Error decrypting.\n");
|
---|
76 | return 1;
|
---|
77 | }
|
---|
78 | QCString dstr;
|
---|
79 | dstr.resize(dec.size()+1);
|
---|
80 | memcpy(dstr.data(), dec.data(), dec.size());
|
---|
81 | printf("<rsa(\"%s\") = [%s]\n", rstr.latin1(), dstr.data());
|
---|
82 | }
|
---|
83 |
|
---|
84 | return 0;
|
---|
85 | }
|
---|
86 |
|
---|