]> git.lizzy.rs Git - plan9front.git/blob - sys/src/cmd/auth/rsa2jwk.c
auth/rsa2jwk: add code to produce jwk rsa keys
[plan9front.git] / sys / src / cmd / auth / rsa2jwk.c
1 #include <u.h>
2 #include <libc.h>
3 #include <auth.h>
4 #include <mp.h>
5 #include <libsec.h>
6 #include "rsa2any.h"
7
8 #define between(x,min,max)      (((min-1-x) & (x-max-1))>>8)
9
10 int
11 encurl64chr(int o)
12 {
13         int c;
14
15         c  = between(o,  0, 25) & ('A'+o);
16         c |= between(o, 26, 51) & ('a'+(o-26));
17         c |= between(o, 52, 61) & ('0'+(o-52));
18         c |= between(o, 62, 62) & ('-');
19         c |= between(o, 63, 63) & ('_');
20         return c;
21 }
22
23 char*
24 encurl64(void *in, int n)
25 {
26         int lim;
27         char *out, *p;
28
29         lim = 4*n/3 + 5;
30         if((out = malloc(lim)) == nil)
31                 sysfatal("malloc: %r");
32         enc64x(out, lim, in, n, encurl64chr);
33         if((p = strchr(out, '=')) != nil)
34                 *p = 0;
35         return out;
36 }
37
38 void
39 usage(void)
40 {
41         fprint(2, "usage: auth/rsa2pub [file]\n");
42         exits("usage");
43 }
44
45 void
46 main(int argc, char **argv)
47 {
48         uchar nbuf[8192], ebuf[512];
49         char *nstr, *estr;
50         RSApriv *k;
51         int nlen, elen;
52
53         fmtinstall('[', encodefmt);
54         quotefmtinstall();
55
56         ARGBEGIN{
57         default:
58                 usage();
59         }ARGEND
60
61         if(argc > 1)
62                 usage();
63
64         if((k = getrsakey(argc, argv, 0, nil)) == nil)
65                 sysfatal("%r");
66
67         nlen = (mpsignif(k->pub.n)+7)/8;
68         if(nlen >= sizeof(nbuf))
69                 sysfatal("key too big");
70         mptobe(k->pub.n, nbuf, nlen, nil);
71         nstr = encurl64(nbuf, nlen);
72
73         elen = (mpsignif(k->pub.ek)+7)/8;
74         if(elen >= sizeof(ebuf))
75                 sysfatal("key too big");
76         mptobe(k->pub.ek, ebuf, elen, nil);
77         estr = encurl64(ebuf, elen);
78
79         print(
80                 "{"
81                 "\"kty\": \"RSA\","
82                 "\"n\": \"%s\","
83                 "\"e\": \"%s\""
84                 "}\n",
85                 nstr, estr);
86         exits(nil);
87 }