Added support code for RSA and EC key encoding (including reconstruction of all public and private key elements from the private key structure), with raw and PKCS#8 formats, both in DER and PEM.

This commit is contained in:
Thomas Pornin 2018-08-06 00:02:36 +02:00
parent cfbc702d3d
commit d8fa415fca
32 changed files with 3528 additions and 105 deletions

173
src/codec/pemenc.c Normal file
View file

@ -0,0 +1,173 @@
/*
* Copyright (c) 2018 Thomas Pornin <pornin@bolet.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "inner.h"
/*
* Get the appropriate Base64 character for a numeric value in the
* 0..63 range. This is constant-time.
*/
static char
b64char(uint32_t x)
{
/*
* Values 0 to 25 map to 0x41..0x5A ('A' to 'Z')
* Values 26 to 51 map to 0x61..0x7A ('a' to 'z')
* Values 52 to 61 map to 0x30..0x39 ('0' to '9')
* Value 62 maps to 0x2B ('+')
* Value 63 maps to 0x2F ('/')
*/
uint32_t a, b, c;
a = x - 26;
b = x - 52;
c = x - 62;
/*
* Looking at bits 8..15 of values a, b and c:
*
* x a b c
* ---------------------
* 0..25 FF FF FF
* 26..51 00 FF FF
* 52..61 00 00 FF
* 62..63 00 00 00
*/
return (char)(((x + 0x41) & ((a & b & c) >> 8))
| ((x + (0x61 - 26)) & ((~a & b & c) >> 8))
| ((x - (52 - 0x30)) & ((~a & ~b & c) >> 8))
| ((0x2B + ((x & 1) << 2)) & (~(a | b | c) >> 8)));
}
/* see bearssl_pem.h */
size_t
br_pem_encode(void *dest, const void *data, size_t len,
const char *banner, unsigned flags)
{
size_t dlen, banner_len, lines;
char *d;
unsigned char *buf;
size_t u;
int off, lim;
banner_len = strlen(banner);
/* FIXME: try to avoid divisions here, as they may pull
an extra libc function. */
if ((flags & BR_PEM_LINE64) != 0) {
lines = (len + 47) / 48;
} else {
lines = (len + 56) / 57;
}
dlen = (banner_len << 1) + 30 + (((len + 2) / 3) << 2)
+ lines + 2;
if ((flags & BR_PEM_CRLF) != 0) {
dlen += lines + 2;
}
if (dest == NULL) {
return dlen;
}
d = dest;
/*
* We always move the source data to the end of output buffer;
* the encoding process never "catches up" except at the very
* end. This also handles all conditions of partial or total
* overlap.
*/
buf = (unsigned char *)d + dlen - len;
memmove(buf, data, len);
memcpy(d, "-----BEGIN ", 11);
d += 11;
memcpy(d, banner, banner_len);
d += banner_len;
memcpy(d, "-----", 5);
d += 5;
if ((flags & BR_PEM_CRLF) != 0) {
*d ++ = 0x0D;
}
*d ++ = 0x0A;
off = 0;
lim = (flags & BR_PEM_LINE64) != 0 ? 16 : 19;
for (u = 0; (u + 2) < len; u += 3) {
uint32_t w;
w = ((uint32_t)buf[u] << 16)
| ((uint32_t)buf[u + 1] << 8)
| (uint32_t)buf[u + 2];
*d ++ = b64char(w >> 18);
*d ++ = b64char((w >> 12) & 0x3F);
*d ++ = b64char((w >> 6) & 0x3F);
*d ++ = b64char(w & 0x3F);
if (++ off == lim) {
off = 0;
if ((flags & BR_PEM_CRLF) != 0) {
*d ++ = 0x0D;
}
*d ++ = 0x0A;
}
}
if (u < len) {
uint32_t w;
w = (uint32_t)buf[u] << 16;
if (u + 1 < len) {
w |= (uint32_t)buf[u + 1] << 8;
}
*d ++ = b64char(w >> 18);
*d ++ = b64char((w >> 12) & 0x3F);
if (u + 1 < len) {
*d ++ = b64char((w >> 6) & 0x3F);
} else {
*d ++ = 0x3D;
}
*d ++ = 0x3D;
off ++;
}
if (off != 0) {
if ((flags & BR_PEM_CRLF) != 0) {
*d ++ = 0x0D;
}
*d ++ = 0x0A;
}
memcpy(d, "-----END ", 9);
d += 9;
memcpy(d, banner, banner_len);
d += banner_len;
memcpy(d, "-----", 5);
d += 5;
if ((flags & BR_PEM_CRLF) != 0) {
*d ++ = 0x0D;
}
*d ++ = 0x0A;
/* Final zero, not counted in returned length. */
*d ++ = 0x00;
return dlen;
}

86
src/ec/ec_keygen.c Normal file
View file

@ -0,0 +1,86 @@
/*
* Copyright (c) 2018 Thomas Pornin <pornin@bolet.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "inner.h"
/* see bearssl_ec.h */
size_t
br_ec_keygen(const br_prng_class **rng_ctx,
const br_ec_impl *impl, br_ec_private_key *sk,
void *kbuf, int curve)
{
const unsigned char *order;
unsigned char *buf;
size_t len;
unsigned mask;
if (curve < 0 || curve >= 32
|| ((impl->supported_curves >> curve) & 1) == 0)
{
return 0;
}
order = impl->order(curve, &len);
while (len > 0 && *order == 0) {
order ++;
len --;
}
if (kbuf == NULL || len == 0) {
return len;
}
mask = order[0];
mask |= (mask >> 1);
mask |= (mask >> 2);
mask |= (mask >> 4);
/*
* We generate sequences of random bits of the right size, until
* the value is strictly lower than the curve order (we also
* check for all-zero values, which are invalid).
*/
buf = kbuf;
for (;;) {
size_t u;
unsigned cc, zz;
(*rng_ctx)->generate(rng_ctx, buf, len);
buf[0] &= mask;
cc = 0;
u = len;
zz = 0;
while (u -- > 0) {
cc = ((unsigned)(buf[u] - order[u] - cc) >> 8) & 1;
zz |= buf[u];
}
if (cc != 0 && zz != 0) {
break;
}
}
if (sk != NULL) {
sk->curve = curve;
sk->x = buf;
sk->xlen = len;
}
return len;
}

85
src/ec/ec_pubkey.c Normal file
View file

@ -0,0 +1,85 @@
/*
* Copyright (c) 2018 Thomas Pornin <pornin@bolet.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "inner.h"
static const unsigned char POINT_LEN[] = {
0, /* 0: not a valid curve ID */
43, /* sect163k1 */
43, /* sect163r1 */
43, /* sect163r2 */
51, /* sect193r1 */
51, /* sect193r2 */
61, /* sect233k1 */
61, /* sect233r1 */
61, /* sect239k1 */
73, /* sect283k1 */
73, /* sect283r1 */
105, /* sect409k1 */
105, /* sect409r1 */
145, /* sect571k1 */
145, /* sect571r1 */
41, /* secp160k1 */
41, /* secp160r1 */
41, /* secp160r2 */
49, /* secp192k1 */
49, /* secp192r1 */
57, /* secp224k1 */
57, /* secp224r1 */
65, /* secp256k1 */
65, /* secp256r1 */
97, /* secp384r1 */
133, /* secp521r1 */
65, /* brainpoolP256r1 */
97, /* brainpoolP384r1 */
129, /* brainpoolP512r1 */
32, /* curve25519 */
56, /* curve448 */
};
/* see bearssl_ec.h */
size_t
br_ec_compute_pub(const br_ec_impl *impl, br_ec_public_key *pk,
void *kbuf, const br_ec_private_key *sk)
{
int curve;
size_t len;
curve = sk->curve;
if (curve < 0 || curve >= 32 || curve >= (int)(sizeof POINT_LEN)
|| ((impl->supported_curves >> curve) & 1) == 0)
{
return 0;
}
if (kbuf == NULL) {
return POINT_LEN[curve];
}
len = impl->mulgen(kbuf, sk->x, sk->xlen, curve);
if (pk != NULL) {
pk->curve = curve;
pk->q = kbuf;
pk->qlen = len;
}
return len;
}

