summaryrefslogtreecommitdiff
path: root/sys/src/cmd/auth/rsa2jwk.c
blob: 606c1473b3dddebdf976e7fb085600c9e6791544 (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
#include <u.h>
#include <libc.h>
#include <auth.h>
#include <mp.h>
#include <libsec.h>
#include "rsa2any.h"

#define between(x,min,max)	(((min-1-x) & (x-max-1))>>8)

int
encurl64chr(int o)
{
	int c;

	c  = between(o,  0, 25) & ('A'+o);
	c |= between(o, 26, 51) & ('a'+(o-26));
	c |= between(o, 52, 61) & ('0'+(o-52));
	c |= between(o, 62, 62) & ('-');
	c |= between(o, 63, 63) & ('_');
	return c;
}

char*
encurl64(void *in, int n)
{
	int lim;
	char *out, *p;

	lim = 4*n/3 + 5;
	if((out = malloc(lim)) == nil)
		sysfatal("malloc: %r");
	enc64x(out, lim, in, n, encurl64chr);
	if((p = strchr(out, '=')) != nil)
		*p = 0;
	return out;
}

void
usage(void)
{
	fprint(2, "usage: auth/rsa2pub [file]\n");
	exits("usage");
}

void
main(int argc, char **argv)
{
	uchar nbuf[8192], ebuf[512];
	char *nstr, *estr;
	RSApriv *k;
	int nlen, elen;

	fmtinstall('[', encodefmt);
	quotefmtinstall();

	ARGBEGIN{
	default:
		usage();
	}ARGEND

	if(argc > 1)
		usage();

	if((k = getrsakey(argc, argv, 0, nil)) == nil)
		sysfatal("%r");

	nlen = (mpsignif(k->pub.n)+7)/8;
	if(nlen >= sizeof(nbuf))
		sysfatal("key too big");
	mptobe(k->pub.n, nbuf, nlen, nil);
	nstr = encurl64(nbuf, nlen);

	elen = (mpsignif(k->pub.ek)+7)/8;
	if(elen >= sizeof(ebuf))
		sysfatal("key too big");
	mptobe(k->pub.ek, ebuf, elen, nil);
	estr = encurl64(ebuf, elen);

	print(
		"{"
		"\"kty\": \"RSA\","
		"\"n\": \"%s\","
		"\"e\": \"%s\""
		"}\n",
		nstr, estr);
	exits(nil);
}