summaryrefslogtreecommitdiff
path: root/other/guess-who/keygen.cc
blob: 3e2af93d3e5283c6a14cbabd2aa6c32848997216 (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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/* Key generator for rsa keys (SSH2!)
 * (C) 2002 Sebastian Krahmer.
 * WARNING: theres no random is the keys, so
 * THE GENERATED KEYS ARE WEAK! Do not use it to
 * generate your pubkeys, this program is for debugging only.
 */ 
#include <stdio.h>
#include <sys/types.h>
#include <netinet/in.h>

extern "C" {
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/bn.h>
#include <openssl/evp.h>
}

#include <string.h>

#include "base64.h"
#include "misc.h"


int rsa2blob(RSA *key, unsigned char *buf, size_t buflen)
{
	size_t blen = buflen;
	int h;
	unsigned char *tmp;

	if (blen < 4)
		return -1;

	if (key->e->neg || key->n->neg)
		printf("AAA");

	size_t l = strlen("ssh-rsa");
	unsigned char *ptr = buf;
	*(unsigned int*)ptr = htonl(l);
	ptr += 4; blen -= 4;
	if (blen < l)
		return -1;
	memcpy(ptr, "ssh-rsa", l); // HAH! 
	ptr += l; blen -= l;

	unsigned int n = BN_num_bytes(key->e);
	if (blen < n+1+4)
		return -1;

	tmp = new unsigned char [n];
	BN_bn2bin(key->e, tmp);
	h = (tmp[0] & 0x80) ? 1 : 0;
	*(unsigned int*)ptr = htonl(n+h);
	ptr += 4; blen -= 4;
	*ptr = 0;
	memcpy(ptr+h, tmp, n);
	ptr += n; blen -= n;
	ptr += h; blen -= h;
	delete [] tmp;

	n = BN_num_bytes(key->n);
	if (blen < n+1+4)
		return -1;

	tmp = new unsigned char [n];
	BN_bn2bin(key->n, tmp);
	h = (tmp[0] & 0x80) ? 1 : 0;
	*(unsigned int*)ptr = htonl(n+h);
	ptr += 4; blen -= 4;
	*ptr = 0;
	memcpy(ptr+h, tmp, n);
	ptr += n; blen -= n;
	ptr += h; blen -= h;
	delete [] tmp;

	return ptr-buf;
}


int main(int argc, char **argv)
{

	if (argc < 3) {
		fprintf(stderr, "Usage: %s <bits> <privfile> <pubfile>\n",
		        *argv);
		return -1;
	}

	RSA *r;
	int bits = atoi(argv[1]);
	r = RSA_generate_key(bits, 35, NULL, NULL);

	FILE *f = fopen(argv[2], "w");
	if (!f)
		die("fopen");

	PEM_write_RSAPrivateKey(f, r, NULL, NULL, 0, NULL, NULL);
	fclose(f);

	unsigned char key_string[1024];
	char uu_key_string[2049];
	memset(uu_key_string, 0, sizeof(uu_key_string));
	memset(key_string, 0, sizeof(key_string));

	int n = rsa2blob(r, key_string, sizeof(key_string));
	printf("%d\n", n);
	if (n < 0)
		die("Not enough memory to store key.");
	b64_ntop(key_string, n, uu_key_string, 2*n);

	f = fopen(argv[3], "w");
	if (!f)
		die("fopen");

	fprintf(f, "ssh-rsa %s icke@dort\n", uu_key_string);
	fclose(f);

	return 0;
}