File: ec.c

package info (click to toggle)
jose 14-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,884 kB
  • sloc: ansic: 10,235; javascript: 987; sh: 586; makefile: 9
file content (83 lines) | stat: -rw-r--r-- 2,165 bytes parent folder | download | duplicates (2)
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
/* vim: set tabstop=8 shiftwidth=4 softtabstop=4 expandtab smarttab colorcolumn=80: */
/*
 * Copyright 2016 Red Hat, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "misc.h"
#include "../hooks.h"
#include <jose/openssl.h>

#include <string.h>

declare_cleanup(EC_KEY)

static bool
jwk_make_handles(jose_cfg_t *cfg, const json_t *jwk)
{
    const char *kty = NULL;

    if (json_unpack((json_t *) jwk, "{s:s}", "kty", &kty) == -1)
        return false;

    return strcmp(kty, "EC") == 0;
}

static bool
jwk_make_execute(jose_cfg_t *cfg, json_t *jwk)
{
    openssl_auto(EC_KEY) *key = NULL;
    const char *crv = "P-256";
    json_auto_t *out = NULL;
    int nid = NID_undef;

    if (!jwk_make_handles(cfg, jwk))
        return false;

    if (json_unpack(jwk, "{s?s}", "crv", &crv) < 0)
        return false;

    switch (str2enum(crv, "P-256", "P-384", "P-521", "secp256k1", NULL)) {
    case 0: nid = NID_X9_62_prime256v1; break;
    case 1: nid = NID_secp384r1; break;
    case 2: nid = NID_secp521r1; break;
    case 3: nid = NID_secp256k1; break;
    default: return false;
    }

    key = EC_KEY_new_by_curve_name(nid);
    if (!key)
        return false;

    if (EC_KEY_generate_key(key) <= 0)
        return false;

    out = jose_openssl_jwk_from_EC_KEY(cfg, key);
    if (!out)
        return false;

    return copy_val(out, jwk, "crv", "x", "y", "d", NULL);
}

static void __attribute__((constructor))
constructor(void)
{
    static jose_hook_jwk_t jwk = {
        .kind = JOSE_HOOK_JWK_KIND_MAKE,
        .make.handles = jwk_make_handles,
        .make.execute = jwk_make_execute
    };

    jose_hook_jwk_push(&jwk);
}