View file

@ -1973,8 +1973,8 @@ void br_mgf1_xor(void *data, size_t len,
* implementations.
*/
uint32_t br_rsa_i31_keygen_inner(const br_prng_class **rng,
br_rsa_private_key *sk, unsigned char *kbuf_priv,
br_rsa_public_key *pk, unsigned char *kbuf_pub,
br_rsa_private_key *sk, void *kbuf_priv,
br_rsa_public_key *pk, void *kbuf_pub,
unsigned size, uint32_t pubexp, br_i31_modpow_opt_type mp31);
/* ==================================================================== */
@ -2027,6 +2027,72 @@ void br_ecdsa_i31_bits2int(uint32_t *x,
void br_ecdsa_i15_bits2int(uint16_t *x,
const void *src, size_t len, uint32_t ebitlen);
/* ==================================================================== */
/*
* ASN.1 support functions.
*/
/*
* A br_asn1_uint structure contains encoding information about an
* INTEGER nonnegative value: pointer to the integer contents (unsigned
* big-endian representation), length of the integer contents,
* and length of the encoded value. The data shall have minimal length:
* - If the integer value is zero, then 'len' must be zero.
* - If the integer value is not zero, then data[0] must be non-zero.
*
* Under these conditions, 'asn1len' is necessarily equal to either len
* or len+1.
*/
typedef struct {
const unsigned char *data;
size_t len;
size_t asn1len;
} br_asn1_uint;
/*
* Given an encoded integer (unsigned big-endian, with possible leading
* bytes of value 0), returned the "prepared INTEGER" structure.
*/
br_asn1_uint br_asn1_uint_prepare(const void *xdata, size_t xlen);
/*
* Encode an ASN.1 length. The length of the encoded length is returned.
* If 'dest' is NULL, then no encoding is performed, but the length of
* the encoded length is still computed and returned.
*/
size_t br_asn1_encode_length(void *dest, size_t len);
/*
* Convenient macro for computing lengths of lengths.
*/
#define len_of_len(len) br_asn1_encode_length(NULL, len)
/*
* Encode a (prepared) ASN.1 INTEGER. The encoded length is returned.
* If 'dest' is NULL, then no encoding is performed, but the length of
* the encoded integer is still computed and returned.
*/
size_t br_asn1_encode_uint(void *dest, br_asn1_uint pp);
/*
* Get the OID that identifies an elliptic curve. Returned value is
* the DER-encoded OID, with the length (always one byte) but without
* the tag. Thus, the first byte of the returned buffer contains the
* number of subsequent bytes in the value. If the curve is not
* recognised, NULL is returned.
*/
const unsigned char *br_get_curve_OID(int curve);
/*
* Inner function for EC private key encoding. This is equivalent to
* the API function br_encode_ec_raw_der(), except for an extra
* parameter: if 'include_curve_oid' is zero, then the curve OID is
* _not_ included in the output blob (this is for PKCS#8 support).
*/
size_t br_encode_ec_raw_der_inner(void *dest,
const br_ec_private_key *sk, const br_ec_public_key *pk,
int include_curve_oid);
/* ==================================================================== */
/*
* SSL/TLS support functions.

View file

@ -0,0 +1,36 @@
/*
* Copyright (c) 2018 Thomas Pornin <pornin@bolet.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "inner.h"
/* see bearssl_rsa.h */
br_rsa_compute_modulus
br_rsa_compute_modulus_get_default(void)
{
#if BR_LOMUL
return &br_rsa_i15_compute_modulus;
#else
return &br_rsa_i31_compute_modulus;
#endif
}

View file

@ -0,0 +1,36 @@
/*
* Copyright (c) 2018 Thomas Pornin <pornin@bolet.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "inner.h"
/* see bearssl_rsa.h */
br_rsa_compute_privexp
br_rsa_compute_privexp_get_default(void)
{
#if BR_LOMUL
return &br_rsa_i15_compute_privexp;
#else
return &br_rsa_i31_compute_privexp;
#endif
}

View file

@ -0,0 +1,36 @@
/*
* Copyright (c) 2018 Thomas Pornin <pornin@bolet.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "inner.h"
/* see bearssl_rsa.h */
br_rsa_compute_pubexp
br_rsa_compute_pubexp_get_default(void)
{
#if BR_LOMUL
return &br_rsa_i15_compute_pubexp;
#else
return &br_rsa_i31_compute_pubexp;
#endif
}

View file

@ -435,8 +435,8 @@ bufswap(void *b1, void *b2, size_t len)
/* see bearssl_rsa.h */
uint32_t
br_rsa_i15_keygen(const br_prng_class **rng,
br_rsa_private_key *sk, unsigned char *kbuf_priv,
br_rsa_public_key *pk, unsigned char *kbuf_pub,
br_rsa_private_key *sk, void *kbuf_priv,
br_rsa_public_key *pk, void *kbuf_pub,
unsigned size, uint32_t pubexp)
{
uint32_t esize_p, esize_q;

99
src/rsa/rsa_i15_modulus.c Normal file
View file

@ -0,0 +1,99 @@
/*
* Copyright (c) 2018 Thomas Pornin <pornin@bolet.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "inner.h"
/* see bearssl_rsa.h */
size_t
br_rsa_i15_compute_modulus(void *n, const br_rsa_private_key *sk)
{
uint16_t tmp[2 * ((BR_MAX_RSA_SIZE + 14) / 15) + 5];
uint16_t *t, *p, *q;
const unsigned char *pbuf, *qbuf;
size_t nlen, plen, qlen, tlen;
/*
* Compute actual byte and lengths for p and q.
*/
pbuf = sk->p;
plen = sk->plen;
while (plen > 0 && *pbuf == 0) {
pbuf ++;
plen --;
}
qbuf = sk->q;
qlen = sk->qlen;
while (qlen > 0 && *qbuf == 0) {
qbuf ++;
qlen --;
}
t = tmp;
tlen = (sizeof tmp) / (sizeof tmp[0]);
/*
* Decode p.
*/
if ((15 * tlen) < (plen << 3) + 15) {
return 0;
}
br_i15_decode(t, pbuf, plen);
p = t;
plen = (p[0] + 31) >> 4;
t += plen;
tlen -= plen;
/*
* Decode q.
*/
if ((15 * tlen) < (qlen << 3) + 15) {
return 0;
}
br_i15_decode(t, qbuf, qlen);
q = t;
qlen = (q[0] + 31) >> 4;
t += qlen;
tlen -= qlen;
/*
* Computation can proceed only if we have enough room for the
* modulus.
*/
if (tlen < (plen + qlen + 1)) {
return 0;
}
/*
* Private key already contains the modulus bit length, from which
* we can infer the output length. Even if n is NULL, we still had
* to decode p and q to make sure that the product can be computed.
*/
nlen = (sk->n_bitlen + 7) >> 3;
if (n != NULL) {
br_i15_zero(t, p[0]);
br_i15_mulacc(t, p, q);
br_i15_encode(n, nlen, t);
}
return nlen;
}

320
src/rsa/rsa_i15_privexp.c Normal file
View file

@ -0,0 +1,320 @@
/*
* Copyright (c) 2018 Thomas Pornin <pornin@bolet.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "inner.h"
/* see bearssl_rsa.h */
size_t
br_rsa_i15_compute_privexp(void *d,
const br_rsa_private_key *sk, uint32_t e)
{
/*
* We want to invert e modulo phi = (p-1)(q-1). This first
* requires computing phi, which is easy since we have the factors
* p and q in the private key structure.
*
* Since p = 3 mod 4 and q = 3 mod 4, phi/4 is an odd integer.
* We could invert e modulo phi/4 then patch the result to
* modulo phi, but this would involve assembling three modulus-wide
* values (phi/4, 1 and e) and calling moddiv, that requires
* three more temporaries, for a total of six big integers, or
* slightly more than 3 kB of stack space for RSA-4096. This
* exceeds our stack requirements.
*
* Instead, we first use one step of the extended GCD:
*
* - We compute phi = k*e + r (Euclidean division of phi by e).
* If public exponent e is correct, then r != 0 (e must be
* invertible modulo phi). We also have k != 0 since we
* enforce non-ridiculously-small factors.
*
* - We find small u, v such that u*e - v*r = 1 (using a
* binary GCD; we can arrange for u < r and v < e, i.e. all
* values fit on 32 bits).
*
* - Solution is: d = u + v*k
* This last computation is exact: since u < r and v < e,
* the above implies d < r + e*((phi-r)/e) = phi
*/
uint16_t tmp[4 * ((BR_MAX_RSA_FACTOR + 14) / 15) + 12];
uint16_t *p, *q, *k, *m, *z, *phi;
const unsigned char *pbuf, *qbuf;
size_t plen, qlen, u, len, dlen;
uint32_t r, a, b, u0, v0, u1, v1, he, hr;
int i;
/*
* Check that e is correct.
*/
if (e < 3 || (e & 1) == 0) {
return 0;
}
/*
* Check lengths of p and q, and that they are both odd.
*/
pbuf = sk->p;
plen = sk->plen;
while (plen > 0 && *pbuf == 0) {
pbuf ++;
plen --;
}
if (plen < 5 || plen > (BR_MAX_RSA_FACTOR / 8)
|| (pbuf[plen - 1] & 1) != 1)
{
return 0;
}
qbuf = sk->q;
qlen = sk->qlen;
while (qlen > 0 && *qbuf == 0) {
qbuf ++;
qlen --;
}
if (qlen < 5 || qlen > (BR_MAX_RSA_FACTOR / 8)
|| (qbuf[qlen - 1] & 1) != 1)
{
return 0;
}
/*
* Output length is that of the modulus.
*/
dlen = (sk->n_bitlen + 7) >> 3;
if (d == NULL) {
return dlen;
}
p = tmp;
br_i15_decode(p, pbuf, plen);
plen = (p[0] + 15) >> 4;
q = p + 1 + plen;
br_i15_decode(q, qbuf, qlen);
qlen = (q[0] + 15) >> 4;
/*
* Compute phi = (p-1)*(q-1), then move it over p-1 and q-1 (that
* we do not need anymore). The mulacc function sets the announced
* bit length of t to be the sum of the announced bit lengths of
* p-1 and q-1, which is usually exact but may overshoot by one 1
* bit in some cases; we readjust it to its true length.
*/
p[1] --;
q[1] --;
phi = q + 1 + qlen;
br_i15_zero(phi, p[0]);
br_i15_mulacc(phi, p, q);
len = (phi[0] + 15) >> 4;
memmove(tmp, phi, (1 + len) * sizeof *phi);
phi = tmp;
phi[0] = br_i15_bit_length(phi + 1, len);
len = (phi[0] + 15) >> 4;
/*
* Divide phi by public exponent e. The final remainder r must be
* non-zero (otherwise, the key is invalid). The quotient is k,
* which we write over phi, since we don't need phi after that.
*/
r = 0;
for (u = len; u >= 1; u --) {
/*
* Upon entry, r < e, and phi[u] < 2^15; hence,
* hi:lo < e*2^15. Thus, the produced word k[u]
* must be lower than 2^15, and the new remainder r
* is lower than e.
*/
uint32_t hi, lo;
hi = r >> 17;
lo = (r << 15) + phi[u];
phi[u] = br_divrem(hi, lo, e, &r);
}
if (r == 0) {
return 0;
}
k = phi;
/*
* Compute u and v such that u*e - v*r = GCD(e,r). We use
* a binary GCD algorithm, with 6 extra integers a, b,
* u0, u1, v0 and v1. Initial values are:
* a = e u0 = 1 v0 = 0
* b = r u1 = r v1 = e-1
* The following invariants are maintained:
* a = u0*e - v0*r
* b = u1*e - v1*r
* 0 < a <= e
* 0 < b <= r
* 0 <= u0 <= r
* 0 <= v0 <= e
* 0 <= u1 <= r
* 0 <= v1 <= e
*
* At each iteration, we reduce either a or b by one bit, and
* adjust u0, u1, v0 and v1 to maintain the invariants:
* - if a is even, then a <- a/2
* - otherwise, if b is even, then b <- b/2
* - otherwise, if a > b, then a <- (a-b)/2
* - otherwise, if b > a, then b <- (b-a)/2
* Algorithm stops when a = b. At that point, the common value
* is the GCD of e and r; it must be 1 (otherwise, the private
* key or public exponent is not valid). The (u0,v0) or (u1,v1)
* pairs are the solution we are looking for.
*
* Since either a or b is reduced by at least 1 bit at each
* iteration, 62 iterations are enough to reach the end
* condition.
*
* To maintain the invariants, we must compute the same operations
* on the u* and v* values that we do on a and b:
* - When a is divided by 2, u0 and v0 must be divided by 2.
* - When b is divided by 2, u1 and v1 must be divided by 2.
* - When b is subtracted from a, u1 and v1 are subtracted from
* u0 and v0, respectively.
* - When a is subtracted from b, u0 and v0 are subtracted from
* u1 and v1, respectively.
*
* However, we want to keep the u* and v* values in their proper
* ranges. The following remarks apply:
*
* - When a is divided by 2, then a is even. Therefore:
*
* * If r is odd, then u0 and v0 must have the same parity;
* if they are both odd, then adding r to u0 and e to v0
* makes them both even, and the division by 2 brings them
* back to the proper range.
*
* * If r is even, then u0 must be even; if v0 is odd, then
* adding r to u0 and e to v0 makes them both even, and the
* division by 2 brings them back to the proper range.
*
* Thus, all we need to do is to look at the parity of v0,
* and add (r,e) to (u0,v0) when v0 is odd. In order to avoid
* a 32-bit overflow, we can add ((r+1)/2,(e/2)+1) after the
* division (r+1 does not overflow since r < e; and (e/2)+1
* is equal to (e+1)/2 since e is odd).
*
* - When we subtract b from a, three cases may occur:
*
* * u1 <= u0 and v1 <= v0: just do the subtractions
*
* * u1 > u0 and v1 > v0: compute:
* (u0, v0) <- (u0 + r - u1, v0 + e - v1)
*
* * u1 <= u0 and v1 > v0: compute:
* (u0, v0) <- (u0 + r - u1, v0 + e - v1)
*
* The fourth case (u1 > u0 and v1 <= v0) is not possible
* because it would contradict "b < a" (which is the reason
* why we subtract b from a).
*
* The tricky case is the third one: from the equations, it
* seems that u0 may go out of range. However, the invariants
* and ranges of other values imply that, in that case, the
* new u0 does not actually exceed the range.
*
* We can thus handle the subtraction by adding (r,e) based
* solely on the comparison between v0 and v1.
*/
a = e;
b = r;
u0 = 1;
v0 = 0;
u1 = r;
v1 = e - 1;
hr = (r + 1) >> 1;
he = (e >> 1) + 1;
for (i = 0; i < 62; i ++) {
uint32_t oa, ob, agtb, bgta;
uint32_t sab, sba, da, db;
uint32_t ctl;
oa = a & 1; /* 1 if a is odd */
ob = b & 1; /* 1 if b is odd */
agtb = GT(a, b); /* 1 if a > b */
bgta = GT(b, a); /* 1 if b > a */
sab = oa & ob & agtb; /* 1 if a <- a-b */
sba = oa & ob & bgta; /* 1 if b <- b-a */
/* a <- a-b, u0 <- u0-u1, v0 <- v0-v1 */
ctl = GT(v1, v0);
a -= b & -sab;
u0 -= (u1 - (r & -ctl)) & -sab;
v0 -= (v1 - (e & -ctl)) & -sab;
/* b <- b-a, u1 <- u1-u0 mod r, v1 <- v1-v0 mod e */
ctl = GT(v0, v1);
b -= a & -sba;
u1 -= (u0 - (r & -ctl)) & -sba;
v1 -= (v0 - (e & -ctl)) & -sba;
da = NOT(oa) | sab; /* 1 if a <- a/2 */
db = (oa & NOT(ob)) | sba; /* 1 if b <- b/2 */
/* a <- a/2, u0 <- u0/2, v0 <- v0/2 */
ctl = v0 & 1;
a ^= (a ^ (a >> 1)) & -da;
u0 ^= (u0 ^ ((u0 >> 1) + (hr & -ctl))) & -da;
v0 ^= (v0 ^ ((v0 >> 1) + (he & -ctl))) & -da;
/* b <- b/2, u1 <- u1/2 mod r, v1 <- v1/2 mod e */
ctl = v1 & 1;
b ^= (b ^ (b >> 1)) & -db;
u1 ^= (u1 ^ ((u1 >> 1) + (hr & -ctl))) & -db;
v1 ^= (v1 ^ ((v1 >> 1) + (he & -ctl))) & -db;
}
/*
* Check that the GCD is indeed 1. If not, then the key is invalid
* (and there's no harm in leaking that piece of information).
*/
if (a != 1) {
return 0;
}
/*
* Now we have u0*e - v0*r = 1. Let's compute the result as:
* d = u0 + v0*k
* We still have k in the tmp[] array, and its announced bit
* length is that of phi.
*/
m = k + 1 + len;
m[0] = (2 << 4) + 2; /* bit length is 32 bits, encoded */
m[1] = v0 & 0x7FFF;
m[2] = (v0 >> 15) & 0x7FFF;
m[3] = v0 >> 30;
z = m + 4;
br_i15_zero(z, k[0]);
z[1] = u0 & 0x7FFF;
z[2] = (u0 >> 15) & 0x7FFF;
z[3] = u0 >> 30;
br_i15_mulacc(z, k, m);
/*
* Encode the result.
*/
br_i15_encode(d, dlen, z);
return dlen;
}

152
src/rsa/rsa_i15_pubexp.c Normal file
View file

@ -0,0 +1,152 @@
/*
* Copyright (c) 2018 Thomas Pornin <pornin@bolet.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "inner.h"
/*
* Recompute public exponent, based on factor p and reduced private
* exponent dp.
*/
static uint32_t
get_pubexp(const unsigned char *pbuf, size_t plen,
const unsigned char *dpbuf, size_t dplen)
{
/*
* dp is the inverse of e modulo p-1. If p = 3 mod 4, then
* p-1 = 2*((p-1)/2). Taken modulo 2, e is odd and has inverse 1;
* thus, dp must be odd.
*
* We compute the inverse of dp modulo (p-1)/2. This requires
* first reducing dp modulo (p-1)/2 (this can be done with a
* conditional subtract, no need to use the generic modular
* reduction function); then, we use moddiv.
*/
uint16_t tmp[6 * ((BR_MAX_RSA_FACTOR + 29) / 15)];
uint16_t *p, *dp, *x;
size_t len;
uint32_t e;
/*
* Compute actual factor length (in bytes) and check that it fits
* under our size constraints.
*/
while (plen > 0 && *pbuf == 0) {
pbuf ++;
plen --;
}
if (plen == 0 || plen < 5 || plen > (BR_MAX_RSA_FACTOR / 8)) {
return 0;
}
/*
* Compute actual reduced exponent length (in bytes) and check that
* it is not longer than p.
*/
while (dplen > 0 && *dpbuf == 0) {
dpbuf ++;
dplen --;
}
if (dplen > plen || dplen == 0
|| (dplen == plen && dpbuf[0] > pbuf[0]))
{
return 0;
}
/*
* Verify that p = 3 mod 4 and that dp is odd.
*/
if ((pbuf[plen - 1] & 3) != 3 || (dpbuf[dplen - 1] & 1) != 1) {
return 0;
}
/*
* Decode p and compute (p-1)/2.
*/
p = tmp;
br_i15_decode(p, pbuf, plen);
len = (p[0] + 31) >> 4;
br_i15_rshift(p, 1);
/*
* Decode dp and make sure its announced bit length matches that of
* p (we already know that the size of dp, in bits, does not exceed
* the size of p, so we just have to copy the header word).
*/
dp = p + len;
memset(dp, 0, len * sizeof *dp);
br_i15_decode(dp, dpbuf, dplen);
dp[0] = p[0];
/*
* Subtract (p-1)/2 from dp if necessary.
*/
br_i15_sub(dp, p, NOT(br_i15_sub(dp, p, 0)));
/*
* If another subtraction is needed, then this means that the
* value was invalid. We don't care to leak information about
* invalid keys.
*/
if (br_i15_sub(dp, p, 0) == 0) {
return 0;
}
/*
* Invert dp modulo (p-1)/2. If the inversion fails, then the
* key value was invalid.
*/
x = dp + len;
br_i15_zero(x, p[0]);
x[1] = 1;
if (br_i15_moddiv(x, dp, p, br_i15_ninv15(p[1]), x + len) == 0) {
return 0;
}
/*
* We now have an inverse. We must set it to zero (error) if its
* length is greater than 32 bits and/or if it is an even integer.
* Take care that the bit_length function returns an encoded
* bit length.
*/
e = (uint32_t)x[1] | ((uint32_t)x[2] << 15) | ((uint32_t)x[3] << 30);
e &= -LT(br_i15_bit_length(x + 1, len - 1), 35);
e &= -(e & 1);
return e;
}
/* see bearssl_rsa.h */
uint32_t
br_rsa_i15_compute_pubexp(const br_rsa_private_key *sk)
{
/*
* Get the public exponent from both p and q. This is the right
* exponent if we get twice the same value.
*/
uint32_t ep, eq;
ep = get_pubexp(sk->p, sk->plen, sk->dp, sk->dplen);
eq = get_pubexp(sk->q, sk->qlen, sk->dq, sk->dqlen);
return ep & -EQ(ep, eq);
}

View file

@ -27,8 +27,8 @@
/* see bearssl_rsa.h */
uint32_t
br_rsa_i31_keygen(const br_prng_class **rng,
br_rsa_private_key *sk, unsigned char *kbuf_priv,
br_rsa_public_key *pk, unsigned char *kbuf_pub,
br_rsa_private_key *sk, void *kbuf_priv,
br_rsa_public_key *pk, void *kbuf_pub,
unsigned size, uint32_t pubexp)
{
return br_rsa_i31_keygen_inner(rng,

View file

@ -456,8 +456,8 @@ bufswap(void *b1, void *b2, size_t len)
/* see inner.h */
uint32_t
br_rsa_i31_keygen_inner(const br_prng_class **rng,
br_rsa_private_key *sk, unsigned char *kbuf_priv,
br_rsa_public_key *pk, unsigned char *kbuf_pub,
br_rsa_private_key *sk, void *kbuf_priv,
br_rsa_public_key *pk, void *kbuf_pub,
unsigned size, uint32_t pubexp, br_i31_modpow_opt_type mp31)
{
uint32_t esize_p, esize_q;

99
src/rsa/rsa_i31_modulus.c Normal file
View file

@ -0,0 +1,99 @@
/*
* Copyright (c) 2018 Thomas Pornin <pornin@bolet.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "inner.h"
/* see bearssl_rsa.h */
size_t
br_rsa_i31_compute_modulus(void *n, const br_rsa_private_key *sk)
{
uint32_t tmp[2 * ((BR_MAX_RSA_SIZE + 30) / 31) + 5];
uint32_t *t, *p, *q;
const unsigned char *pbuf, *qbuf;
size_t nlen, plen, qlen, tlen;
/*
* Compute actual byte and lengths for p and q.
*/
pbuf = sk->p;
plen = sk->plen;
while (plen > 0 && *pbuf == 0) {
pbuf ++;
plen --;
}
qbuf = sk->q;
qlen = sk->qlen;
while (qlen > 0 && *qbuf == 0) {
qbuf ++;
qlen --;
}
t = tmp;
tlen = (sizeof tmp) / (sizeof tmp[0]);
/*
* Decode p.
*/
if ((31 * tlen) < (plen << 3) + 31) {
return 0;
}
br_i31_decode(t, pbuf, plen);
p = t;
plen = (p[0] + 63) >> 5;
t += plen;
tlen -= plen;
/*
* Decode q.
*/
if ((31 * tlen) < (qlen << 3) + 31) {
return 0;
}
br_i31_decode(t, qbuf, qlen);
q = t;
qlen = (q[0] + 63) >> 5;
t += qlen;
tlen -= qlen;
/*
* Computation can proceed only if we have enough room for the
* modulus.
*/
if (tlen < (plen + qlen + 1)) {
return 0;
}
/*
* Private key already contains the modulus bit length, from which
* we can infer the output length. Even if n is NULL, we still had
* to decode p and q to make sure that the product can be computed.
*/
nlen = (sk->n_bitlen + 7) >> 3;
if (n != NULL) {
br_i31_zero(t, p[0]);
br_i31_mulacc(t, p, q);
br_i31_encode(n, nlen, t);
}
return nlen;
}

318
src/rsa/rsa_i31_privexp.c Normal file
View file

@ -0,0 +1,318 @@
/*
* Copyright (c) 2018 Thomas Pornin <pornin@bolet.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "inner.h"
/* see bearssl_rsa.h */
size_t
br_rsa_i31_compute_privexp(void *d,
const br_rsa_private_key *sk, uint32_t e)
{
/*
* We want to invert e modulo phi = (p-1)(q-1). This first
* requires computing phi, which is easy since we have the factors
* p and q in the private key structure.
*
* Since p = 3 mod 4 and q = 3 mod 4, phi/4 is an odd integer.
* We could invert e modulo phi/4 then patch the result to
* modulo phi, but this would involve assembling three modulus-wide
* values (phi/4, 1 and e) and calling moddiv, that requires
* three more temporaries, for a total of six big integers, or
* slightly more than 3 kB of stack space for RSA-4096. This
* exceeds our stack requirements.
*
* Instead, we first use one step of the extended GCD:
*
* - We compute phi = k*e + r (Euclidean division of phi by e).
* If public exponent e is correct, then r != 0 (e must be
* invertible modulo phi). We also have k != 0 since we
* enforce non-ridiculously-small factors.
*
* - We find small u, v such that u*e - v*r = 1 (using a
* binary GCD; we can arrange for u < r and v < e, i.e. all
* values fit on 32 bits).
*
* - Solution is: d = u + v*k
* This last computation is exact: since u < r and v < e,
* the above implies d < r + e*((phi-r)/e) = phi
*/
uint32_t tmp[4 * ((BR_MAX_RSA_FACTOR + 30) / 31) + 12];
uint32_t *p, *q, *k, *m, *z, *phi;
const unsigned char *pbuf, *qbuf;
size_t plen, qlen, u, len, dlen;
uint32_t r, a, b, u0, v0, u1, v1, he, hr;
int i;
/*
* Check that e is correct.
*/
if (e < 3 || (e & 1) == 0) {
return 0;
}
/*
* Check lengths of p and q, and that they are both odd.
*/
pbuf = sk->p;
plen = sk->plen;
while (plen > 0 && *pbuf == 0) {
pbuf ++;
plen --;
}
if (plen < 5 || plen > (BR_MAX_RSA_FACTOR / 8)
|| (pbuf[plen - 1] & 1) != 1)
{
return 0;
}
qbuf = sk->q;
qlen = sk->qlen;
while (qlen > 0 && *qbuf == 0) {
qbuf ++;
qlen --;
}
if (qlen < 5 || qlen > (BR_MAX_RSA_FACTOR / 8)
|| (qbuf[qlen - 1] & 1) != 1)
{
return 0;
}
/*
* Output length is that of the modulus.
*/
dlen = (sk->n_bitlen + 7) >> 3;
if (d == NULL) {
return dlen;
}
p = tmp;
br_i31_decode(p, pbuf, plen);
plen = (p[0] + 31) >> 5;
q = p + 1 + plen;
br_i31_decode(q, qbuf, qlen);
qlen = (q[0] + 31) >> 5;
/*
* Compute phi = (p-1)*(q-1), then move it over p-1 and q-1 (that
* we do not need anymore). The mulacc function sets the announced
* bit length of t to be the sum of the announced bit lengths of
* p-1 and q-1, which is usually exact but may overshoot by one 1
* bit in some cases; we readjust it to its true length.
*/
p[1] --;
q[1] --;
phi = q + 1 + qlen;
br_i31_zero(phi, p[0]);
br_i31_mulacc(phi, p, q);
len = (phi[0] + 31) >> 5;
memmove(tmp, phi, (1 + len) * sizeof *phi);
phi = tmp;
phi[0] = br_i31_bit_length(phi + 1, len);
len = (phi[0] + 31) >> 5;
/*
* Divide phi by public exponent e. The final remainder r must be
* non-zero (otherwise, the key is invalid). The quotient is k,
* which we write over phi, since we don't need phi after that.
*/
r = 0;
for (u = len; u >= 1; u --) {
/*
* Upon entry, r < e, and phi[u] < 2^31; hence,
* hi:lo < e*2^31. Thus, the produced word k[u]
* must be lower than 2^31, and the new remainder r
* is lower than e.
*/
uint32_t hi, lo;
hi = r >> 1;
lo = (r << 31) + phi[u];
phi[u] = br_divrem(hi, lo, e, &r);
}
if (r == 0) {
return 0;
}
k = phi;
/*
* Compute u and v such that u*e - v*r = GCD(e,r). We use
* a binary GCD algorithm, with 6 extra integers a, b,
* u0, u1, v0 and v1. Initial values are:
* a = e u0 = 1 v0 = 0
* b = r u1 = r v1 = e-1
* The following invariants are maintained:
* a = u0*e - v0*r
* b = u1*e - v1*r
* 0 < a <= e
* 0 < b <= r
* 0 <= u0 <= r
* 0 <= v0 <= e
* 0 <= u1 <= r
* 0 <= v1 <= e
*
* At each iteration, we reduce either a or b by one bit, and
* adjust u0, u1, v0 and v1 to maintain the invariants:
* - if a is even, then a <- a/2
* - otherwise, if b is even, then b <- b/2
* - otherwise, if a > b, then a <- (a-b)/2
* - otherwise, if b > a, then b <- (b-a)/2
* Algorithm stops when a = b. At that point, the common value
* is the GCD of e and r; it must be 1 (otherwise, the private
* key or public exponent is not valid). The (u0,v0) or (u1,v1)
* pairs are the solution we are looking for.
*
* Since either a or b is reduced by at least 1 bit at each
* iteration, 62 iterations are enough to reach the end
* condition.
*
* To maintain the invariants, we must compute the same operations
* on the u* and v* values that we do on a and b:
* - When a is divided by 2, u0 and v0 must be divided by 2.
* - When b is divided by 2, u1 and v1 must be divided by 2.
* - When b is subtracted from a, u1 and v1 are subtracted from
* u0 and v0, respectively.
* - When a is subtracted from b, u0 and v0 are subtracted from
* u1 and v1, respectively.
*
* However, we want to keep the u* and v* values in their proper
* ranges. The following remarks apply:
*
* - When a is divided by 2, then a is even. Therefore:
*
* * If r is odd, then u0 and v0 must have the same parity;
* if they are both odd, then adding r to u0 and e to v0
* makes them both even, and the division by 2 brings them
* back to the proper range.
*
* * If r is even, then u0 must be even; if v0 is odd, then
* adding r to u0 and e to v0 makes them both even, and the
* division by 2 brings them back to the proper range.
*
* Thus, all we need to do is to look at the parity of v0,
* and add (r,e) to (u0,v0) when v0 is odd. In order to avoid
* a 32-bit overflow, we can add ((r+1)/2,(e/2)+1) after the
* division (r+1 does not overflow since r < e; and (e/2)+1
* is equal to (e+1)/2 since e is odd).
*
* - When we subtract b from a, three cases may occur:
*
* * u1 <= u0 and v1 <= v0: just do the subtractions
*
* * u1 > u0 and v1 > v0: compute:
* (u0, v0) <- (u0 + r - u1, v0 + e - v1)
*
* * u1 <= u0 and v1 > v0: compute:
* (u0, v0) <- (u0 + r - u1, v0 + e - v1)
*
* The fourth case (u1 > u0 and v1 <= v0) is not possible
* because it would contradict "b < a" (which is the reason
* why we subtract b from a).
*
* The tricky case is the third one: from the equations, it
* seems that u0 may go out of range. However, the invariants
* and ranges of other values imply that, in that case, the
* new u0 does not actually exceed the range.
*
* We can thus handle the subtraction by adding (r,e) based
* solely on the comparison between v0 and v1.
*/
a = e;
b = r;
u0 = 1;
v0 = 0;
u1 = r;
v1 = e - 1;
hr = (r + 1) >> 1;
he = (e >> 1) + 1;
for (i = 0; i < 62; i ++) {
uint32_t oa, ob, agtb, bgta;
uint32_t sab, sba, da, db;
uint32_t ctl;
oa = a & 1; /* 1 if a is odd */
ob = b & 1; /* 1 if b is odd */
agtb = GT(a, b); /* 1 if a > b */
bgta = GT(b, a); /* 1 if b > a */
sab = oa & ob & agtb; /* 1 if a <- a-b */
sba = oa & ob & bgta; /* 1 if b <- b-a */
/* a <- a-b, u0 <- u0-u1, v0 <- v0-v1 */
ctl = GT(v1, v0);
a -= b & -sab;
u0 -= (u1 - (r & -ctl)) & -sab;
v0 -= (v1 - (e & -ctl)) & -sab;
/* b <- b-a, u1 <- u1-u0 mod r, v1 <- v1-v0 mod e */
ctl = GT(v0, v1);
b -= a & -sba;
u1 -= (u0 - (r & -ctl)) & -sba;
v1 -= (v0 - (e & -ctl)) & -sba;
da = NOT(oa) | sab; /* 1 if a <- a/2 */
db = (oa & NOT(ob)) | sba; /* 1 if b <- b/2 */
/* a <- a/2, u0 <- u0/2, v0 <- v0/2 */
ctl = v0 & 1;
a ^= (a ^ (a >> 1)) & -da;
u0 ^= (u0 ^ ((u0 >> 1) + (hr & -ctl))) & -da;
v0 ^= (v0 ^ ((v0 >> 1) + (he & -ctl))) & -da;
/* b <- b/2, u1 <- u1/2 mod r, v1 <- v1/2 mod e */
ctl = v1 & 1;
b ^= (b ^ (b >> 1)) & -db;
u1 ^= (u1 ^ ((u1 >> 1) + (hr & -ctl))) & -db;
v1 ^= (v1 ^ ((v1 >> 1) + (he & -ctl))) & -db;
}
/*
* Check that the GCD is indeed 1. If not, then the key is invalid
* (and there's no harm in leaking that piece of information).
*/
if (a != 1) {
return 0;
}
/*
* Now we have u0*e - v0*r = 1. Let's compute the result as:
* d = u0 + v0*k
* We still have k in the tmp[] array, and its announced bit
* length is that of phi.
*/
m = k + 1 + len;
m[0] = (1 << 5) + 1; /* bit length is 32 bits, encoded */
m[1] = v0 & 0x7FFFFFFF;
m[2] = v0 >> 31;
z = m + 3;
br_i31_zero(z, k[0]);
z[1] = u0 & 0x7FFFFFFF;
z[2] = u0 >> 31;
br_i31_mulacc(z, k, m);
/*
* Encode the result.
*/
br_i31_encode(d, dlen, z);
return dlen;
}

152
src/rsa/rsa_i31_pubexp.c Normal file
View file

@ -0,0 +1,152 @@
/*
* Copyright (c) 2018 Thomas Pornin <pornin@bolet.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "inner.h"
/*
* Recompute public exponent, based on factor p and reduced private
* exponent dp.
*/
static uint32_t
get_pubexp(const unsigned char *pbuf, size_t plen,
const unsigned char *dpbuf, size_t dplen)
{
/*
* dp is the inverse of e modulo p-1. If p = 3 mod 4, then
* p-1 = 2*((p-1)/2). Taken modulo 2, e is odd and has inverse 1;
* thus, dp must be odd.
*
* We compute the inverse of dp modulo (p-1)/2. This requires
* first reducing dp modulo (p-1)/2 (this can be done with a
* conditional subtract, no need to use the generic modular
* reduction function); then, we use moddiv.
*/
uint32_t tmp[6 * ((BR_MAX_RSA_FACTOR + 61) / 31)];
uint32_t *p, *dp, *x;
size_t len;
uint32_t e;
/*
* Compute actual factor length (in bytes) and check that it fits
* under our size constraints.
*/
while (plen > 0 && *pbuf == 0) {
pbuf ++;
plen --;
}
if (plen == 0 || plen < 5 || plen > (BR_MAX_RSA_FACTOR / 8)) {
return 0;
}
/*
* Compute actual reduced exponent length (in bytes) and check that
* it is not longer than p.
*/
while (dplen > 0 && *dpbuf == 0) {
dpbuf ++;
dplen --;
}
if (dplen > plen || dplen == 0
|| (dplen == plen && dpbuf[0] > pbuf[0]))
{
return 0;
}
/*
* Verify that p = 3 mod 4 and that dp is odd.
*/
if ((pbuf[plen - 1] & 3) != 3 || (dpbuf[dplen - 1] & 1) != 1) {
return 0;
}
/*
* Decode p and compute (p-1)/2.
*/
p = tmp;
br_i31_decode(p, pbuf, plen);
len = (p[0] + 63) >> 5;
br_i31_rshift(p, 1);
/*
* Decode dp and make sure its announced bit length matches that of
* p (we already know that the size of dp, in bits, does not exceed
* the size of p, so we just have to copy the header word).
*/
dp = p + len;
memset(dp, 0, len * sizeof *dp);
br_i31_decode(dp, dpbuf, dplen);
dp[0] = p[0];
/*
* Subtract (p-1)/2 from dp if necessary.
*/
br_i31_sub(dp, p, NOT(br_i31_sub(dp, p, 0)));
/*
* If another subtraction is needed, then this means that the
* value was invalid. We don't care to leak information about
* invalid keys.
*/
if (br_i31_sub(dp, p, 0) == 0) {
return 0;
}
/*
* Invert dp modulo (p-1)/2. If the inversion fails, then the
* key value was invalid.
*/
x = dp + len;
br_i31_zero(x, p[0]);
x[1] = 1;
if (br_i31_moddiv(x, dp, p, br_i31_ninv31(p[1]), x + len) == 0) {
return 0;
}
/*
* We now have an inverse. We must set it to zero (error) if its
* length is greater than 32 bits and/or if it is an even integer.
* Take care that the bit_length function returns an encoded
* bit length.
*/
e = (uint32_t)x[1] | ((uint32_t)x[2] << 31);
e &= -LT(br_i31_bit_length(x + 1, len - 1), 34);
e &= -(e & 1);
return e;
}
/* see bearssl_rsa.h */
uint32_t
br_rsa_i31_compute_pubexp(const br_rsa_private_key *sk)
{
/*
* Get the public exponent from both p and q. This is the right
* exponent if we get twice the same value.
*/
uint32_t ep, eq;
ep = get_pubexp(sk->p, sk->plen, sk->dp, sk->dplen);
eq = get_pubexp(sk->q, sk->qlen, sk->dq, sk->dqlen);
return ep & -EQ(ep, eq);
}

View file

@ -29,8 +29,8 @@
/* see bearssl_rsa.h */
uint32_t
br_rsa_i62_keygen(const br_prng_class **rng,
br_rsa_private_key *sk, unsigned char *kbuf_priv,
br_rsa_public_key *pk, unsigned char *kbuf_pub,
br_rsa_private_key *sk, void *kbuf_priv,
br_rsa_public_key *pk, void *kbuf_pub,
unsigned size, uint32_t pubexp)
{
return br_rsa_i31_keygen_inner(rng,

93
src/x509/asn1enc.c Normal file
View file

@ -0,0 +1,93 @@
/*
* Copyright (c) 2018 Thomas Pornin <pornin@bolet.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "inner.h"
/* see inner.h */
br_asn1_uint
br_asn1_uint_prepare(const void *xdata, size_t xlen)
{
const unsigned char *x;
br_asn1_uint t;
x = xdata;
while (xlen > 0 && *x == 0) {
x ++;
xlen --;
}
t.data = x;
t.len = xlen;
t.asn1len = xlen;
if (xlen == 0 || x[0] >= 0x80) {
t.asn1len ++;
}
return t;
}
/* see inner.h */
size_t
br_asn1_encode_length(void *dest, size_t len)
{
unsigned char *buf;
size_t z;
int i, j;
buf = dest;
if (len < 0x80) {
if (buf != NULL) {
*buf = len;
}
return 1;
}
i = 0;
for (z = len; z != 0; z >>= 8) {
i ++;
}
if (buf != NULL) {
*buf ++ = 0x80 + i;
for (j = i - 1; j >= 0; j --) {
*buf ++ = len >> (j << 3);
}
}
return i + 1;
}
/* see inner.h */
size_t
br_asn1_encode_uint(void *dest, br_asn1_uint pp)
{
unsigned char *buf;
size_t lenlen;
if (dest == NULL) {
return 1 + br_asn1_encode_length(NULL, pp.asn1len) + pp.asn1len;
}
buf = dest;
*buf ++ = 0x02;
lenlen = br_asn1_encode_length(buf, pp.asn1len);
buf += lenlen;
*buf = 0x00;
memcpy(buf + pp.asn1len - pp.len, pp.data, pp.len);
return 1 + lenlen + pp.asn1len;
}

110
src/x509/encode_ec_pk8der.c Normal file
View file

@ -0,0 +1,110 @@
/*
* Copyright (c) 2018 Thomas Pornin <pornin@bolet.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "inner.h"
/* see bearssl_x509.h */
size_t
br_encode_ec_pkcs8_der(void *dest,
const br_ec_private_key *sk, const br_ec_public_key *pk)
{
/*
* ASN.1 format:
*
* OneAsymmetricKey ::= SEQUENCE {
* version Version,
* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
* privateKey PrivateKey,
* attributes [0] Attributes OPTIONAL,
* ...,
* [[2: publicKey [1] PublicKey OPTIONAL ]],
* ...
* }
*
* We don't include attributes or public key (the public key
* is included in the private key value instead). The
* 'version' field is an INTEGER that we will set to 0
* (meaning 'v1', compatible with previous versions of PKCS#8).
* The 'privateKeyAlgorithm' structure is an AlgorithmIdentifier
* whose OID should be id-ecPublicKey, with, as parameters, the
* curve OID. The 'privateKey' is an OCTET STRING, whose value
* is the "raw DER" encoding of the key pair.
*/
/*
* OID id-ecPublicKey (1.2.840.10045.2.1), DER-encoded (with
* the tag).
*/
static const unsigned char OID_ECPUBKEY[] = {
0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01
};
size_t len_version, len_privateKeyAlgorithm, len_privateKeyValue;
size_t len_privateKey, len_seq;
const unsigned char *oid;
oid = br_get_curve_OID(sk->curve);
if (oid == NULL) {
return 0;
}
len_version = 3;
len_privateKeyAlgorithm = 2 + sizeof OID_ECPUBKEY + 2 + oid[0];
len_privateKeyValue = br_encode_ec_raw_der_inner(NULL, sk, pk, 0);
len_privateKey = 1 + len_of_len(len_privateKeyValue)
+ len_privateKeyValue;
len_seq = len_version + len_privateKeyAlgorithm + len_privateKey;
if (dest == NULL) {
return 1 + len_of_len(len_seq) + len_seq;
} else {
unsigned char *buf;
size_t lenlen;
buf = dest;
*buf ++ = 0x30; /* SEQUENCE tag */
lenlen = br_asn1_encode_length(buf, len_seq);
buf += lenlen;
/* version */
*buf ++ = 0x02;
*buf ++ = 0x01;
*buf ++ = 0x00;
/* privateKeyAlgorithm */
*buf ++ = 0x30;
*buf ++ = (sizeof OID_ECPUBKEY) + 2 + oid[0];
memcpy(buf, OID_ECPUBKEY, sizeof OID_ECPUBKEY);
buf += sizeof OID_ECPUBKEY;
*buf ++ = 0x06;
memcpy(buf, oid, 1 + oid[0]);
buf += 1 + oid[0];
/* privateKey */
*buf ++ = 0x04;
buf += br_asn1_encode_length(buf, len_privateKeyValue);
br_encode_ec_raw_der_inner(buf, sk, pk, 0);
return 1 + lenlen + len_seq;
}
}

161
src/x509/encode_ec_rawder.c Normal file
View file

@ -0,0 +1,161 @@
/*
* Copyright (c) 2018 Thomas Pornin <pornin@bolet.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "inner.h"
/* see inner.h */
const unsigned char *
br_get_curve_OID(int curve)
{
static const unsigned char OID_secp256r1[] = {
0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07
};
static const unsigned char OID_secp384r1[] = {
0x05, 0x2b, 0x81, 0x04, 0x00, 0x22
};
static const unsigned char OID_secp521r1[] = {
0x05, 0x2b, 0x81, 0x04, 0x00, 0x23
};
switch (curve) {
case BR_EC_secp256r1: return OID_secp256r1;
case BR_EC_secp384r1: return OID_secp384r1;
case BR_EC_secp521r1: return OID_secp521r1;
default:
return NULL;
}
}
/* see inner.h */
size_t
br_encode_ec_raw_der_inner(void *dest,
const br_ec_private_key *sk, const br_ec_public_key *pk,
int include_curve_oid)
{
/*
* ASN.1 format:
*
* ECPrivateKey ::= SEQUENCE {
* version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
* privateKey OCTET STRING,
* parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
* publicKey [1] BIT STRING OPTIONAL
* }
*
* The tages '[0]' and '[1]' are explicit. The 'ECParameters'
* is a CHOICE; in our case, it will always be an OBJECT IDENTIFIER
* that identifies the curve.
*
* The value of the 'privateKey' field is the raw unsigned big-endian
* encoding of the private key (integer modulo the curve subgroup
* order); there is no INTEGER tag, and the leading bit may be 1.
* Also, leading bytes of value 0x00 are _not_ removed.
*
* The 'publicKey' contents are the raw encoded public key point,
* normally uncompressed (leading byte of value 0x04, followed
* by the unsigned big-endian encodings of the X and Y coordinates,
* padded to the full field length if necessary).
*/
size_t len_version, len_privateKey, len_parameters, len_publicKey;
size_t len_publicKey_bits, len_seq;
const unsigned char *oid;
if (include_curve_oid) {
oid = br_get_curve_OID(sk->curve);
if (oid == NULL) {
return 0;
}
} else {
oid = NULL;
}
len_version = 3;
len_privateKey = 1 + len_of_len(sk->xlen) + sk->xlen;
if (include_curve_oid) {
len_parameters = 4 + oid[0];
} else {
len_parameters = 0;
}
if (pk == NULL) {
len_publicKey = 0;
len_publicKey_bits = 0;
} else {
len_publicKey_bits = 2 + len_of_len(pk->qlen) + pk->qlen;
len_publicKey = 1 + len_of_len(len_publicKey_bits)
+ len_publicKey_bits;
}
len_seq = len_version + len_privateKey + len_parameters + len_publicKey;
if (dest == NULL) {
return 1 + len_of_len(len_seq) + len_seq;
} else {
unsigned char *buf;
size_t lenlen;
buf = dest;
*buf ++ = 0x30; /* SEQUENCE tag */
lenlen = br_asn1_encode_length(buf, len_seq);
buf += lenlen;
/* version */
*buf ++ = 0x02;
*buf ++ = 0x01;
*buf ++ = 0x01;
/* privateKey */
*buf ++ = 0x04;
buf += br_asn1_encode_length(buf, sk->xlen);
memcpy(buf, sk->x, sk->xlen);
buf += sk->xlen;
/* parameters */
if (include_curve_oid) {
*buf ++ = 0xA0;
*buf ++ = oid[0] + 2;
*buf ++ = 0x06;
memcpy(buf, oid, oid[0] + 1);
buf += oid[0] + 1;
}
/* publicKey */
if (pk != NULL) {
*buf ++ = 0xA1;
buf += br_asn1_encode_length(buf, len_publicKey_bits);
*buf ++ = 0x03;
buf += br_asn1_encode_length(buf, pk->qlen + 1);
*buf ++ = 0x00;
memcpy(buf, pk->q, pk->qlen);
/* buf += pk->qlen; */
}
return 1 + lenlen + len_seq;
}
}
/* see bearssl_x509.h */
size_t
br_encode_ec_raw_der(void *dest,
const br_ec_private_key *sk, const br_ec_public_key *pk)
{
return br_encode_ec_raw_der_inner(dest, sk, pk, 1);
}

View file

@ -0,0 +1,97 @@
/*
* Copyright (c) 2018 Thomas Pornin <pornin@bolet.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "inner.h"
/* see bearssl_x509.h */
size_t
br_encode_rsa_pkcs8_der(void *dest, const br_rsa_private_key *sk,
const br_rsa_public_key *pk, const void *d, size_t dlen)
{
/*
* ASN.1 format:
*
* OneAsymmetricKey ::= SEQUENCE {
* version Version,
* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
* privateKey PrivateKey,
* attributes [0] Attributes OPTIONAL,
* ...,
* [[2: publicKey [1] PublicKey OPTIONAL ]],
* ...
* }
*
* We don't include attributes or public key. The 'version' field
* is an INTEGER that we will set to 0 (meaning 'v1', compatible
* with previous versions of PKCS#8). The 'privateKeyAlgorithm'
* structure is an AlgorithmIdentifier whose OID should be
* rsaEncryption, with NULL parameters. The 'privateKey' is an
* OCTET STRING, whose value is the "raw DER" encoding of the
* key pair.
*
* Since the private key value comes last, this function really
* adds a header, which is mostly fixed (only some lengths have
* to be modified.
*/
/*
* Concatenation of:
* - DER encoding of an INTEGER of value 0 (the 'version' field)
* - DER encoding of a PrivateKeyAlgorithmIdentifier that uses
* the rsaEncryption OID, and NULL parameters
* - An OCTET STRING tag
*/
static const unsigned char PK8_HEAD[] = {
0x02, 0x01, 0x00,
0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00,
0x04
};
size_t len_raw, len_seq;
len_raw = br_encode_rsa_raw_der(NULL, sk, pk, d, dlen);
len_seq = (sizeof PK8_HEAD) + len_of_len(len_raw) + len_raw;
if (dest == NULL) {
return 1 + len_of_len(len_seq) + len_seq;
} else {
unsigned char *buf;
size_t lenlen;
buf = dest;
*buf ++ = 0x30; /* SEQUENCE tag */
lenlen = br_asn1_encode_length(buf, len_seq);
buf += lenlen;
/* version, privateKeyAlgorithm, privateKey tag */
memcpy(buf, PK8_HEAD, sizeof PK8_HEAD);
buf += sizeof PK8_HEAD;
/* privateKey */
buf += br_asn1_encode_length(buf, len_raw);
br_encode_rsa_raw_der(buf, sk, pk, d, dlen);
return 1 + lenlen + len_seq;
}
}

View file

@ -0,0 +1,96 @@
/*
* Copyright (c) 2018 Thomas Pornin <pornin@bolet.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "inner.h"
/* see bearssl_x509.h */
size_t
br_encode_rsa_raw_der(void *dest, const br_rsa_private_key *sk,
const br_rsa_public_key *pk, const void *d, size_t dlen)
{
/*
* ASN.1 format:
*
* RSAPrivateKey ::= SEQUENCE {
* version Version,
* modulus INTEGER, -- n
* publicExponent INTEGER, -- e
* privateExponent INTEGER, -- d
* prime1 INTEGER, -- p
* prime2 INTEGER, -- q
* exponent1 INTEGER, -- d mod (p-1)
* exponent2 INTEGER, -- d mod (q-1)
* coefficient INTEGER, -- (inverse of q) mod p
* otherPrimeInfos OtherPrimeInfos OPTIONAL
* }
*
* The 'version' field is an INTEGER of value 0 (meaning: there
* are exactly two prime factors), and 'otherPrimeInfos' will
* be absent (because there are exactly two prime factors).
*/
br_asn1_uint num[9];
size_t u, slen;
/*
* For all INTEGER values, get the pointer and length for the
* data bytes.
*/
num[0] = br_asn1_uint_prepare(NULL, 0);
num[1] = br_asn1_uint_prepare(pk->n, pk->nlen);
num[2] = br_asn1_uint_prepare(pk->e, pk->elen);
num[3] = br_asn1_uint_prepare(d, dlen);
num[4] = br_asn1_uint_prepare(sk->p, sk->plen);
num[5] = br_asn1_uint_prepare(sk->q, sk->qlen);
num[6] = br_asn1_uint_prepare(sk->dp, sk->dplen);
num[7] = br_asn1_uint_prepare(sk->dq, sk->dqlen);
num[8] = br_asn1_uint_prepare(sk->iq, sk->iqlen);
/*
* Get the length of the SEQUENCE contents.
*/
slen = 0;
for (u = 0; u < 9; u ++) {
uint32_t ilen;
ilen = num[u].asn1len;
slen += 1 + len_of_len(ilen) + ilen;
}
if (dest == NULL) {
return 1 + len_of_len(slen) + slen;
} else {
unsigned char *buf;
size_t lenlen;
buf = dest;
*buf ++ = 0x30; /* SEQUENCE tag */
lenlen = br_asn1_encode_length(buf, slen);
buf += lenlen;
for (u = 0; u < 9; u ++) {
buf += br_asn1_encode_uint(buf, num[u]);
}
return 1 + lenlen + slen;
}
}