summaryrefslogtreecommitdiffstats
path: root/examples/rsatest/rsatest.cpp
blob: bd513fd43b812000697e2b3e2cb132027eed871c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include<tqfile.h>
#include<tqfileinfo.h>
#include"qca.h"
#include<stdio.h>

//#define USE_FILE

TQCA::RSAKey readKeyFile(const TQString &name)
{
	TQCA::RSAKey k;
	TQFile f(name);
	if(!f.open(IO_ReadOnly)) {
		printf("Unable to open %s\n", name.latin1());
		return k;
	}
	TQByteArray der = f.readAll();
	f.close();
	printf("Read %s [%d bytes]\n", name.latin1(), der.size());

	if(!k.fromDER(der)) {
		printf("%s: Error importing DER format.\n", name.latin1());
		return k;
	}
	char *yes = "yes";
	char *no = "no";
	printf("Successfully imported %s (enc=%s, dec=%s)\n",
		name.latin1(),
		k.havePublic() ? yes : no,
		k.havePrivate() ? yes : no);

	printf("Converting to DER: %d bytes\n", k.toDER().size());
	printf("Converting to PEM:\n%s\n", k.toPEM().latin1());
	return k;
}

int main(int argc, char **argv)
{
	TQCA::init();
	TQCString cs = (argc >= 2) ? argv[1] : "hello";

	if(!TQCA::isSupported(TQCA::CAP_RSA))
		printf("RSA not supported!\n");
	else {
#ifdef USE_FILE
		TQCA::RSAKey pubkey = readKeyFile("keypublic.der");
		if(pubkey.isNull())
			return 1;
		TQCA::RSAKey seckey = readKeyFile("keyprivate.der");
		if(seckey.isNull())
			return 1;
#else
		TQCA::RSAKey seckey = TQCA::RSA::generateKey(1024);
		if(seckey.isNull())
			return 1;
		TQCA::RSAKey pubkey = seckey;
#endif
		// encrypt some data
		TQByteArray a(cs.length());
		memcpy(a.data(), cs.data(), a.size());

		TQCA::RSA op;
		op.setKey(pubkey);
		TQByteArray result;
		if(!op.encrypt(a, &result)) {
			printf("Error encrypting.\n");
			return 1;
		}
		TQString rstr = TQCA::arrayToHex(result);
		printf(">rsa(\"%s\") = [%s]\n", cs.data(), rstr.latin1());

		// now decrypt it
		op.setKey(seckey);
		TQByteArray dec;
		if(!op.decrypt(result, &dec)) {
			printf("Error decrypting.\n");
			return 1;
		}
		TQCString dstr;
		dstr.resize(dec.size()+1);
		memcpy(dstr.data(), dec.data(), dec.size());
		printf("<rsa(\"%s\") = [%s]\n", rstr.latin1(), dstr.data());
	}

	return 0;
}