Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 97 lines (80 sloc) 2.43 kb
f1904e89 » jake
2008-04-30 OAuth client/server lib
1 /*
2 Converts a private key or certificate in PEM format to a marshaled Cryptokit.RSA.key.
3
4 pem2cryptokit [--certificate] < file.pem > file.ocaml
5
6 Recover the marshaled key with e.g.
7
8 input_value (open_in "file.ocaml")
9 */
10
11 #include <stdio.h>
12 #include <string.h>
13
14 #include <openssl/rsa.h>
15 #include <openssl/evp.h>
16 #include <openssl/x509.h>
17 #include <openssl/pem.h>
18 #include <openssl/bn.h>
19
20 #include <caml/mlvalues.h>
21 #include <caml/memory.h>
22
23 CAMLextern void caml_startup_code(
24 code_t code, asize_t code_size,
25 char *data, asize_t data_size,
26 char *section_table, asize_t section_table_size,
27 char **argv);
28
29 typedef long (*primitive)();
30 primitive caml_builtin_cprim[] = { };
31 char *caml_names_of_builtin_cprim[] = {};
32 char global_data[] = {
33 /* need to stub out Out_of_memory global for caml_init_exceptions */
34 0x84, 0x95, 0xA6, 0xBE, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x1,
35 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x3, 0xA0, 0x40, 0x40
36 };
37
38 value val_bn(BIGNUM *bn) {
39 if (bn) {
40 value v = caml_alloc_string(BN_num_bytes(bn));
41 BN_bn2bin(bn, String_val(v));
42 return v;
43 }
44 else
45 caml_alloc_string(0);
46 }
47
48 value val_rsa(RSA *rsa) {
49 CAMLparam0 ();
50 CAMLlocal1 (ck_rsa);
51 ck_rsa = caml_alloc(8, 0);
52 Store_field(ck_rsa, 0, Val_int(BN_num_bits(rsa->n)));
53 Store_field(ck_rsa, 1, val_bn(rsa->n));
54 Store_field(ck_rsa, 2, val_bn(rsa->e));
55 Store_field(ck_rsa, 3, val_bn(rsa->d));
56 Store_field(ck_rsa, 4, val_bn(rsa->p));
57 Store_field(ck_rsa, 5, val_bn(rsa->q));
58 Store_field(ck_rsa, 6, val_bn(rsa->dmp1));
59 Store_field(ck_rsa, 7, val_bn(rsa->dmq1));
60 Store_field(ck_rsa, 8, val_bn(rsa->iqmp));
61 CAMLreturn (ck_rsa);
62 }
63
64 int main(int argc, char **argv)
65 {
66 RSA *rsa = NULL;
67 EVP_PKEY *pkey = NULL;
68 X509 *x = NULL;
69
70 caml_startup_code(NULL, 0, global_data, sizeof global_data, NULL, 0, 0);
71
72 if (argc > 1 && strcmp(argv[1], "--certificate") == 0)
73 {
74 x = PEM_read_X509_AUX(stdin,NULL,NULL,NULL);
75 if (x)
76 pkey = X509_get_pubkey(x);
77 }
78 else
79 pkey = PEM_read_PrivateKey(stdin,NULL,NULL,NULL);
80
81 if (pkey)
82 rsa = EVP_PKEY_get1_RSA(pkey);
83
84 if (rsa) {
85 value ck_rsa;
86 char **buf;
87 int len;
88
89 ck_rsa = val_rsa(rsa);
90 caml_output_value_to_malloc(ck_rsa, Val_emptylist, &buf, &len);
91 write(1, buf, len);
92 }
93 else
94 fprintf(stderr, "Error reading PEM file; check with 'openssl rsa' or 'openssl x509'\n");
95
96 return 0;
97 }
Something went wrong with that request. Please try again.