Compare commits

..
7 Commits
Author SHA1 Message Date
Cory Benfield afe4c9b5f6 Update BoringSSL to 54858b63c1d886f6c8d903d4a4f594f1485de189 (#47) 2020-08-03 15:57:04 +01:00
Cory Benfield d82f7d8ce8 Update to Developer Beta 3 build. (#46) 2020-07-31 19:50:26 +01:00
Tim Condon 6445f9fb06 Fix path to environment script (#44) 2020-07-03 18:01:46 +01:00
Tim Condon f8b6e4e17e Clarify the location of the line to comment out for macOS development (#42) 2020-07-03 09:59:19 +01:00
buttaface 68d56d2b3c DERTests: enable test function for Android (#41) 2020-06-27 21:01:37 +01:00
Cory Benfield 794901c991 Update Swift Crypto with API from CryptoKit @ WWDC20 (#40)
Motivation:

At WWDC 2020 Apple updated the CryptoKit APIs. This PR brings those new
APIs to Swift Crypto. This brings Swift Crypto up-to-date with the
latest CryptoKit API support, including PEM/DER key support and HKDF API
extensions.

Modifications:

- Bring forward the CryptoKit API files
- Update to have API match the WWDC seed.

Result:

Users will have access to the seed APIs.
2020-06-22 21:40:34 +01:00
Johannes Weiss 82503a48ce fix warnings in with newer Swift compilers (#37)
Motiviation:

One `let` was hiding as a `var` and a few `#file` parameters have been
forwarded to (now) `#filePath` ones.

Modification:

- make the `var` a `let`
- silence the `#file`/`#filePath` warning by adding `(#file)` because we
  can't forward them properly right now
  (https://bugs.swift.org/browse/SR-12934). That's okay because even on
  the Swift master branch, `#file` == `#filePath`.

Result:

No warnings in newer Swift compilers.
2020-06-15 13:52:24 +01:00
134 changed files with 6723 additions and 1988 deletions

No files matched your search

+1 -1
View File
@@ -33,7 +33,7 @@ _[the Swift Crypto tag/commit hash]_
### Environment
Stand in the root of the repo and run `./scripts/environments.sh` and paste the output below
Stand in the root of the repo and run `./scripts/environment.sh` and paste the output below
<details>
<pre>PLEASE_REPLACE_THIS_STIRNG_WITH_OUTPUT_OF_script_environments_THAT_IS_IN_YOUR_PASTEBOARD</pre>
+1 -1
View File
@@ -26,7 +26,7 @@ _[the Swift Crypto tag/commit hash]_
### Environment
Stand in the root of the repo and run `./scripts/environments.sh` and paste the output below
Stand in the root of the repo and run `./scripts/environment.sh` and paste the output below
<details>
<pre>PLEASE_REPLACE_THIS_STIRNG_WITH_OUTPUT_OF_script_environments_THAT_IS_IN_YOUR_PASTEBOARD</pre>
+1 -1
View File
@@ -20,7 +20,7 @@
// Sources/CCryptoBoringSSL directory. The source repository is at
// https://boringssl.googlesource.com/boringssl.
//
// BoringSSL Commit: 53a17f55247101105ae35767d5c5a6c311843a8e
// BoringSSL Commit: 54858b63c1d886f6c8d903d4a4f594f1485de189
import PackageDescription
+1 -1
View File
@@ -108,5 +108,5 @@ SemVer and Swift Crypto's Public API guarantees should result in a working progr
### Developing Swift Crypto on macOS
Swift Crypto normally defers to the OS implementation of CryptoKit on macOS. Naturally, this makes developing Swift Crypto on macOS tricky. To get Swift Crypto to build the open source implementation on macOS, uncomment the line that reads: `//.define("CRYPTO_IN_SWIFTPM_FORCE_BUILD_API")`, as this will force Swift Crypto to build its public API.
Swift Crypto normally defers to the OS implementation of CryptoKit on macOS. Naturally, this makes developing Swift Crypto on macOS tricky. To get Swift Crypto to build the open source implementation on macOS, in `Package.swift`, uncomment the line that reads: `//.define("CRYPTO_IN_SWIFTPM_FORCE_BUILD_API")`, as this will force Swift Crypto to build its public API.
@@ -70,7 +70,7 @@ int ASN1_BIT_STRING_set(ASN1_BIT_STRING *x, unsigned char *d, int len)
return M_ASN1_BIT_STRING_set(x, d, len);
}
int i2c_ASN1_BIT_STRING(ASN1_BIT_STRING *a, unsigned char **pp)
int i2c_ASN1_BIT_STRING(const ASN1_BIT_STRING *a, unsigned char **pp)
{
int ret, j, bits, len;
unsigned char *p, *d;
@@ -233,7 +233,7 @@ int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value)
return (1);
}
int ASN1_BIT_STRING_get_bit(ASN1_BIT_STRING *a, int n)
int ASN1_BIT_STRING_get_bit(const ASN1_BIT_STRING *a, int n)
{
int w, v;
@@ -250,7 +250,7 @@ int ASN1_BIT_STRING_get_bit(ASN1_BIT_STRING *a, int n)
* which is not specified in 'flags', 1 otherwise.
* 'len' is the length of 'flags'.
*/
int ASN1_BIT_STRING_check(ASN1_BIT_STRING *a,
int ASN1_BIT_STRING_check(const ASN1_BIT_STRING *a,
unsigned char *flags, int flags_len)
{
int i, ok;
@@ -108,7 +108,7 @@ int ASN1_ENUMERATED_set(ASN1_ENUMERATED *a, long v)
return (1);
}
long ASN1_ENUMERATED_get(ASN1_ENUMERATED *a)
long ASN1_ENUMERATED_get(const ASN1_ENUMERATED *a)
{
int neg = 0, i;
@@ -147,7 +147,7 @@ long ASN1_ENUMERATED_get(ASN1_ENUMERATED *a)
return r;
}
ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(BIGNUM *bn, ASN1_ENUMERATED *ai)
ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(const BIGNUM *bn, ASN1_ENUMERATED *ai)
{
ASN1_ENUMERATED *ret;
int len, j;
@@ -183,7 +183,7 @@ ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(BIGNUM *bn, ASN1_ENUMERATED *ai)
return (NULL);
}
BIGNUM *ASN1_ENUMERATED_to_BN(ASN1_ENUMERATED *ai, BIGNUM *bn)
BIGNUM *ASN1_ENUMERATED_to_BN(const ASN1_ENUMERATED *ai, BIGNUM *bn)
{
BIGNUM *ret;
+1 -1
View File
@@ -115,7 +115,7 @@ int ASN1_INTEGER_cmp(const ASN1_INTEGER *x, const ASN1_INTEGER *y)
* followed by optional zeros isn't padded.
*/
int i2c_ASN1_INTEGER(ASN1_INTEGER *a, unsigned char **pp)
int i2c_ASN1_INTEGER(const ASN1_INTEGER *a, unsigned char **pp)
{
int pad = 0, ret, i, neg;
unsigned char *p, *n, pb = 0;
@@ -66,7 +66,7 @@
#include "../internal.h"
int i2d_ASN1_OBJECT(ASN1_OBJECT *a, unsigned char **pp)
int i2d_ASN1_OBJECT(const ASN1_OBJECT *a, unsigned char **pp)
{
unsigned char *p, *allocated = NULL;
int objsize;
@@ -98,12 +98,12 @@ int i2d_ASN1_OBJECT(ASN1_OBJECT *a, unsigned char **pp)
return objsize;
}
int i2t_ASN1_OBJECT(char *buf, int buf_len, ASN1_OBJECT *a)
int i2t_ASN1_OBJECT(char *buf, int buf_len, const ASN1_OBJECT *a)
{
return OBJ_obj2txt(buf, buf_len, a, 0);
}
int i2a_ASN1_OBJECT(BIO *bp, ASN1_OBJECT *a)
int i2a_ASN1_OBJECT(BIO *bp, const ASN1_OBJECT *a)
{
char buf[80], *p = buf;
int i;
@@ -100,7 +100,7 @@ ASN1_TIME *ASN1_TIME_adj(ASN1_TIME *s, time_t t,
return ASN1_GENERALIZEDTIME_adj(s, t, offset_day, offset_sec);
}
int ASN1_TIME_check(ASN1_TIME *t)
int ASN1_TIME_check(const ASN1_TIME *t)
{
if (t->type == V_ASN1_GENERALIZEDTIME)
return ASN1_GENERALIZEDTIME_check(t);
@@ -110,7 +110,7 @@ int ASN1_TIME_check(ASN1_TIME *t)
}
/* Convert an ASN1_TIME structure to GeneralizedTime */
ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(ASN1_TIME *t,
ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(const ASN1_TIME *t,
ASN1_GENERALIZEDTIME **out)
{
ASN1_GENERALIZEDTIME *ret = NULL;
@@ -61,7 +61,7 @@
#include <CCryptoBoringSSL_mem.h>
#include <CCryptoBoringSSL_obj.h>
int ASN1_TYPE_get(ASN1_TYPE *a)
int ASN1_TYPE_get(const ASN1_TYPE *a)
{
if ((a->value.ptr != NULL) || (a->type == V_ASN1_NULL))
return (a->type);
@@ -430,7 +430,7 @@ void ASN1_STRING_length_set(ASN1_STRING *x, int len)
return;
}
int ASN1_STRING_type(ASN1_STRING *x)
int ASN1_STRING_type(const ASN1_STRING *x)
{
return M_ASN1_STRING_type(x);
}
@@ -93,7 +93,7 @@ ASN1_STRING *ASN1_item_pack(void *obj, const ASN1_ITEM *it, ASN1_STRING **oct)
/* Extract an ASN1 object from an ASN1_STRING */
void *ASN1_item_unpack(ASN1_STRING *oct, const ASN1_ITEM *it)
void *ASN1_item_unpack(const ASN1_STRING *oct, const ASN1_ITEM *it)
{
const unsigned char *p;
void *ret;
@@ -60,7 +60,7 @@
/* Based on a_int.c: equivalent ENUMERATED functions */
int i2a_ASN1_ENUMERATED(BIO *bp, ASN1_ENUMERATED *a)
int i2a_ASN1_ENUMERATED(BIO *bp, const ASN1_ENUMERATED *a)
{
int i, n = 0;
static const char *h = "0123456789ABCDEF";
+1 -1
View File
@@ -58,7 +58,7 @@
#include <CCryptoBoringSSL_bio.h>
int i2a_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *a)
int i2a_ASN1_INTEGER(BIO *bp, const ASN1_INTEGER *a)
{
int i, n = 0;
static const char *h = "0123456789ABCDEF";
@@ -58,7 +58,7 @@
#include <CCryptoBoringSSL_bio.h>
int i2a_ASN1_STRING(BIO *bp, ASN1_STRING *a, int type)
int i2a_ASN1_STRING(BIO *bp, const ASN1_STRING *a, int type)
{
int i, n = 0;
static const char *h = "0123456789ABCDEF";
@@ -133,6 +133,7 @@ void EVP_tls_cbc_copy_mac(uint8_t *out, size_t md_size, const uint8_t *in,
assert(orig_len >= in_len);
assert(in_len >= md_size);
assert(md_size <= EVP_MAX_MD_SIZE);
assert(md_size > 0);
// scan_start contains the number of bytes that we can ignore because
// the MAC's position can only vary by 255 bytes.
@@ -50,12 +50,10 @@
// expand_message_xmd implements the operation described in section 5.3.1 of
// draft-irtf-cfrg-hash-to-curve-07. It returns one on success and zero on
// allocation failure or if |out_len| was too large. If |is_draft06| is one, it
// implements the operation from draft-irtf-cfrg-hash-to-curve-06 instead.
// allocation failure or if |out_len| was too large.
static int expand_message_xmd(const EVP_MD *md, uint8_t *out, size_t out_len,
const uint8_t *msg, size_t msg_len,
const uint8_t *dst, size_t dst_len,
int is_draft06) {
const uint8_t *dst, size_t dst_len) {
int ret = 0;
const size_t block_size = EVP_MD_block_size(md);
const size_t md_size = EVP_MD_size(md);
@@ -88,9 +86,8 @@ static int expand_message_xmd(const EVP_MD *md, uint8_t *out, size_t out_len,
!EVP_DigestUpdate(&ctx, kZeros, block_size) ||
!EVP_DigestUpdate(&ctx, msg, msg_len) ||
!EVP_DigestUpdate(&ctx, l_i_b_str_zero, sizeof(l_i_b_str_zero)) ||
(is_draft06 && !EVP_DigestUpdate(&ctx, &dst_len_u8, 1)) ||
!EVP_DigestUpdate(&ctx, dst, dst_len) ||
(!is_draft06 && !EVP_DigestUpdate(&ctx, &dst_len_u8, 1)) ||
!EVP_DigestUpdate(&ctx, &dst_len_u8, 1) ||
!EVP_DigestFinal_ex(&ctx, b_0, NULL)) {
goto err;
}
@@ -114,9 +111,8 @@ static int expand_message_xmd(const EVP_MD *md, uint8_t *out, size_t out_len,
if (!EVP_DigestInit_ex(&ctx, md, NULL) ||
!EVP_DigestUpdate(&ctx, b_i, md_size) ||
!EVP_DigestUpdate(&ctx, &i, 1) ||
(is_draft06 && !EVP_DigestUpdate(&ctx, &dst_len_u8, 1)) ||
!EVP_DigestUpdate(&ctx, dst, dst_len) ||
(!is_draft06 && !EVP_DigestUpdate(&ctx, &dst_len_u8, 1)) ||
!EVP_DigestUpdate(&ctx, &dst_len_u8, 1) ||
!EVP_DigestFinal_ex(&ctx, b_i, NULL)) {
goto err;
}
@@ -175,12 +171,11 @@ static void big_endian_to_words(BN_ULONG *out, size_t num_words,
static int hash_to_field2(const EC_GROUP *group, const EVP_MD *md,
EC_FELEM *out1, EC_FELEM *out2, const uint8_t *dst,
size_t dst_len, unsigned k, const uint8_t *msg,
size_t msg_len, int is_draft06) {
size_t msg_len) {
size_t L;
uint8_t buf[4 * EC_MAX_BYTES];
if (!num_bytes_to_derive(&L, &group->field, k) ||
!expand_message_xmd(md, buf, 2 * L, msg, msg_len, dst, dst_len,
is_draft06)) {
!expand_message_xmd(md, buf, 2 * L, msg, msg_len, dst, dst_len)) {
return 0;
}
BN_ULONG words[2 * EC_MAX_WORDS];
@@ -196,12 +191,11 @@ static int hash_to_field2(const EC_GROUP *group, const EVP_MD *md,
// group order rather than a field element. |k| is the security factor.
static int hash_to_scalar(const EC_GROUP *group, const EVP_MD *md,
EC_SCALAR *out, const uint8_t *dst, size_t dst_len,
unsigned k, const uint8_t *msg, size_t msg_len,
int is_draft06) {
unsigned k, const uint8_t *msg, size_t msg_len) {
size_t L;
uint8_t buf[EC_MAX_BYTES * 2];
if (!num_bytes_to_derive(&L, &group->order, k) ||
!expand_message_xmd(md, buf, L, msg, msg_len, dst, dst_len, is_draft06)) {
!expand_message_xmd(md, buf, L, msg, msg_len, dst, dst_len)) {
return 0;
}
@@ -310,10 +304,9 @@ static int map_to_curve_simple_swu(const EC_GROUP *group, const EC_FELEM *Z,
static int hash_to_curve(const EC_GROUP *group, const EVP_MD *md,
const EC_FELEM *Z, const EC_FELEM *c2, unsigned k,
EC_RAW_POINT *out, const uint8_t *dst, size_t dst_len,
const uint8_t *msg, size_t msg_len, int is_draft06) {
const uint8_t *msg, size_t msg_len) {
EC_FELEM u0, u1;
if (!hash_to_field2(group, md, &u0, &u1, dst, dst_len, k, msg, msg_len,
is_draft06)) {
if (!hash_to_field2(group, md, &u0, &u1, dst, dst_len, k, msg, msg_len)) {
return 0;
}
@@ -376,7 +369,7 @@ int ec_hash_to_curve_p384_xmd_sha512_sswu_draft07(
ec_felem_neg(group, &Z, &Z);
return hash_to_curve(group, EVP_sha512(), &Z, &c2, /*k=*/192, out, dst,
dst_len, msg, msg_len, /*is_draft06=*/0);
dst_len, msg, msg_len);
}
int ec_hash_to_scalar_p384_xmd_sha512_draft07(
@@ -388,38 +381,5 @@ int ec_hash_to_scalar_p384_xmd_sha512_draft07(
}
return hash_to_scalar(group, EVP_sha512(), out, dst, dst_len, /*k=*/192, msg,
msg_len, /*is_draft06=*/0);
}
int ec_hash_to_curve_p521_xmd_sha512_sswu_draft06(
const EC_GROUP *group, EC_RAW_POINT *out, const uint8_t *dst,
size_t dst_len, const uint8_t *msg, size_t msg_len) {
// See section 8.3 of draft-irtf-cfrg-hash-to-curve-06.
if (EC_GROUP_get_curve_name(group) != NID_secp521r1) {
OPENSSL_PUT_ERROR(EC, EC_R_GROUP_MISMATCH);
return 0;
}
// Z = -4, c2 = 8.
EC_FELEM Z, c2;
if (!felem_from_u8(group, &Z, 4) ||
!felem_from_u8(group, &c2, 8)) {
return 0;
}
ec_felem_neg(group, &Z, &Z);
return hash_to_curve(group, EVP_sha512(), &Z, &c2, /*k=*/256, out, dst,
dst_len, msg, msg_len, /*is_draft06=*/1);
}
int ec_hash_to_scalar_p521_xmd_sha512_draft06(
const EC_GROUP *group, EC_SCALAR *out, const uint8_t *dst, size_t dst_len,
const uint8_t *msg, size_t msg_len) {
if (EC_GROUP_get_curve_name(group) != NID_secp521r1) {
OPENSSL_PUT_ERROR(EC, EC_R_GROUP_MISMATCH);
return 0;
}
return hash_to_scalar(group, EVP_sha512(), out, dst, dst_len, /*k=*/256, msg,
msg_len, /*is_draft06=*/1);
msg_len);
}
@@ -48,28 +48,6 @@ OPENSSL_EXPORT int ec_hash_to_scalar_p384_xmd_sha512_draft07(
const EC_GROUP *group, EC_SCALAR *out, const uint8_t *dst, size_t dst_len,
const uint8_t *msg, size_t msg_len);
// ec_hash_to_curve_p521_xmd_sha512_sswu_draft06 hashes |msg| to a point on
// |group| and writes the result to |out|, implementing the
// P521_XMD:SHA-512_SSWU_RO_ suite from draft-irtf-cfrg-hash-to-curve-06. It
// returns one on success and zero on error.
//
// This function implements an older version of the draft and should not be used
// in new code.
OPENSSL_EXPORT int ec_hash_to_curve_p521_xmd_sha512_sswu_draft06(
const EC_GROUP *group, EC_RAW_POINT *out, const uint8_t *dst,
size_t dst_len, const uint8_t *msg, size_t msg_len);
// ec_hash_to_scalar_p521_xmd_sha512_draft06 hashes |msg| to a scalar on |group|
// and writes the result to |out|, using the hash_to_field operation from the
// P521_XMD:SHA-512_SSWU_RO_ suite from draft-irtf-cfrg-hash-to-curve-06, but
// generating a value modulo the group order rather than a field element.
//
// This function implements an older version of the draft and should not be used
// in new code.
OPENSSL_EXPORT int ec_hash_to_scalar_p521_xmd_sha512_draft06(
const EC_GROUP *group, EC_SCALAR *out, const uint8_t *dst, size_t dst_len,
const uint8_t *msg, size_t msg_len);
#if defined(__cplusplus)
} // extern C
+89 -83
View File
@@ -199,36 +199,39 @@ const uint32_t kOpenSSLReasonValues[] = {
0x2c34b058,
0x2c353073,
0x2c35b085,
0x2c363098,
0x2c3630b5,
0x2c36832d,
0x2c3730a5,
0x2c37b0b7,
0x2c3830dc,
0x2c38b0f3,
0x2c393101,
0x2c39b111,
0x2c3a3123,
0x2c3ab137,
0x2c3b3148,
0x2c3bb167,
0x2c3730c2,
0x2c37b0ee,
0x2c383113,
0x2c38b12a,
0x2c393148,
0x2c39b158,
0x2c3a316a,
0x2c3ab17e,
0x2c3b318f,
0x2c3bb1ae,
0x2c3c12fa,
0x2c3c9310,
0x2c3d317b,
0x2c3d31c2,
0x2c3d9329,
0x2c3e3198,
0x2c3eb1a6,
0x2c3f31be,
0x2c3fb1d6,
0x2c403200,
0x2c3e31df,
0x2c3eb1ed,
0x2c3f3205,
0x2c3fb21d,
0x2c403247,
0x2c4091fb,
0x2c413211,
0x2c41b224,
0x2c413258,
0x2c41b26b,
0x2c4211c1,
0x2c42b235,
0x2c42b27c,
0x2c430722,
0x2c43b159,
0x2c4430ca,
0x2c44b1e3,
0x2c43b1a0,
0x2c443101,
0x2c44b22a,
0x2c453098,
0x2c45b0d4,
0x2c463138,
0x30320000,
0x30328015,
0x3033001f,
@@ -654,69 +657,69 @@ const uint32_t kOpenSSLReasonValues[] = {
0x4c411557,
0x4c4193da,
0x4c421543,
0x50323247,
0x5032b256,
0x50333261,
0x5033b271,
0x5034328a,
0x5034b2a4,
0x503532b2,
0x5035b2c8,
0x503632da,
0x5036b2f0,
0x50373309,
0x5037b31c,
0x50383334,
0x5038b345,
0x5039335a,
0x5039b36e,
0x503a338e,
0x503ab3a4,
0x503b33bc,
0x503bb3ce,
0x503c33ea,
0x503cb401,
0x503d341a,
0x503db430,
0x503e343d,
0x503eb453,
0x503f3465,
0x5032328e,
0x5032b29d,
0x503332a8,
0x5033b2b8,
0x503432d1,
0x5034b2eb,
0x503532f9,
0x5035b30f,
0x50363321,
0x5036b337,
0x50373350,
0x5037b363,
0x5038337b,
0x5038b38c,
0x503933a1,
0x5039b3b5,
0x503a33d5,
0x503ab3eb,
0x503b3403,
0x503bb415,
0x503c3431,
0x503cb448,
0x503d3461,
0x503db477,
0x503e3484,
0x503eb49a,
0x503f34ac,
0x503f837b,
0x50403478,
0x5040b488,
0x504134a2,
0x5041b4b1,
0x504234cb,
0x5042b4e8,
0x504334f8,
0x5043b508,
0x50443517,
0x504034bf,
0x5040b4cf,
0x504134e9,
0x5041b4f8,
0x50423512,
0x5042b52f,
0x5043353f,
0x5043b54f,
0x5044355e,
0x50448431,
0x5045352b,
0x5045b549,
0x5046355c,
0x5046b572,
0x50473584,
0x5047b599,
0x504835bf,
0x5048b5cd,
0x504935e0,
0x5049b5f5,
0x504a360b,
0x504ab61b,
0x504b363b,
0x504bb64e,
0x504c3671,
0x504cb69f,
0x504d36b1,
0x504db6ce,
0x504e36e9,
0x504eb705,
0x504f3717,
0x504fb72e,
0x5050373d,
0x50453572,
0x5045b590,
0x504635a3,
0x5046b5b9,
0x504735cb,
0x5047b5e0,
0x50483606,
0x5048b614,
0x50493627,
0x5049b63c,
0x504a3652,
0x504ab662,
0x504b3682,
0x504bb695,
0x504c36b8,
0x504cb6e6,
0x504d36f8,
0x504db715,
0x504e3730,
0x504eb74c,
0x504f375e,
0x504fb775,
0x50503784,
0x505086f1,
0x50513750,
0x50513797,
0x58320f65,
0x68320f27,
0x68328c7f,
@@ -1352,12 +1355,15 @@ const char kOpenSSLReasonStringData[] =
"CERT_ALREADY_IN_HASH_TABLE\0"
"CRL_ALREADY_DELTA\0"
"CRL_VERIFY_FAILURE\0"
"DELTA_CRL_WITHOUT_CRL_NUMBER\0"
"IDP_MISMATCH\0"
"INVALID_DIRECTORY\0"
"INVALID_FIELD_FOR_VERSION\0"
"INVALID_FIELD_NAME\0"
"INVALID_PARAMETER\0"
"INVALID_PSS_PARAMETERS\0"
"INVALID_TRUST\0"
"INVALID_VERSION\0"
"ISSUER_MISMATCH\0"
"KEY_TYPE_MISMATCH\0"
"KEY_VALUES_MISMATCH\0"
@@ -65,6 +65,7 @@
#include <CCryptoBoringSSL_rsa.h>
#include "internal.h"
#include "../bytestring/internal.h"
#include "../internal.h"
@@ -386,3 +387,145 @@ err:
EVP_PKEY_free(ret);
return NULL;
}
EVP_PKEY *d2i_PUBKEY(EVP_PKEY **out, const uint8_t **inp, long len) {
if (len < 0) {
return NULL;
}
CBS cbs;
CBS_init(&cbs, *inp, (size_t)len);
EVP_PKEY *ret = EVP_parse_public_key(&cbs);
if (ret == NULL) {
return NULL;
}
if (out != NULL) {
EVP_PKEY_free(*out);
*out = ret;
}
*inp = CBS_data(&cbs);
return ret;
}
int i2d_PUBKEY(const EVP_PKEY *pkey, uint8_t **outp) {
CBB cbb;
if (!CBB_init(&cbb, 128) ||
!EVP_marshal_public_key(&cbb, pkey)) {
CBB_cleanup(&cbb);
return -1;
}
return CBB_finish_i2d(&cbb, outp);
}
RSA *d2i_RSA_PUBKEY(RSA **out, const uint8_t **inp, long len) {
if (len < 0) {
return NULL;
}
CBS cbs;
CBS_init(&cbs, *inp, (size_t)len);
EVP_PKEY *pkey = EVP_parse_public_key(&cbs);
if (pkey == NULL) {
return NULL;
}
RSA *rsa = EVP_PKEY_get1_RSA(pkey);
EVP_PKEY_free(pkey);
if (rsa == NULL) {
return NULL;
}
if (out != NULL) {
RSA_free(*out);
*out = rsa;
}
*inp = CBS_data(&cbs);
return rsa;
}
int i2d_RSA_PUBKEY(const RSA *rsa, uint8_t **outp) {
int ret = -1;
EVP_PKEY *pkey = EVP_PKEY_new();
if (pkey == NULL ||
!EVP_PKEY_set1_RSA(pkey, (RSA *)rsa)) {
goto err;
}
ret = i2d_PUBKEY(pkey, outp);
err:
EVP_PKEY_free(pkey);
return ret;
}
DSA *d2i_DSA_PUBKEY(DSA **out, const uint8_t **inp, long len) {
if (len < 0) {
return NULL;
}
CBS cbs;
CBS_init(&cbs, *inp, (size_t)len);
EVP_PKEY *pkey = EVP_parse_public_key(&cbs);
if (pkey == NULL) {
return NULL;
}
DSA *dsa = EVP_PKEY_get1_DSA(pkey);
EVP_PKEY_free(pkey);
if (dsa == NULL) {
return NULL;
}
if (out != NULL) {
DSA_free(*out);
*out = dsa;
}
*inp = CBS_data(&cbs);
return dsa;
}
int i2d_DSA_PUBKEY(const DSA *dsa, uint8_t **outp) {
int ret = -1;
EVP_PKEY *pkey = EVP_PKEY_new();
if (pkey == NULL ||
!EVP_PKEY_set1_DSA(pkey, (DSA *)dsa)) {
goto err;
}
ret = i2d_PUBKEY(pkey, outp);
err:
EVP_PKEY_free(pkey);
return ret;
}
EC_KEY *d2i_EC_PUBKEY(EC_KEY **out, const uint8_t **inp, long len) {
if (len < 0) {
return NULL;
}
CBS cbs;
CBS_init(&cbs, *inp, (size_t)len);
EVP_PKEY *pkey = EVP_parse_public_key(&cbs);
if (pkey == NULL) {
return NULL;
}
EC_KEY *ec_key = EVP_PKEY_get1_EC_KEY(pkey);
EVP_PKEY_free(pkey);
if (ec_key == NULL) {
return NULL;
}
if (out != NULL) {
EC_KEY_free(*out);
*out = ec_key;
}
*inp = CBS_data(&cbs);
return ec_key;
}
int i2d_EC_PUBKEY(const EC_KEY *ec_key, uint8_t **outp) {
int ret = -1;
EVP_PKEY *pkey = EVP_PKEY_new();
if (pkey == NULL ||
!EVP_PKEY_set1_EC_KEY(pkey, (EC_KEY *)ec_key)) {
goto err;
}
ret = i2d_PUBKEY(pkey, outp);
err:
EVP_PKEY_free(pkey);
return ret;
}
@@ -404,9 +404,19 @@ uint64_t bn_mont_n0(const BIGNUM *n);
int bn_mod_exp_base_2_consttime(BIGNUM *r, unsigned p, const BIGNUM *n,
BN_CTX *ctx);
#if defined(OPENSSL_X86_64) && defined(_MSC_VER)
#if defined(_MSC_VER)
#if defined(OPENSSL_X86_64)
#define BN_UMULT_LOHI(low, high, a, b) ((low) = _umul128((a), (b), &(high)))
#elif defined(OPENSSL_AARCH64)
#define BN_UMULT_LOHI(low, high, a, b) \
do { \
const BN_ULONG _a = (a); \
const BN_ULONG _b = (b); \
(low) = _a * _b; \
(high) = __umulh(_a, _b); \
} while (0)
#endif
#endif // _MSC_VER
#if !defined(BN_ULLONG) && !defined(BN_UMULT_LOHI)
#error "Either BN_ULLONG or BN_UMULT_LOHI must be defined on every platform."
@@ -703,7 +703,8 @@ void ec_GFp_mont_felem_to_bytes(const EC_GROUP *group, uint8_t *out,
int ec_GFp_mont_felem_from_bytes(const EC_GROUP *group, EC_FELEM *out,
const uint8_t *in, size_t len);
void ec_GFp_nistp_recode_scalar_bits(uint8_t *sign, uint8_t *digit, uint8_t in);
void ec_GFp_nistp_recode_scalar_bits(crypto_word_t *sign, crypto_word_t *digit,
crypto_word_t in);
const EC_METHOD *EC_GFp_nistp224_method(void);
const EC_METHOD *EC_GFp_nistp256_method(void);
@@ -866,7 +866,7 @@ static void p224_select_point(const uint64_t idx, size_t size,
}
// p224_get_bit returns the |i|th bit in |in|
static char p224_get_bit(const p224_felem_bytearray in, size_t i) {
static crypto_word_t p224_get_bit(const p224_felem_bytearray in, size_t i) {
if (i >= 224) {
return 0;
}
@@ -977,13 +977,13 @@ static void ec_GFp_nistp224_point_mul(const EC_GROUP *group, EC_RAW_POINT *r,
// Add every 5 doublings.
if (i % 5 == 0) {
uint64_t bits = p224_get_bit(scalar->bytes, i + 4) << 5;
crypto_word_t bits = p224_get_bit(scalar->bytes, i + 4) << 5;
bits |= p224_get_bit(scalar->bytes, i + 3) << 4;
bits |= p224_get_bit(scalar->bytes, i + 2) << 3;
bits |= p224_get_bit(scalar->bytes, i + 1) << 2;
bits |= p224_get_bit(scalar->bytes, i) << 1;
bits |= p224_get_bit(scalar->bytes, i - 1);
uint8_t sign, digit;
crypto_word_t sign, digit;
ec_GFp_nistp_recode_scalar_bits(&sign, &digit, bits);
// Select the point to add or subtract.
@@ -1022,7 +1022,7 @@ static void ec_GFp_nistp224_point_mul_base(const EC_GROUP *group,
}
// First, look 28 bits upwards.
uint64_t bits = p224_get_bit(scalar->bytes, i + 196) << 3;
crypto_word_t bits = p224_get_bit(scalar->bytes, i + 196) << 3;
bits |= p224_get_bit(scalar->bytes, i + 140) << 2;
bits |= p224_get_bit(scalar->bytes, i + 84) << 1;
bits |= p224_get_bit(scalar->bytes, i + 28);
@@ -1080,14 +1080,15 @@ static void ec_GFp_nistp224_point_mul_public(const EC_GROUP *group,
// Add multiples of the generator.
if (i <= 27) {
// First, look 28 bits upwards.
uint64_t bits = p224_get_bit(g_scalar->bytes, i + 196) << 3;
crypto_word_t bits = p224_get_bit(g_scalar->bytes, i + 196) << 3;
bits |= p224_get_bit(g_scalar->bytes, i + 140) << 2;
bits |= p224_get_bit(g_scalar->bytes, i + 84) << 1;
bits |= p224_get_bit(g_scalar->bytes, i + 28);
size_t index = (size_t)bits;
p224_point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */,
g_p224_pre_comp[1][bits][0], g_p224_pre_comp[1][bits][1],
g_p224_pre_comp[1][bits][2]);
g_p224_pre_comp[1][index][0], g_p224_pre_comp[1][index][1],
g_p224_pre_comp[1][index][2]);
assert(!skip);
// Second, look at the current position.
@@ -1095,20 +1096,21 @@ static void ec_GFp_nistp224_point_mul_public(const EC_GROUP *group,
bits |= p224_get_bit(g_scalar->bytes, i + 112) << 2;
bits |= p224_get_bit(g_scalar->bytes, i + 56) << 1;
bits |= p224_get_bit(g_scalar->bytes, i);
index = (size_t)bits;
p224_point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */,
g_p224_pre_comp[0][bits][0], g_p224_pre_comp[0][bits][1],
g_p224_pre_comp[0][bits][2]);
g_p224_pre_comp[0][index][0], g_p224_pre_comp[0][index][1],
g_p224_pre_comp[0][index][2]);
}
// Incorporate |p_scalar| every 5 doublings.
if (i % 5 == 0) {
uint64_t bits = p224_get_bit(p_scalar->bytes, i + 4) << 5;
crypto_word_t bits = p224_get_bit(p_scalar->bytes, i + 4) << 5;
bits |= p224_get_bit(p_scalar->bytes, i + 3) << 4;
bits |= p224_get_bit(p_scalar->bytes, i + 2) << 3;
bits |= p224_get_bit(p_scalar->bytes, i + 1) << 2;
bits |= p224_get_bit(p_scalar->bytes, i) << 1;
bits |= p224_get_bit(p_scalar->bytes, i - 1);
uint8_t sign, digit;
crypto_word_t sign, digit;
ec_GFp_nistp_recode_scalar_bits(&sign, &digit, bits);
// Select the point to add or subtract.
@@ -52,8 +52,8 @@ static const BN_ULONG ONE[P256_LIMBS] = {
// Recode window to a signed digit, see |ec_GFp_nistp_recode_scalar_bits| in
// util.c for details
static unsigned booth_recode_w5(unsigned in) {
unsigned s, d;
static crypto_word_t booth_recode_w5(crypto_word_t in) {
crypto_word_t s, d;
s = ~((in >> 5) - 1);
d = (1 << 6) - in - 1;
@@ -63,8 +63,8 @@ static unsigned booth_recode_w5(unsigned in) {
return (d << 1) + (s & 1);
}
static unsigned booth_recode_w7(unsigned in) {
unsigned s, d;
static crypto_word_t booth_recode_w7(crypto_word_t in) {
crypto_word_t s, d;
s = ~((in >> 7) - 1);
d = (1 << 8) - in - 1;
@@ -196,8 +196,8 @@ static void ecp_nistz256_windowed_mul(const EC_GROUP *group, P256_POINT *r,
assert(p_scalar != NULL);
assert(group->field.width == P256_LIMBS);
static const unsigned kWindowSize = 5;
static const unsigned kMask = (1 << (5 /* kWindowSize */ + 1)) - 1;
static const size_t kWindowSize = 5;
static const crypto_word_t kMask = (1 << (5 /* kWindowSize */ + 1)) - 1;
// A |P256_POINT| is (3 * 32) = 96 bytes, and the 64-byte alignment should
// add no more than 63 bytes of overhead. Thus, |table| should require
@@ -234,17 +234,17 @@ static void ecp_nistz256_windowed_mul(const EC_GROUP *group, P256_POINT *r,
BN_ULONG tmp[P256_LIMBS];
alignas(32) P256_POINT h;
unsigned index = 255;
unsigned wvalue = p_str[(index - 1) / 8];
size_t index = 255;
crypto_word_t wvalue = p_str[(index - 1) / 8];
wvalue = (wvalue >> ((index - 1) % 8)) & kMask;
ecp_nistz256_select_w5(r, table, booth_recode_w5(wvalue) >> 1);
while (index >= 5) {
if (index != 255) {
unsigned off = (index - 1) / 8;
size_t off = (index - 1) / 8;
wvalue = p_str[off] | p_str[off + 1] << 8;
wvalue = (crypto_word_t)p_str[off] | (crypto_word_t)p_str[off + 1] << 8;
wvalue = (wvalue >> ((index - 1) % 8)) & kMask;
wvalue = booth_recode_w5(wvalue);
@@ -285,21 +285,22 @@ typedef union {
P256_POINT_AFFINE a;
} p256_point_union_t;
static unsigned calc_first_wvalue(unsigned *index, const uint8_t p_str[33]) {
static const unsigned kWindowSize = 7;
static const unsigned kMask = (1 << (7 /* kWindowSize */ + 1)) - 1;
static crypto_word_t calc_first_wvalue(size_t *index, const uint8_t p_str[33]) {
static const size_t kWindowSize = 7;
static const crypto_word_t kMask = (1 << (7 /* kWindowSize */ + 1)) - 1;
*index = kWindowSize;
unsigned wvalue = (p_str[0] << 1) & kMask;
crypto_word_t wvalue = (p_str[0] << 1) & kMask;
return booth_recode_w7(wvalue);
}
static unsigned calc_wvalue(unsigned *index, const uint8_t p_str[33]) {
static const unsigned kWindowSize = 7;
static const unsigned kMask = (1 << (7 /* kWindowSize */ + 1)) - 1;
static crypto_word_t calc_wvalue(size_t *index, const uint8_t p_str[33]) {
static const size_t kWindowSize = 7;
static const crypto_word_t kMask = (1 << (7 /* kWindowSize */ + 1)) - 1;
const unsigned off = (*index - 1) / 8;
unsigned wvalue = p_str[off] | p_str[off + 1] << 8;
const size_t off = (*index - 1) / 8;
crypto_word_t wvalue =
(crypto_word_t)p_str[off] | (crypto_word_t)p_str[off + 1] << 8;
wvalue = (wvalue >> ((*index - 1) % 8)) & kMask;
*index += kWindowSize;
@@ -327,8 +328,8 @@ static void ecp_nistz256_point_mul_base(const EC_GROUP *group, EC_RAW_POINT *r,
p_str[32] = 0;
// First window
unsigned index = 0;
unsigned wvalue = calc_first_wvalue(&index, p_str);
size_t index = 0;
crypto_word_t wvalue = calc_first_wvalue(&index, p_str);
ecp_nistz256_select_w7(&p.a, ecp_nistz256_precomputed[0], wvalue >> 1);
ecp_nistz256_neg(p.p.Z, p.p.Y);
@@ -372,8 +373,8 @@ static void ecp_nistz256_points_mul_public(const EC_GROUP *group,
p_str[32] = 0;
// First window
unsigned index = 0;
unsigned wvalue = calc_first_wvalue(&index, p_str);
size_t index = 0;
size_t wvalue = calc_first_wvalue(&index, p_str);
// Convert |p| from affine to Jacobian coordinates. We set Z to zero if |p|
// is infinity and |ONE| otherwise. |p| was computed from the table, so it
@@ -67,7 +67,7 @@ static fiat_p256_limb_t fiat_p256_nz(
static void fiat_p256_copy(fiat_p256_limb_t out[FIAT_P256_NLIMBS],
const fiat_p256_limb_t in1[FIAT_P256_NLIMBS]) {
for (int i = 0; i < FIAT_P256_NLIMBS; i++) {
for (size_t i = 0; i < FIAT_P256_NLIMBS; i++) {
out[i] = in1[i];
}
}
@@ -393,7 +393,7 @@ static void fiat_p256_select_point(const fiat_p256_limb_t idx, size_t size,
}
// fiat_p256_get_bit returns the |i|th bit in |in|
static char fiat_p256_get_bit(const uint8_t *in, int i) {
static crypto_word_t fiat_p256_get_bit(const uint8_t *in, int i) {
if (i < 0 || i >= 256) {
return 0;
}
@@ -498,20 +498,20 @@ static void ec_GFp_nistp256_point_mul(const EC_GROUP *group, EC_RAW_POINT *r,
// do other additions every 5 doublings
if (i % 5 == 0) {
uint64_t bits = fiat_p256_get_bit(scalar->bytes, i + 4) << 5;
crypto_word_t bits = fiat_p256_get_bit(scalar->bytes, i + 4) << 5;
bits |= fiat_p256_get_bit(scalar->bytes, i + 3) << 4;
bits |= fiat_p256_get_bit(scalar->bytes, i + 2) << 3;
bits |= fiat_p256_get_bit(scalar->bytes, i + 1) << 2;
bits |= fiat_p256_get_bit(scalar->bytes, i) << 1;
bits |= fiat_p256_get_bit(scalar->bytes, i - 1);
uint8_t sign, digit;
crypto_word_t sign, digit;
ec_GFp_nistp_recode_scalar_bits(&sign, &digit, bits);
// select the point to add or subtract, in constant time.
fiat_p256_select_point(digit, 17, (const fiat_p256_felem(*)[3])p_pre_comp,
tmp);
fiat_p256_select_point((fiat_p256_limb_t)digit, 17,
(const fiat_p256_felem(*)[3])p_pre_comp, tmp);
fiat_p256_opp(ftmp, tmp[1]); // (X, -Y, Z) is the negative point.
fiat_p256_cmovznz(tmp[1], sign, tmp[1], ftmp);
fiat_p256_cmovznz(tmp[1], (fiat_p256_limb_t)sign, tmp[1], ftmp);
if (!skip) {
fiat_p256_point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2],
@@ -543,12 +543,13 @@ static void ec_GFp_nistp256_point_mul_base(const EC_GROUP *group,
}
// First, look 32 bits upwards.
uint64_t bits = fiat_p256_get_bit(scalar->bytes, i + 224) << 3;
crypto_word_t bits = fiat_p256_get_bit(scalar->bytes, i + 224) << 3;
bits |= fiat_p256_get_bit(scalar->bytes, i + 160) << 2;
bits |= fiat_p256_get_bit(scalar->bytes, i + 96) << 1;
bits |= fiat_p256_get_bit(scalar->bytes, i + 32);
// Select the point to add, in constant time.
fiat_p256_select_point_affine(bits, 15, fiat_p256_g_pre_comp[1], tmp);
fiat_p256_select_point_affine((fiat_p256_limb_t)bits, 15,
fiat_p256_g_pre_comp[1], tmp);
if (!skip) {
fiat_p256_point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2],
@@ -566,7 +567,8 @@ static void ec_GFp_nistp256_point_mul_base(const EC_GROUP *group,
bits |= fiat_p256_get_bit(scalar->bytes, i + 64) << 1;
bits |= fiat_p256_get_bit(scalar->bytes, i);
// Select the point to add, in constant time.
fiat_p256_select_point_affine(bits, 15, fiat_p256_g_pre_comp[0], tmp);
fiat_p256_select_point_affine((fiat_p256_limb_t)bits, 15,
fiat_p256_g_pre_comp[0], tmp);
fiat_p256_point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */,
tmp[0], tmp[1], tmp[2]);
}
@@ -613,14 +615,15 @@ static void ec_GFp_nistp256_point_mul_public(const EC_GROUP *group,
// constant-time lookup.
if (i <= 31) {
// First, look 32 bits upwards.
uint64_t bits = fiat_p256_get_bit(g_scalar->bytes, i + 224) << 3;
crypto_word_t bits = fiat_p256_get_bit(g_scalar->bytes, i + 224) << 3;
bits |= fiat_p256_get_bit(g_scalar->bytes, i + 160) << 2;
bits |= fiat_p256_get_bit(g_scalar->bytes, i + 96) << 1;
bits |= fiat_p256_get_bit(g_scalar->bytes, i + 32);
if (bits != 0) {
size_t index = (size_t)(bits - 1);
fiat_p256_point_add(ret[0], ret[1], ret[2], ret[0], ret[1], ret[2],
1 /* mixed */, fiat_p256_g_pre_comp[1][bits - 1][0],
fiat_p256_g_pre_comp[1][bits - 1][1],
1 /* mixed */, fiat_p256_g_pre_comp[1][index][0],
fiat_p256_g_pre_comp[1][index][1],
fiat_p256_one);
skip = 0;
}
@@ -631,9 +634,10 @@ static void ec_GFp_nistp256_point_mul_public(const EC_GROUP *group,
bits |= fiat_p256_get_bit(g_scalar->bytes, i + 64) << 1;
bits |= fiat_p256_get_bit(g_scalar->bytes, i);
if (bits != 0) {
size_t index = (size_t)(bits - 1);
fiat_p256_point_add(ret[0], ret[1], ret[2], ret[0], ret[1], ret[2],
1 /* mixed */, fiat_p256_g_pre_comp[0][bits - 1][0],
fiat_p256_g_pre_comp[0][bits - 1][1],
1 /* mixed */, fiat_p256_g_pre_comp[0][index][0],
fiat_p256_g_pre_comp[0][index][1],
fiat_p256_one);
skip = 0;
}
@@ -642,7 +646,7 @@ static void ec_GFp_nistp256_point_mul_public(const EC_GROUP *group,
int digit = p_wNAF[i];
if (digit != 0) {
assert(digit & 1);
int idx = digit < 0 ? (-digit) >> 1 : digit >> 1;
size_t idx = (size_t)(digit < 0 ? (-digit) >> 1 : digit >> 1);
fiat_p256_felem *y = &p_pre_comp[idx][1], tmp;
if (digit < 0) {
fiat_p256_opp(tmp, p_pre_comp[idx][1]);
@@ -108,7 +108,7 @@ static void ec_GFp_mont_batch_get_window(const EC_GROUP *group,
if (i > 0) {
window |= bn_is_bit_set_words(scalar->words, width, i - 1);
}
uint8_t sign, digit;
crypto_word_t sign, digit;
ec_GFp_nistp_recode_scalar_bits(&sign, &digit, window);
// Select the entry in constant-time.
@@ -121,7 +121,7 @@ static void ec_GFp_mont_batch_get_window(const EC_GROUP *group,
// Negate if necessary.
EC_FELEM neg_Y;
ec_felem_neg(group, &neg_Y, &out->Y);
BN_ULONG sign_mask = sign;
crypto_word_t sign_mask = sign;
sign_mask = 0u - sign_mask;
ec_felem_select(group, &out->Y, sign_mask, &neg_Y, &out->Y);
}
@@ -240,9 +240,9 @@
// P-384: ...01110011; w = 2, 5, 6, 7 are okay
// P-256: ...01010001; w = 5, 7 are okay
// P-224: ...00111101; w = 3, 4, 5, 6 are okay
void ec_GFp_nistp_recode_scalar_bits(uint8_t *sign, uint8_t *digit,
uint8_t in) {
uint8_t s, d;
void ec_GFp_nistp_recode_scalar_bits(crypto_word_t *sign, crypto_word_t *digit,
crypto_word_t in) {
crypto_word_t s, d;
s = ~((in >> 5) - 1); /* sets all bits to MSB(in), 'in' seen as
* 6-bit value */
@@ -21,6 +21,7 @@
#include <CCryptoBoringSSL_aes.h>
#include <CCryptoBoringSSL_bn.h>
#include <CCryptoBoringSSL_des.h>
#include <CCryptoBoringSSL_ec.h>
#include <CCryptoBoringSSL_ecdsa.h>
#include <CCryptoBoringSSL_ec_key.h>
#include <CCryptoBoringSSL_nid.h>
@@ -430,11 +431,44 @@ int boringssl_fips_self_test(
0xba, 0x4d, 0xd9, 0x86, 0x77, 0xda, 0x7d, 0x8f, 0xef, 0xc4, 0x1a,
0xf0, 0xcc, 0x81, 0xe5, 0xea, 0x3f, 0xc2, 0x41, 0x7f, 0xd8,
};
// kP256Point is SHA256("Primitive Z Computation KAT")×G within P-256.
const uint8_t kP256Point[65] = {
0x04, 0x4e, 0xc1, 0x94, 0x8c, 0x5c, 0xf4, 0x37, 0x35, 0x0d, 0xa3,
0xf9, 0x55, 0xf9, 0x8b, 0x26, 0x23, 0x5c, 0x43, 0xe0, 0x83, 0x51,
0x2b, 0x0d, 0x4b, 0x56, 0x24, 0xc3, 0xe4, 0xa5, 0xa8, 0xe2, 0xe9,
0x95, 0xf2, 0xc4, 0xb9, 0xb7, 0x48, 0x7d, 0x2a, 0xae, 0xc5, 0xc0,
0x0a, 0xcc, 0x1b, 0xd0, 0xec, 0xb8, 0xdc, 0xbe, 0x0c, 0xbe, 0x52,
0x79, 0x93, 0x7c, 0x0b, 0x92, 0x2b, 0x7f, 0x17, 0xa5, 0x80,
};
// kP256Scalar is SHA256("Primitive Z Computation KAT scalar").
const uint8_t kP256Scalar[32] = {
0xe7, 0x60, 0x44, 0x91, 0x26, 0x9a, 0xfb, 0x5b, 0x10, 0x2d, 0x6e,
0xa5, 0x2c, 0xb5, 0x9f, 0xeb, 0x70, 0xae, 0xde, 0x6c, 0xe3, 0xbf,
0xb3, 0xe0, 0x10, 0x54, 0x85, 0xab, 0xd8, 0x61, 0xd7, 0x7b,
};
// kP256PointResult is |kP256Scalar|×|kP256Point|.
const uint8_t kP256PointResult[65] = {
0x04, 0xf1, 0x63, 0x00, 0x88, 0xc5, 0xd5, 0xe9, 0x05, 0x52, 0xac,
0xb6, 0xec, 0x68, 0x76, 0xb8, 0x73, 0x7f, 0x0f, 0x72, 0x34, 0xe6,
0xbb, 0x30, 0x32, 0x22, 0x37, 0xb6, 0x2a, 0x80, 0xe8, 0x9e, 0x6e,
0x6f, 0x36, 0x02, 0xe7, 0x21, 0xd2, 0x31, 0xdb, 0x94, 0x63, 0xb7,
0xd8, 0x19, 0x0e, 0xc2, 0xc0, 0xa7, 0x2f, 0x15, 0x49, 0x1a, 0xa2,
0x7c, 0x41, 0x8f, 0xaf, 0x9c, 0x40, 0xaf, 0x2e, 0x4a,
#if !defined(BORINGSSL_FIPS_BREAK_Z_COMPUTATION)
0x0c,
#else
0x00,
#endif
};
EVP_AEAD_CTX aead_ctx;
EVP_AEAD_CTX_zero(&aead_ctx);
RSA *rsa_key = NULL;
EC_KEY *ec_key = NULL;
EC_GROUP *ec_group = NULL;
EC_POINT *ec_point_in = NULL;
EC_POINT *ec_point_out = NULL;
BIGNUM *ec_scalar = NULL;
ECDSA_SIG *sig = NULL;
int ret = 0;
@@ -602,6 +636,30 @@ int boringssl_fips_self_test(
goto err;
}
// Primitive Z Computation KAT (IG 9.6).
ec_group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
if (ec_group == NULL) {
fprintf(stderr, "Failed to create P-256 group.\n");
goto err;
}
ec_point_in = EC_POINT_new(ec_group);
ec_point_out = EC_POINT_new(ec_group);
ec_scalar = BN_new();
uint8_t z_comp_result[65];
if (ec_point_in == NULL || ec_point_out == NULL || ec_scalar == NULL ||
!EC_POINT_oct2point(ec_group, ec_point_in, kP256Point, sizeof(kP256Point),
NULL) ||
!BN_bin2bn(kP256Scalar, sizeof(kP256Scalar), ec_scalar) ||
!EC_POINT_mul(ec_group, ec_point_out, NULL, ec_point_in, ec_scalar,
NULL) ||
!EC_POINT_point2oct(ec_group, ec_point_out, POINT_CONVERSION_UNCOMPRESSED,
z_comp_result, sizeof(z_comp_result), NULL) ||
!check_test(kP256PointResult, z_comp_result, sizeof(z_comp_result),
"Z Computation Result")) {
fprintf(stderr, "Z Computation KAT failed.\n");
goto err;
}
// DBRG KAT
CTR_DRBG_STATE drbg;
if (!CTR_DRBG_init(&drbg, kDRBGEntropy, kDRBGPersonalization,
@@ -642,6 +700,10 @@ err:
EVP_AEAD_CTX_cleanup(&aead_ctx);
RSA_free(rsa_key);
EC_KEY_free(ec_key);
EC_POINT_free(ec_point_in);
EC_POINT_free(ec_point_out);
EC_GROUP_free(ec_group);
BN_free(ec_scalar);
ECDSA_SIG_free(sig);
return ret;
@@ -29,6 +29,8 @@ sha1_block_data_order:
movl 8(%r10),%r10d
testl $512,%r8d
jz .Lialu
testl $536870912,%r10d
jnz _shaext_shortcut
andl $296,%r10d
cmpl $296,%r10d
je _avx2_shortcut
@@ -1271,6 +1273,175 @@ sha1_block_data_order:
.byte 0xf3,0xc3
.cfi_endproc
.size sha1_block_data_order,.-sha1_block_data_order
.type sha1_block_data_order_shaext,@function
.align 32
sha1_block_data_order_shaext:
_shaext_shortcut:
.cfi_startproc
movdqu (%rdi),%xmm0
movd 16(%rdi),%xmm1
movdqa K_XX_XX+160(%rip),%xmm3
movdqu (%rsi),%xmm4
pshufd $27,%xmm0,%xmm0
movdqu 16(%rsi),%xmm5
pshufd $27,%xmm1,%xmm1
movdqu 32(%rsi),%xmm6
.byte 102,15,56,0,227
movdqu 48(%rsi),%xmm7
.byte 102,15,56,0,235
.byte 102,15,56,0,243
movdqa %xmm1,%xmm9
.byte 102,15,56,0,251
jmp .Loop_shaext
.align 16
.Loop_shaext:
decq %rdx
leaq 64(%rsi),%r8
paddd %xmm4,%xmm1
cmovneq %r8,%rsi
movdqa %xmm0,%xmm8
.byte 15,56,201,229
movdqa %xmm0,%xmm2
.byte 15,58,204,193,0
.byte 15,56,200,213
pxor %xmm6,%xmm4
.byte 15,56,201,238
.byte 15,56,202,231
movdqa %xmm0,%xmm1
.byte 15,58,204,194,0
.byte 15,56,200,206
pxor %xmm7,%xmm5
.byte 15,56,202,236
.byte 15,56,201,247
movdqa %xmm0,%xmm2
.byte 15,58,204,193,0
.byte 15,56,200,215
pxor %xmm4,%xmm6
.byte 15,56,201,252
.byte 15,56,202,245
movdqa %xmm0,%xmm1
.byte 15,58,204,194,0
.byte 15,56,200,204
pxor %xmm5,%xmm7
.byte 15,56,202,254
.byte 15,56,201,229
movdqa %xmm0,%xmm2
.byte 15,58,204,193,0
.byte 15,56,200,213
pxor %xmm6,%xmm4
.byte 15,56,201,238
.byte 15,56,202,231
movdqa %xmm0,%xmm1
.byte 15,58,204,194,1
.byte 15,56,200,206
pxor %xmm7,%xmm5
.byte 15,56,202,236
.byte 15,56,201,247
movdqa %xmm0,%xmm2
.byte 15,58,204,193,1
.byte 15,56,200,215
pxor %xmm4,%xmm6
.byte 15,56,201,252
.byte 15,56,202,245
movdqa %xmm0,%xmm1
.byte 15,58,204,194,1
.byte 15,56,200,204
pxor %xmm5,%xmm7
.byte 15,56,202,254
.byte 15,56,201,229
movdqa %xmm0,%xmm2
.byte 15,58,204,193,1
.byte 15,56,200,213
pxor %xmm6,%xmm4
.byte 15,56,201,238
.byte 15,56,202,231
movdqa %xmm0,%xmm1
.byte 15,58,204,194,1
.byte 15,56,200,206
pxor %xmm7,%xmm5
.byte 15,56,202,236
.byte 15,56,201,247
movdqa %xmm0,%xmm2
.byte 15,58,204,193,2
.byte 15,56,200,215
pxor %xmm4,%xmm6
.byte 15,56,201,252
.byte 15,56,202,245
movdqa %xmm0,%xmm1
.byte 15,58,204,194,2
.byte 15,56,200,204
pxor %xmm5,%xmm7
.byte 15,56,202,254
.byte 15,56,201,229
movdqa %xmm0,%xmm2
.byte 15,58,204,193,2
.byte 15,56,200,213
pxor %xmm6,%xmm4
.byte 15,56,201,238
.byte 15,56,202,231
movdqa %xmm0,%xmm1
.byte 15,58,204,194,2
.byte 15,56,200,206
pxor %xmm7,%xmm5
.byte 15,56,202,236
.byte 15,56,201,247
movdqa %xmm0,%xmm2
.byte 15,58,204,193,2
.byte 15,56,200,215
pxor %xmm4,%xmm6
.byte 15,56,201,252
.byte 15,56,202,245
movdqa %xmm0,%xmm1
.byte 15,58,204,194,3
.byte 15,56,200,204
pxor %xmm5,%xmm7
.byte 15,56,202,254
movdqu (%rsi),%xmm4
movdqa %xmm0,%xmm2
.byte 15,58,204,193,3
.byte 15,56,200,213
movdqu 16(%rsi),%xmm5
.byte 102,15,56,0,227
movdqa %xmm0,%xmm1
.byte 15,58,204,194,3
.byte 15,56,200,206
movdqu 32(%rsi),%xmm6
.byte 102,15,56,0,235
movdqa %xmm0,%xmm2
.byte 15,58,204,193,3
.byte 15,56,200,215
movdqu 48(%rsi),%xmm7
.byte 102,15,56,0,243
movdqa %xmm0,%xmm1
.byte 15,58,204,194,3
.byte 65,15,56,200,201
.byte 102,15,56,0,251
paddd %xmm8,%xmm0
movdqa %xmm1,%xmm9
jnz .Loop_shaext
pshufd $27,%xmm0,%xmm0
pshufd $27,%xmm1,%xmm1
movdqu %xmm0,(%rdi)
movd %xmm1,16(%rdi)
.byte 0xf3,0xc3
.cfi_endproc
.size sha1_block_data_order_shaext,.-sha1_block_data_order_shaext
.type sha1_block_data_order_ssse3,@function
.align 16
sha1_block_data_order_ssse3:
@@ -28,6 +28,8 @@ _sha1_block_data_order:
movl 8(%r10),%r10d
testl $512,%r8d
jz L$ialu
testl $536870912,%r10d
jnz _shaext_shortcut
andl $296,%r10d
cmpl $296,%r10d
je _avx2_shortcut
@@ -1271,6 +1273,175 @@ L$epilogue:
.p2align 5
sha1_block_data_order_shaext:
_shaext_shortcut:
movdqu (%rdi),%xmm0
movd 16(%rdi),%xmm1
movdqa K_XX_XX+160(%rip),%xmm3
movdqu (%rsi),%xmm4
pshufd $27,%xmm0,%xmm0
movdqu 16(%rsi),%xmm5
pshufd $27,%xmm1,%xmm1
movdqu 32(%rsi),%xmm6
.byte 102,15,56,0,227
movdqu 48(%rsi),%xmm7
.byte 102,15,56,0,235
.byte 102,15,56,0,243
movdqa %xmm1,%xmm9
.byte 102,15,56,0,251
jmp L$oop_shaext
.p2align 4
L$oop_shaext:
decq %rdx
leaq 64(%rsi),%r8
paddd %xmm4,%xmm1
cmovneq %r8,%rsi
movdqa %xmm0,%xmm8
.byte 15,56,201,229
movdqa %xmm0,%xmm2
.byte 15,58,204,193,0
.byte 15,56,200,213
pxor %xmm6,%xmm4
.byte 15,56,201,238
.byte 15,56,202,231
movdqa %xmm0,%xmm1
.byte 15,58,204,194,0
.byte 15,56,200,206
pxor %xmm7,%xmm5
.byte 15,56,202,236
.byte 15,56,201,247
movdqa %xmm0,%xmm2
.byte 15,58,204,193,0
.byte 15,56,200,215
pxor %xmm4,%xmm6
.byte 15,56,201,252
.byte 15,56,202,245
movdqa %xmm0,%xmm1
.byte 15,58,204,194,0
.byte 15,56,200,204
pxor %xmm5,%xmm7
.byte 15,56,202,254
.byte 15,56,201,229
movdqa %xmm0,%xmm2
.byte 15,58,204,193,0
.byte 15,56,200,213
pxor %xmm6,%xmm4
.byte 15,56,201,238
.byte 15,56,202,231
movdqa %xmm0,%xmm1
.byte 15,58,204,194,1
.byte 15,56,200,206
pxor %xmm7,%xmm5
.byte 15,56,202,236
.byte 15,56,201,247
movdqa %xmm0,%xmm2
.byte 15,58,204,193,1
.byte 15,56,200,215
pxor %xmm4,%xmm6
.byte 15,56,201,252
.byte 15,56,202,245
movdqa %xmm0,%xmm1
.byte 15,58,204,194,1
.byte 15,56,200,204
pxor %xmm5,%xmm7
.byte 15,56,202,254
.byte 15,56,201,229
movdqa %xmm0,%xmm2
.byte 15,58,204,193,1
.byte 15,56,200,213
pxor %xmm6,%xmm4
.byte 15,56,201,238
.byte 15,56,202,231
movdqa %xmm0,%xmm1
.byte 15,58,204,194,1
.byte 15,56,200,206
pxor %xmm7,%xmm5
.byte 15,56,202,236
.byte 15,56,201,247
movdqa %xmm0,%xmm2
.byte 15,58,204,193,2
.byte 15,56,200,215
pxor %xmm4,%xmm6
.byte 15,56,201,252
.byte 15,56,202,245
movdqa %xmm0,%xmm1
.byte 15,58,204,194,2
.byte 15,56,200,204
pxor %xmm5,%xmm7
.byte 15,56,202,254
.byte 15,56,201,229
movdqa %xmm0,%xmm2
.byte 15,58,204,193,2
.byte 15,56,200,213
pxor %xmm6,%xmm4
.byte 15,56,201,238
.byte 15,56,202,231
movdqa %xmm0,%xmm1
.byte 15,58,204,194,2
.byte 15,56,200,206
pxor %xmm7,%xmm5
.byte 15,56,202,236
.byte 15,56,201,247
movdqa %xmm0,%xmm2
.byte 15,58,204,193,2
.byte 15,56,200,215
pxor %xmm4,%xmm6
.byte 15,56,201,252
.byte 15,56,202,245
movdqa %xmm0,%xmm1
.byte 15,58,204,194,3
.byte 15,56,200,204
pxor %xmm5,%xmm7
.byte 15,56,202,254
movdqu (%rsi),%xmm4
movdqa %xmm0,%xmm2
.byte 15,58,204,193,3
.byte 15,56,200,213
movdqu 16(%rsi),%xmm5
.byte 102,15,56,0,227
movdqa %xmm0,%xmm1
.byte 15,58,204,194,3
.byte 15,56,200,206
movdqu 32(%rsi),%xmm6
.byte 102,15,56,0,235
movdqa %xmm0,%xmm2
.byte 15,58,204,193,3
.byte 15,56,200,215
movdqu 48(%rsi),%xmm7
.byte 102,15,56,0,243
movdqa %xmm0,%xmm1
.byte 15,58,204,194,3
.byte 65,15,56,200,201
.byte 102,15,56,0,251
paddd %xmm8,%xmm0
movdqa %xmm1,%xmm9
jnz L$oop_shaext
pshufd $27,%xmm0,%xmm0
pshufd $27,%xmm1,%xmm1
movdqu %xmm0,(%rdi)
movd %xmm1,16(%rdi)
.byte 0xf3,0xc3
.p2align 4
sha1_block_data_order_ssse3:
_ssse3_shortcut:
+29 -15
View File
@@ -72,6 +72,8 @@ OPENSSL_MSVC_PRAGMA(warning(pop))
#define OPENSSL_MALLOC_PREFIX 8
OPENSSL_STATIC_ASSERT(OPENSSL_MALLOC_PREFIX >= sizeof(size_t),
"size_t too large");
#if defined(OPENSSL_ASAN)
void __asan_poison_memory_region(const volatile void *addr, size_t size);
@@ -101,13 +103,21 @@ static void __asan_unpoison_memory_region(const void *addr, size_t size) {}
// linked. This isn't an ideal result, but its helps in some cases.
WEAK_SYMBOL_FUNC(void, sdallocx, (void *ptr, size_t size, int flags));
// The following two functions are for memory tracking. They are no-ops by
// default but can be overridden at link time if the application needs to
// observe heap operations.
WEAK_SYMBOL_FUNC(void, OPENSSL_track_memory_alloc, (void *ptr, size_t size));
WEAK_SYMBOL_FUNC(void, OPENSSL_track_memory_free, (void *ptr, size_t size));
// The following three functions can be defined to override default heap
// allocation and freeing. If defined, it is the responsibility of
// |OPENSSL_memory_free| to zero out the memory before returning it to the
// system. |OPENSSL_memory_free| will not be passed NULL pointers.
WEAK_SYMBOL_FUNC(void*, OPENSSL_memory_alloc, (size_t size));
WEAK_SYMBOL_FUNC(void, OPENSSL_memory_free, (void *ptr));
WEAK_SYMBOL_FUNC(size_t, OPENSSL_memory_get_size, (void *ptr));
void *OPENSSL_malloc(size_t size) {
if (OPENSSL_memory_alloc != NULL) {
assert(OPENSSL_memory_free != NULL);
assert(OPENSSL_memory_get_size != NULL);
return OPENSSL_memory_alloc(size);
}
if (size + OPENSSL_MALLOC_PREFIX < size) {
return NULL;
}
@@ -120,9 +130,6 @@ void *OPENSSL_malloc(size_t size) {
*(size_t *)ptr = size;
__asan_poison_memory_region(ptr, OPENSSL_MALLOC_PREFIX);
if (OPENSSL_track_memory_alloc) {
OPENSSL_track_memory_alloc(ptr, size + OPENSSL_MALLOC_PREFIX);
}
return ((uint8_t *)ptr) + OPENSSL_MALLOC_PREFIX;
}
@@ -131,13 +138,15 @@ void OPENSSL_free(void *orig_ptr) {
return;
}
if (OPENSSL_memory_free != NULL) {
OPENSSL_memory_free(orig_ptr);
return;
}
void *ptr = ((uint8_t *)orig_ptr) - OPENSSL_MALLOC_PREFIX;
__asan_unpoison_memory_region(ptr, OPENSSL_MALLOC_PREFIX);
size_t size = *(size_t *)ptr;
if (OPENSSL_track_memory_free) {
OPENSSL_track_memory_free(ptr, size + OPENSSL_MALLOC_PREFIX);
}
OPENSSL_cleanse(ptr, size + OPENSSL_MALLOC_PREFIX);
if (sdallocx) {
sdallocx(ptr, size + OPENSSL_MALLOC_PREFIX, 0 /* flags */);
@@ -151,10 +160,15 @@ void *OPENSSL_realloc(void *orig_ptr, size_t new_size) {
return OPENSSL_malloc(new_size);
}
void *ptr = ((uint8_t *)orig_ptr) - OPENSSL_MALLOC_PREFIX;
__asan_unpoison_memory_region(ptr, OPENSSL_MALLOC_PREFIX);
size_t old_size = *(size_t *)ptr;
__asan_poison_memory_region(ptr, OPENSSL_MALLOC_PREFIX);
size_t old_size;
if (OPENSSL_memory_get_size != NULL) {
old_size = OPENSSL_memory_get_size(orig_ptr);
} else {
void *ptr = ((uint8_t *)orig_ptr) - OPENSSL_MALLOC_PREFIX;
__asan_unpoison_memory_region(ptr, OPENSSL_MALLOC_PREFIX);
old_size = *(size_t *)ptr;
__asan_poison_memory_region(ptr, OPENSSL_MALLOC_PREFIX);
}
void *ret = OPENSSL_malloc(new_size);
if (ret == NULL) {
@@ -63,6 +63,13 @@ extern "C" {
#endif
struct pkcs8_priv_key_info_st {
ASN1_INTEGER *version;
X509_ALGOR *pkeyalg;
ASN1_OCTET_STRING *pkey;
STACK_OF(X509_ATTRIBUTE) *attributes;
};
// pkcs8_pbe_decrypt decrypts |in| using the PBE scheme described by
// |algorithm|, which should be a serialized AlgorithmIdentifier structure. On
// success, it sets |*out| to a newly-allocated buffer containing the decrypted
@@ -96,10 +96,8 @@ static int pkey_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
// Since the structure must still be valid use ASN1_OP_FREE_PRE
if (operation == ASN1_OP_FREE_PRE) {
PKCS8_PRIV_KEY_INFO *key = (PKCS8_PRIV_KEY_INFO *)*pval;
if (key->pkey && key->pkey->type == V_ASN1_OCTET_STRING &&
key->pkey->value.octet_string) {
OPENSSL_cleanse(key->pkey->value.octet_string->data,
key->pkey->value.octet_string->length);
if (key->pkey) {
OPENSSL_cleanse(key->pkey->data, key->pkey->length);
}
}
return 1;
@@ -108,12 +106,45 @@ static int pkey_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
ASN1_SEQUENCE_cb(PKCS8_PRIV_KEY_INFO, pkey_cb) = {
ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, version, ASN1_INTEGER),
ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, pkeyalg, X509_ALGOR),
ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, pkey, ASN1_ANY),
ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, pkey, ASN1_OCTET_STRING),
ASN1_IMP_SET_OF_OPT(PKCS8_PRIV_KEY_INFO, attributes, X509_ATTRIBUTE, 0)
} ASN1_SEQUENCE_END_cb(PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO)
IMPLEMENT_ASN1_FUNCTIONS(PKCS8_PRIV_KEY_INFO)
int PKCS8_pkey_set0(PKCS8_PRIV_KEY_INFO *priv, ASN1_OBJECT *aobj, int version,
int ptype, void *pval, uint8_t *penc, int penclen) {
if (version >= 0 &&
!ASN1_INTEGER_set(priv->version, version)) {
return 0;
}
if (!X509_ALGOR_set0(priv->pkeyalg, aobj, ptype, pval)) {
return 0;
}
if (penc != NULL) {
ASN1_STRING_set0(priv->pkey, penc, penclen);
}
return 1;
}
int PKCS8_pkey_get0(ASN1_OBJECT **ppkalg, const uint8_t **pk, int *ppklen,
X509_ALGOR **pa, PKCS8_PRIV_KEY_INFO *p8) {
if (ppkalg) {
*ppkalg = p8->pkeyalg->algorithm;
}
if (pk) {
*pk = ASN1_STRING_data(p8->pkey);
*ppklen = ASN1_STRING_length(p8->pkey);
}
if (pa) {
*pa = p8->pkeyalg;
}
return 1;
}
EVP_PKEY *EVP_PKCS82PKEY(PKCS8_PRIV_KEY_INFO *p8) {
uint8_t *der = NULL;
int der_len = i2d_PKCS8_PRIV_KEY_INFO(p8, &der);
@@ -77,27 +77,6 @@ OPENSSL_EXPORT void PMBTOKEN_PRETOKEN_free(PMBTOKEN_PRETOKEN *token);
DEFINE_STACK_OF(PMBTOKEN_PRETOKEN)
// The following functions implement the corresponding |TRUST_TOKENS_METHOD|
// functions for |TRUST_TOKENS_experiment_v0|'s PMBTokens construction which
// uses P-521.
int pmbtoken_exp0_generate_key(CBB *out_private, CBB *out_public);
int pmbtoken_exp0_client_key_from_bytes(PMBTOKEN_CLIENT_KEY *key,
const uint8_t *in, size_t len);
int pmbtoken_exp0_issuer_key_from_bytes(PMBTOKEN_ISSUER_KEY *key,
const uint8_t *in, size_t len);
STACK_OF(PMBTOKEN_PRETOKEN) * pmbtoken_exp0_blind(CBB *cbb, size_t count);
int pmbtoken_exp0_sign(const PMBTOKEN_ISSUER_KEY *key, CBB *cbb, CBS *cbs,
size_t num_requested, size_t num_to_issue,
uint8_t private_metadata);
STACK_OF(TRUST_TOKEN) *
pmbtoken_exp0_unblind(const PMBTOKEN_CLIENT_KEY *key,
const STACK_OF(PMBTOKEN_PRETOKEN) * pretokens,
CBS *cbs, size_t count, uint32_t key_id);
int pmbtoken_exp0_read(const PMBTOKEN_ISSUER_KEY *key,
uint8_t out_nonce[PMBTOKEN_NONCE_SIZE],
uint8_t *out_private_metadata, const uint8_t *token,
size_t token_len);
// The following functions implement the corresponding |TRUST_TOKENS_METHOD|
// functions for |TRUST_TOKENS_experiment_v1|'s PMBTokens construction which
// uses P-384.
@@ -193,14 +172,6 @@ struct trust_token_method_st {
uint8_t out_nonce[PMBTOKEN_NONCE_SIZE],
uint8_t *out_private_metadata, const uint8_t *token,
size_t token_len);
// use_token_hash determines whether to include the token hash in the SRR and
// private metadata encryption.
int use_token_hash : 1;
// batched_proof determines whether PMBToken uses a batched DLEQOR proof when
// signing tokens.
int batched_proof : 1;
};
// Structure representing a single Trust Token public key with the specified ID.
@@ -52,9 +52,6 @@ typedef struct {
// hash_c implements the H_c operation in PMBTokens. It returns one on success
// and zero on error.
hash_c_func_t hash_c;
// batched_proof determines whether PMBToken uses a batched DLEQOR proof when
// signing tokens.
int batched_proof : 1;
} PMBTOKEN_METHOD;
static const uint8_t kDefaultAdditionalData[32] = {0};
@@ -62,7 +59,7 @@ static const uint8_t kDefaultAdditionalData[32] = {0};
static int pmbtoken_init_method(PMBTOKEN_METHOD *method, int curve_nid,
const uint8_t *h_bytes, size_t h_len,
hash_t_func_t hash_t, hash_s_func_t hash_s,
hash_c_func_t hash_c, int batched_proof) {
hash_c_func_t hash_c) {
method->group = EC_GROUP_new_by_curve_name(curve_nid);
if (method->group == NULL) {
return 0;
@@ -71,7 +68,6 @@ static int pmbtoken_init_method(PMBTOKEN_METHOD *method, int curve_nid,
method->hash_t = hash_t;
method->hash_s = hash_s;
method->hash_c = hash_c;
method->batched_proof = batched_proof;
EC_AFFINE h;
if (!ec_point_from_uncompressed(method->group, &h, h_bytes, h_len)) {
@@ -724,37 +720,31 @@ static int pmbtoken_sign(const PMBTOKEN_METHOD *method,
return 0;
}
if (num_to_issue > ((size_t)-1) / sizeof(EC_RAW_POINT) ||
num_to_issue > ((size_t)-1) / sizeof(EC_SCALAR)) {
OPENSSL_PUT_ERROR(TRUST_TOKEN, ERR_R_OVERFLOW);
return 0;
}
int ret = 0;
EC_RAW_POINT *Tps = NULL;
EC_RAW_POINT *Sps = NULL;
EC_RAW_POINT *Wps = NULL;
EC_RAW_POINT *Wsps = NULL;
EC_SCALAR *es = NULL;
EC_RAW_POINT *Tps = OPENSSL_malloc(num_to_issue * sizeof(EC_RAW_POINT));
EC_RAW_POINT *Sps = OPENSSL_malloc(num_to_issue * sizeof(EC_RAW_POINT));
EC_RAW_POINT *Wps = OPENSSL_malloc(num_to_issue * sizeof(EC_RAW_POINT));
EC_RAW_POINT *Wsps = OPENSSL_malloc(num_to_issue * sizeof(EC_RAW_POINT));
EC_SCALAR *es = OPENSSL_malloc(num_to_issue * sizeof(EC_SCALAR));
CBB batch_cbb;
CBB_zero(&batch_cbb);
if (method->batched_proof) {
if (num_to_issue > ((size_t)-1) / sizeof(EC_RAW_POINT) ||
num_to_issue > ((size_t)-1) / sizeof(EC_SCALAR)) {
OPENSSL_PUT_ERROR(TRUST_TOKEN, ERR_R_OVERFLOW);
goto err;
}
Tps = OPENSSL_malloc(num_to_issue * sizeof(EC_RAW_POINT));
Sps = OPENSSL_malloc(num_to_issue * sizeof(EC_RAW_POINT));
Wps = OPENSSL_malloc(num_to_issue * sizeof(EC_RAW_POINT));
Wsps = OPENSSL_malloc(num_to_issue * sizeof(EC_RAW_POINT));
es = OPENSSL_malloc(num_to_issue * sizeof(EC_SCALAR));
if (!Tps ||
!Sps ||
!Wps ||
!Wsps ||
!es ||
!CBB_init(&batch_cbb, 0) ||
!point_to_cbb(&batch_cbb, method->group, &key->pubs) ||
!point_to_cbb(&batch_cbb, method->group, &key->pub0) ||
!point_to_cbb(&batch_cbb, method->group, &key->pub1)) {
OPENSSL_PUT_ERROR(TRUST_TOKEN, ERR_R_MALLOC_FAILURE);
goto err;
}
if (!Tps ||
!Sps ||
!Wps ||
!Wsps ||
!es ||
!CBB_init(&batch_cbb, 0) ||
!point_to_cbb(&batch_cbb, method->group, &key->pubs) ||
!point_to_cbb(&batch_cbb, method->group, &key->pub0) ||
!point_to_cbb(&batch_cbb, method->group, &key->pub1)) {
OPENSSL_PUT_ERROR(TRUST_TOKEN, ERR_R_MALLOC_FAILURE);
goto err;
}
for (size_t i = 0; i < num_to_issue; i++) {
@@ -793,25 +783,17 @@ static int pmbtoken_sign(const PMBTOKEN_METHOD *method,
goto err;
}
if (!method->batched_proof) {
if (!CBB_add_u16_length_prefixed(cbb, &child) ||
!dleq_generate(method, &child, key, &Tp, &jacobians[0], &jacobians[1],
&jacobians[2], private_metadata)) {
goto err;
}
} else {
if (!point_to_cbb(&batch_cbb, group, &Tp_affine) ||
!point_to_cbb(&batch_cbb, group, &affines[0]) ||
!point_to_cbb(&batch_cbb, group, &affines[1]) ||
!point_to_cbb(&batch_cbb, group, &affines[2])) {
OPENSSL_PUT_ERROR(TRUST_TOKEN, ERR_R_MALLOC_FAILURE);
goto err;
}
Tps[i] = Tp;
Sps[i] = jacobians[0];
Wps[i] = jacobians[1];
Wsps[i] = jacobians[2];
if (!point_to_cbb(&batch_cbb, group, &Tp_affine) ||
!point_to_cbb(&batch_cbb, group, &affines[0]) ||
!point_to_cbb(&batch_cbb, group, &affines[1]) ||
!point_to_cbb(&batch_cbb, group, &affines[2])) {
OPENSSL_PUT_ERROR(TRUST_TOKEN, ERR_R_MALLOC_FAILURE);
goto err;
}
Tps[i] = Tp;
Sps[i] = jacobians[0];
Wps[i] = jacobians[1];
Wsps[i] = jacobians[2];
if (!CBB_flush(cbb)) {
goto err;
@@ -821,36 +803,34 @@ static int pmbtoken_sign(const PMBTOKEN_METHOD *method,
// The DLEQ batching construction is described in appendix B of
// https://eprint.iacr.org/2020/072/20200324:214215. Note the additional
// computations all act on public inputs.
if (method->batched_proof) {
for (size_t i = 0; i < num_to_issue; i++) {
if (!hash_c_batch(method, &es[i], &batch_cbb, i)) {
goto err;
}
}
EC_RAW_POINT Tp_batch, Sp_batch, Wp_batch, Wsp_batch;
if (!ec_point_mul_scalar_public_batch(group, &Tp_batch,
/*g_scalar=*/NULL, Tps, es,
num_to_issue) ||
!ec_point_mul_scalar_public_batch(group, &Sp_batch,
/*g_scalar=*/NULL, Sps, es,
num_to_issue) ||
!ec_point_mul_scalar_public_batch(group, &Wp_batch,
/*g_scalar=*/NULL, Wps, es,
num_to_issue) ||
!ec_point_mul_scalar_public_batch(group, &Wsp_batch,
/*g_scalar=*/NULL, Wsps, es,
num_to_issue)) {
for (size_t i = 0; i < num_to_issue; i++) {
if (!hash_c_batch(method, &es[i], &batch_cbb, i)) {
goto err;
}
}
CBB proof;
if (!CBB_add_u16_length_prefixed(cbb, &proof) ||
!dleq_generate(method, &proof, key, &Tp_batch, &Sp_batch, &Wp_batch,
&Wsp_batch, private_metadata) ||
!CBB_flush(cbb)) {
goto err;
}
EC_RAW_POINT Tp_batch, Sp_batch, Wp_batch, Wsp_batch;
if (!ec_point_mul_scalar_public_batch(group, &Tp_batch,
/*g_scalar=*/NULL, Tps, es,
num_to_issue) ||
!ec_point_mul_scalar_public_batch(group, &Sp_batch,
/*g_scalar=*/NULL, Sps, es,
num_to_issue) ||
!ec_point_mul_scalar_public_batch(group, &Wp_batch,
/*g_scalar=*/NULL, Wps, es,
num_to_issue) ||
!ec_point_mul_scalar_public_batch(group, &Wsp_batch,
/*g_scalar=*/NULL, Wsps, es,
num_to_issue)) {
goto err;
}
CBB proof;
if (!CBB_add_u16_length_prefixed(cbb, &proof) ||
!dleq_generate(method, &proof, key, &Tp_batch, &Sp_batch, &Wp_batch,
&Wsp_batch, private_metadata) ||
!CBB_flush(cbb)) {
goto err;
}
// Skip over any unused requests.
@@ -890,36 +870,29 @@ static STACK_OF(TRUST_TOKEN) *
return NULL;
}
EC_RAW_POINT *Tps = NULL;
EC_RAW_POINT *Sps = NULL;
EC_RAW_POINT *Wps = NULL;
EC_RAW_POINT *Wsps = NULL;
EC_SCALAR *es = NULL;
if (count > ((size_t)-1) / sizeof(EC_RAW_POINT) ||
count > ((size_t)-1) / sizeof(EC_SCALAR)) {
OPENSSL_PUT_ERROR(TRUST_TOKEN, ERR_R_OVERFLOW);
return 0;
}
EC_RAW_POINT *Tps = OPENSSL_malloc(count * sizeof(EC_RAW_POINT));
EC_RAW_POINT *Sps = OPENSSL_malloc(count * sizeof(EC_RAW_POINT));
EC_RAW_POINT *Wps = OPENSSL_malloc(count * sizeof(EC_RAW_POINT));
EC_RAW_POINT *Wsps = OPENSSL_malloc(count * sizeof(EC_RAW_POINT));
EC_SCALAR *es = OPENSSL_malloc(count * sizeof(EC_SCALAR));
CBB batch_cbb;
CBB_zero(&batch_cbb);
if (method->batched_proof) {
if (count > ((size_t)-1) / sizeof(EC_RAW_POINT) ||
count > ((size_t)-1) / sizeof(EC_SCALAR)) {
OPENSSL_PUT_ERROR(TRUST_TOKEN, ERR_R_OVERFLOW);
goto err;
}
Tps = OPENSSL_malloc(count * sizeof(EC_RAW_POINT));
Sps = OPENSSL_malloc(count * sizeof(EC_RAW_POINT));
Wps = OPENSSL_malloc(count * sizeof(EC_RAW_POINT));
Wsps = OPENSSL_malloc(count * sizeof(EC_RAW_POINT));
es = OPENSSL_malloc(count * sizeof(EC_SCALAR));
if (!Tps ||
!Sps ||
!Wps ||
!Wsps ||
!es ||
!CBB_init(&batch_cbb, 0) ||
!point_to_cbb(&batch_cbb, method->group, &key->pubs) ||
!point_to_cbb(&batch_cbb, method->group, &key->pub0) ||
!point_to_cbb(&batch_cbb, method->group, &key->pub1)) {
OPENSSL_PUT_ERROR(TRUST_TOKEN, ERR_R_MALLOC_FAILURE);
goto err;
}
if (!Tps ||
!Sps ||
!Wps ||
!Wsps ||
!es ||
!CBB_init(&batch_cbb, 0) ||
!point_to_cbb(&batch_cbb, method->group, &key->pubs) ||
!point_to_cbb(&batch_cbb, method->group, &key->pub0) ||
!point_to_cbb(&batch_cbb, method->group, &key->pub1)) {
OPENSSL_PUT_ERROR(TRUST_TOKEN, ERR_R_MALLOC_FAILURE);
goto err;
}
for (size_t i = 0; i < count; i++) {
@@ -928,7 +901,6 @@ static STACK_OF(TRUST_TOKEN) *
uint8_t s[PMBTOKEN_NONCE_SIZE];
EC_AFFINE Wp_affine, Wsp_affine;
CBS proof;
if (!CBS_copy_bytes(cbs, s, PMBTOKEN_NONCE_SIZE) ||
!cbs_get_prefixed_point(cbs, group, &Wp_affine) ||
!cbs_get_prefixed_point(cbs, group, &Wsp_affine)) {
@@ -936,50 +908,29 @@ static STACK_OF(TRUST_TOKEN) *
goto err;
}
EC_RAW_POINT Tp, Wp, Wsp, Sp;
ec_affine_to_jacobian(group, &Tp, &pretoken->Tp);
ec_affine_to_jacobian(group, &Wp, &Wp_affine);
ec_affine_to_jacobian(group, &Wsp, &Wsp_affine);
if (!method->hash_s(group, &Sp, &pretoken->Tp, s)) {
ec_affine_to_jacobian(group, &Tps[i], &pretoken->Tp);
ec_affine_to_jacobian(group, &Wps[i], &Wp_affine);
ec_affine_to_jacobian(group, &Wsps[i], &Wsp_affine);
if (!method->hash_s(group, &Sps[i], &pretoken->Tp, s)) {
goto err;
}
if (!method->batched_proof) {
if(!CBS_get_u16_length_prefixed(cbs, &proof)) {
OPENSSL_PUT_ERROR(TRUST_TOKEN, TRUST_TOKEN_R_DECODE_FAILURE);
goto err;
}
if (!dleq_verify(method, &proof, key, &Tp, &Sp, &Wp, &Wsp)) {
goto err;
}
if (CBS_len(&proof) != 0) {
OPENSSL_PUT_ERROR(TRUST_TOKEN, TRUST_TOKEN_R_DECODE_FAILURE);
goto err;
}
} else {
EC_AFFINE Sp_affine;
if (!point_to_cbb(&batch_cbb, group, &pretoken->Tp) ||
!ec_jacobian_to_affine(group, &Sp_affine, &Sp) ||
!point_to_cbb(&batch_cbb, group, &Sp_affine) ||
!point_to_cbb(&batch_cbb, group, &Wp_affine) ||
!point_to_cbb(&batch_cbb, group, &Wsp_affine)) {
OPENSSL_PUT_ERROR(TRUST_TOKEN, ERR_R_MALLOC_FAILURE);
goto err;
}
Tps[i] = Tp;
Sps[i] = Sp;
Wps[i] = Wp;
Wsps[i] = Wsp;
EC_AFFINE Sp_affine;
if (!point_to_cbb(&batch_cbb, group, &pretoken->Tp) ||
!ec_jacobian_to_affine(group, &Sp_affine, &Sps[i]) ||
!point_to_cbb(&batch_cbb, group, &Sp_affine) ||
!point_to_cbb(&batch_cbb, group, &Wp_affine) ||
!point_to_cbb(&batch_cbb, group, &Wsp_affine)) {
OPENSSL_PUT_ERROR(TRUST_TOKEN, ERR_R_MALLOC_FAILURE);
goto err;
}
// Unblind the token.
EC_RAW_POINT jacobians[3];
EC_AFFINE affines[3];
if (!ec_point_mul_scalar(group, &jacobians[0], &Sp, &pretoken->r) ||
!ec_point_mul_scalar(group, &jacobians[1], &Wp, &pretoken->r) ||
!ec_point_mul_scalar(group, &jacobians[2], &Wsp, &pretoken->r) ||
if (!ec_point_mul_scalar(group, &jacobians[0], &Sps[i], &pretoken->r) ||
!ec_point_mul_scalar(group, &jacobians[1], &Wps[i], &pretoken->r) ||
!ec_point_mul_scalar(group, &jacobians[2], &Wsps[i], &pretoken->r) ||
!ec_jacobian_to_affine_batch(group, affines, jacobians, 3)) {
goto err;
}
@@ -1018,32 +969,30 @@ static STACK_OF(TRUST_TOKEN) *
// The DLEQ batching construction is described in appendix B of
// https://eprint.iacr.org/2020/072/20200324:214215. Note the additional
// computations all act on public inputs.
if (method->batched_proof) {
for (size_t i = 0; i < count; i++) {
if (!hash_c_batch(method, &es[i], &batch_cbb, i)) {
goto err;
}
}
EC_RAW_POINT Tp_batch, Sp_batch, Wp_batch, Wsp_batch;
if (!ec_point_mul_scalar_public_batch(group, &Tp_batch,
/*g_scalar=*/NULL, Tps, es, count) ||
!ec_point_mul_scalar_public_batch(group, &Sp_batch,
/*g_scalar=*/NULL, Sps, es, count) ||
!ec_point_mul_scalar_public_batch(group, &Wp_batch,
/*g_scalar=*/NULL, Wps, es, count) ||
!ec_point_mul_scalar_public_batch(group, &Wsp_batch,
/*g_scalar=*/NULL, Wsps, es, count)) {
for (size_t i = 0; i < count; i++) {
if (!hash_c_batch(method, &es[i], &batch_cbb, i)) {
goto err;
}
}
CBS proof;
if (!CBS_get_u16_length_prefixed(cbs, &proof) ||
!dleq_verify(method, &proof, key, &Tp_batch, &Sp_batch, &Wp_batch,
&Wsp_batch) ||
CBS_len(&proof) != 0) {
goto err;
}
EC_RAW_POINT Tp_batch, Sp_batch, Wp_batch, Wsp_batch;
if (!ec_point_mul_scalar_public_batch(group, &Tp_batch,
/*g_scalar=*/NULL, Tps, es, count) ||
!ec_point_mul_scalar_public_batch(group, &Sp_batch,
/*g_scalar=*/NULL, Sps, es, count) ||
!ec_point_mul_scalar_public_batch(group, &Wp_batch,
/*g_scalar=*/NULL, Wps, es, count) ||
!ec_point_mul_scalar_public_batch(group, &Wsp_batch,
/*g_scalar=*/NULL, Wsps, es, count)) {
goto err;
}
CBS proof;
if (!CBS_get_u16_length_prefixed(cbs, &proof) ||
!dleq_verify(method, &proof, key, &Tp_batch, &Sp_batch, &Wp_batch,
&Wsp_batch) ||
CBS_len(&proof) != 0) {
goto err;
}
ok = 1;
@@ -1127,202 +1076,6 @@ static int pmbtoken_read(const PMBTOKEN_METHOD *method,
}
// PMBTokens experiment v0.
static int pmbtoken_exp0_hash_t(const EC_GROUP *group, EC_RAW_POINT *out,
const uint8_t t[PMBTOKEN_NONCE_SIZE]) {
const uint8_t kHashTLabel[] = "PMBTokensV0 HashT";
return ec_hash_to_curve_p521_xmd_sha512_sswu_draft06(
group, out, kHashTLabel, sizeof(kHashTLabel), t, PMBTOKEN_NONCE_SIZE);
}
static int pmbtoken_exp0_hash_s(const EC_GROUP *group, EC_RAW_POINT *out,
const EC_AFFINE *t,
const uint8_t s[PMBTOKEN_NONCE_SIZE]) {
const uint8_t kHashSLabel[] = "PMBTokensV0 HashS";
int ret = 0;
CBB cbb;
uint8_t *buf = NULL;
size_t len;
if (!CBB_init(&cbb, 0) ||
!point_to_cbb(&cbb, group, t) ||
!CBB_add_bytes(&cbb, s, PMBTOKEN_NONCE_SIZE) ||
!CBB_finish(&cbb, &buf, &len) ||
!ec_hash_to_curve_p521_xmd_sha512_sswu_draft06(
group, out, kHashSLabel, sizeof(kHashSLabel), buf, len)) {
OPENSSL_PUT_ERROR(TRUST_TOKEN, ERR_R_MALLOC_FAILURE);
goto err;
}
ret = 1;
err:
OPENSSL_free(buf);
CBB_cleanup(&cbb);
return ret;
}
static int pmbtoken_exp0_hash_c(const EC_GROUP *group, EC_SCALAR *out,
uint8_t *buf, size_t len) {
const uint8_t kHashCLabel[] = "PMBTokensV0 HashC";
return ec_hash_to_scalar_p521_xmd_sha512_draft06(
group, out, kHashCLabel, sizeof(kHashCLabel), buf, len);
}
// H for PMBTokens v0 was generated with the following Python code.
/*
import hashlib
SEED_H = 'PrivacyPass H'
A = -3
B = 0x051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00
P = 2**521 - 1
def get_y(x):
y2 = (x**3 + A*x + B) % P
y = pow(y2, (P+1)/4, P)
if (y*y) % P != y2:
raise ValueError("point not on curve")
return y
def bit(h,i):
return (ord(h[i/8]) >> (i%8)) & 1
b = 521
def decode_point(so):
s = hashlib.sha256(so + '0').digest() + hashlib.sha256(so + '1').digest() + \
hashlib.sha256(so + '2').digest()
x = 0
for i in range(0,b):
x = x + (long(bit(s,i))<<i)
if x >= P:
raise ValueError("x out of range")
y = get_y(x)
if y & 1 != bit(s,b-1): y = P-y
return (x, y)
def gen_point(seed):
v = hashlib.sha256(seed).digest()
it = 1
while True:
try:
x,y = decode_point(v)
except Exception, e:
print e
it += 1
v = hashlib.sha256(v).digest()
continue
print "Found in %d iterations:" % it
print " x = %d" % x
print " y = %d" % y
print " Encoded (hex): (%x, %x)" % (x, y)
return (x, y)
if __name__ == "__main__":
gen_point(SEED_H)
*/
static int pmbtoken_exp0_ok = 0;
static PMBTOKEN_METHOD pmbtoken_exp0_method;
static CRYPTO_once_t pmbtoken_exp0_method_once = CRYPTO_ONCE_INIT;
static void pmbtoken_exp0_init_method_impl(void) {
static const uint8_t kH[] = {
0x04, 0x01, 0xf0, 0xa9, 0xf7, 0x9e, 0xbc, 0x12, 0x6c, 0xef, 0xd1, 0xab,
0x29, 0x10, 0x03, 0x6f, 0x4e, 0xf5, 0xbd, 0xeb, 0x0f, 0x6b, 0xc0, 0x5c,
0x0e, 0xce, 0xfe, 0x59, 0x45, 0xd1, 0x3e, 0x25, 0x33, 0x7e, 0x4c, 0xda,
0x64, 0x53, 0x54, 0x4e, 0xf9, 0x76, 0x0d, 0x6d, 0xc5, 0x39, 0x2a, 0xd4,
0xce, 0x84, 0x6e, 0x31, 0xc2, 0x86, 0x21, 0xf9, 0x5c, 0x98, 0xb9, 0x3d,
0x01, 0x74, 0x9f, 0xc5, 0x1e, 0x47, 0x24, 0x00, 0x5c, 0x17, 0x62, 0x51,
0x7d, 0x32, 0x5e, 0x29, 0xac, 0x52, 0x14, 0x75, 0x6f, 0x36, 0xd9, 0xc7,
0xfa, 0xbb, 0xa9, 0x3b, 0x9d, 0x70, 0x49, 0x1e, 0xb4, 0x53, 0xbc, 0x55,
0xea, 0xad, 0x8f, 0x26, 0x1d, 0xe0, 0xbc, 0xf3, 0x50, 0x5c, 0x7e, 0x66,
0x41, 0xb5, 0x61, 0x70, 0x12, 0x72, 0xac, 0x6a, 0xb0, 0x6e, 0x78, 0x3d,
0x17, 0x08, 0xe3, 0xdf, 0x3c, 0xff, 0xa6, 0xa0, 0xea, 0x96, 0x67, 0x92,
0xcd,
};
pmbtoken_exp0_ok =
pmbtoken_init_method(&pmbtoken_exp0_method, NID_secp521r1, kH, sizeof(kH),
pmbtoken_exp0_hash_t, pmbtoken_exp0_hash_s,
pmbtoken_exp0_hash_c, /*batched_proof=*/0);
}
static int pmbtoken_exp0_init_method(void) {
CRYPTO_once(&pmbtoken_exp0_method_once, pmbtoken_exp0_init_method_impl);
if (!pmbtoken_exp0_ok) {
OPENSSL_PUT_ERROR(TRUST_TOKEN, ERR_R_INTERNAL_ERROR);
return 0;
}
return 1;
}
int pmbtoken_exp0_generate_key(CBB *out_private, CBB *out_public) {
if (!pmbtoken_exp0_init_method()) {
return 0;
}
return pmbtoken_generate_key(&pmbtoken_exp0_method, out_private, out_public);
}
int pmbtoken_exp0_client_key_from_bytes(PMBTOKEN_CLIENT_KEY *key,
const uint8_t *in, size_t len) {
if (!pmbtoken_exp0_init_method()) {
return 0;
}
return pmbtoken_client_key_from_bytes(&pmbtoken_exp0_method, key, in, len);
}
int pmbtoken_exp0_issuer_key_from_bytes(PMBTOKEN_ISSUER_KEY *key,
const uint8_t *in, size_t len) {
if (!pmbtoken_exp0_init_method()) {
return 0;
}
return pmbtoken_issuer_key_from_bytes(&pmbtoken_exp0_method, key, in, len);
}
STACK_OF(PMBTOKEN_PRETOKEN) * pmbtoken_exp0_blind(CBB *cbb, size_t count) {
if (!pmbtoken_exp0_init_method()) {
return NULL;
}
return pmbtoken_blind(&pmbtoken_exp0_method, cbb, count);
}
int pmbtoken_exp0_sign(const PMBTOKEN_ISSUER_KEY *key, CBB *cbb, CBS *cbs,
size_t num_requested, size_t num_to_issue,
uint8_t private_metadata) {
if (!pmbtoken_exp0_init_method()) {
return 0;
}
return pmbtoken_sign(&pmbtoken_exp0_method, key, cbb, cbs, num_requested,
num_to_issue, private_metadata);
}
STACK_OF(TRUST_TOKEN) *
pmbtoken_exp0_unblind(const PMBTOKEN_CLIENT_KEY *key,
const STACK_OF(PMBTOKEN_PRETOKEN) * pretokens,
CBS *cbs, size_t count, uint32_t key_id) {
if (!pmbtoken_exp0_init_method()) {
return NULL;
}
return pmbtoken_unblind(&pmbtoken_exp0_method, key, pretokens, cbs, count,
key_id);
}
int pmbtoken_exp0_read(const PMBTOKEN_ISSUER_KEY *key,
uint8_t out_nonce[PMBTOKEN_NONCE_SIZE],
uint8_t *out_private_metadata, const uint8_t *token,
size_t token_len) {
if (!pmbtoken_exp0_init_method()) {
return 0;
}
return pmbtoken_read(&pmbtoken_exp0_method, key, out_nonce,
out_private_metadata, token, token_len);
}
// PMBTokens experiment v1.
static int pmbtoken_exp1_hash_t(const EC_GROUP *group, EC_RAW_POINT *out,
@@ -1387,7 +1140,7 @@ static void pmbtoken_exp1_init_method_impl(void) {
pmbtoken_exp1_ok =
pmbtoken_init_method(&pmbtoken_exp1_method, NID_secp384r1, kH, sizeof(kH),
pmbtoken_exp1_hash_t, pmbtoken_exp1_hash_s,
pmbtoken_exp1_hash_c, /*batched_proof=*/1);
pmbtoken_exp1_hash_c);
}
static int pmbtoken_exp1_init_method(void) {
@@ -27,21 +27,6 @@
// protocol for issuing and redeeming tokens built on top of the PMBTokens
// construction.
const TRUST_TOKEN_METHOD *TRUST_TOKEN_experiment_v0(void) {
static const TRUST_TOKEN_METHOD kMethod = {
pmbtoken_exp0_generate_key,
pmbtoken_exp0_client_key_from_bytes,
pmbtoken_exp0_issuer_key_from_bytes,
pmbtoken_exp0_blind,
pmbtoken_exp0_sign,
pmbtoken_exp0_unblind,
pmbtoken_exp0_read,
0 /* don't use token hash */,
0 /* don't use batched proof */,
};
return &kMethod;
}
const TRUST_TOKEN_METHOD *TRUST_TOKEN_experiment_v1(void) {
static const TRUST_TOKEN_METHOD kMethod = {
pmbtoken_exp1_generate_key,
@@ -51,8 +36,6 @@ const TRUST_TOKEN_METHOD *TRUST_TOKEN_experiment_v1(void) {
pmbtoken_exp1_sign,
pmbtoken_exp1_unblind,
pmbtoken_exp1_read,
1 /* use token hash */,
1 /* use batched proof */,
};
return &kMethod;
}
@@ -597,16 +580,8 @@ int TRUST_TOKEN_ISSUER_redeem(const TRUST_TOKEN_ISSUER *ctx, uint8_t **out,
SHA256_Update(&sha_ctx, CBS_data(&token_copy), CBS_len(&token_copy));
SHA256_Final(token_hash, &sha_ctx);
uint8_t metadata_obfuscator;
if (ctx->method->use_token_hash) {
metadata_obfuscator =
get_metadata_obfuscator(ctx->metadata_key, ctx->metadata_key_len,
token_hash, sizeof(token_hash));
} else {
metadata_obfuscator =
get_metadata_obfuscator(ctx->metadata_key, ctx->metadata_key_len,
CBS_data(&client_data), CBS_len(&client_data));
}
uint8_t metadata_obfuscator = get_metadata_obfuscator(
ctx->metadata_key, ctx->metadata_key_len, token_hash, sizeof(token_hash));
// The SRR is constructed as per the format described in
// https://docs.google.com/document/d/1TNnya6B8pyomDK2F1R9CL3dY10OAmqWlnCxsWyOBDVQ/edit#heading=h.7mkzvhpqb8l5
@@ -625,10 +600,7 @@ int TRUST_TOKEN_ISSUER_redeem(const TRUST_TOKEN_ISSUER *ctx, uint8_t **out,
assert(strlen(kClientDataLabel) < strlen(kExpiryTimestampLabel));
assert(strlen(kPublicLabel) < strlen(kPrivateLabel));
size_t map_entries = 3;
if (ctx->method->use_token_hash) {
map_entries = 4;
}
size_t map_entries = 4;
if (!CBB_init(&srr, 0) ||
!add_cbor_map(&srr, map_entries) || // SRR map
@@ -637,20 +609,10 @@ int TRUST_TOKEN_ISSUER_redeem(const TRUST_TOKEN_ISSUER *ctx, uint8_t **out,
!add_cbor_text(&srr, kPublicLabel, strlen(kPublicLabel)) ||
!add_cbor_int(&srr, public_metadata) ||
!add_cbor_text(&srr, kPrivateLabel, strlen(kPrivateLabel)) ||
!add_cbor_int(&srr, private_metadata ^ metadata_obfuscator)) {
OPENSSL_PUT_ERROR(TRUST_TOKEN, ERR_R_MALLOC_FAILURE);
goto err;
}
if (ctx->method->use_token_hash) {
if (!add_cbor_text(&srr, kTokenHashLabel, strlen(kTokenHashLabel)) ||
!add_cbor_bytes(&srr, token_hash, sizeof(token_hash))) {
OPENSSL_PUT_ERROR(TRUST_TOKEN, ERR_R_MALLOC_FAILURE);
goto err;
}
}
if (!add_cbor_text(&srr, kClientDataLabel, strlen(kClientDataLabel)) ||
!add_cbor_int(&srr, private_metadata ^ metadata_obfuscator) ||
!add_cbor_text(&srr, kTokenHashLabel, strlen(kTokenHashLabel)) ||
!add_cbor_bytes(&srr, token_hash, sizeof(token_hash)) ||
!add_cbor_text(&srr, kClientDataLabel, strlen(kClientDataLabel)) ||
!CBB_add_bytes(&srr, CBS_data(&client_data), CBS_len(&client_data)) ||
!add_cbor_text(&srr, kExpiryTimestampLabel,
strlen(kExpiryTimestampLabel)) ||
@@ -296,7 +296,7 @@ static int do_hex_dump(char_io *io_ch, void *arg, unsigned char *buf,
*/
static int do_dump(unsigned long lflags, char_io *io_ch, void *arg,
ASN1_STRING *str)
const ASN1_STRING *str)
{
/*
* Placing the ASN1_STRING in a temp ASN1_TYPE allows the DER encoding to
@@ -354,7 +354,7 @@ static const signed char tag2nbyte[] = {
*/
static int do_print_ex(char_io *io_ch, void *arg, unsigned long lflags,
ASN1_STRING *str)
const ASN1_STRING *str)
{
int outlen, len;
int type;
@@ -610,13 +610,13 @@ int X509_NAME_print_ex_fp(FILE *fp, X509_NAME *nm, int indent,
}
#endif
int ASN1_STRING_print_ex(BIO *out, ASN1_STRING *str, unsigned long flags)
int ASN1_STRING_print_ex(BIO *out, const ASN1_STRING *str, unsigned long flags)
{
return do_print_ex(send_bio_chars, out, flags, str);
}
#ifndef OPENSSL_NO_FP_API
int ASN1_STRING_print_ex_fp(FILE *fp, ASN1_STRING *str, unsigned long flags)
int ASN1_STRING_print_ex_fp(FILE *fp, const ASN1_STRING *str, unsigned long flags)
{
return do_print_ex(send_fp_chars, fp, flags, str);
}
@@ -142,6 +142,14 @@ int x509_digest_verify_init(EVP_MD_CTX *ctx, X509_ALGOR *sigalg,
return 0;
}
/* RSA signature algorithms include an explicit NULL parameter but we also
* accept omitted values for compatibility. Other algorithms must omit it. */
if (sigalg->parameter != NULL && (pkey_nid != EVP_PKEY_RSA ||
sigalg->parameter->type != V_ASN1_NULL)) {
OPENSSL_PUT_ERROR(X509, X509_R_INVALID_PARAMETER);
return 0;
}
/* Otherwise, initialize with the digest from the OID. */
const EVP_MD *digest = EVP_get_digestbynid(digest_nid);
if (digest == NULL) {
@@ -123,7 +123,7 @@ typedef struct {
int exp_count;
} tag_exp_arg;
static ASN1_TYPE *generate_v3(char *str, X509V3_CTX *cnf, int depth,
static ASN1_TYPE *generate_v3(const char *str, X509V3_CTX *cnf, int depth,
int *perr);
static int bitstr_cb(const char *elem, int len, void *bitstr);
static int asn1_cb(const char *elem, int len, void *bitstr);
@@ -136,7 +136,7 @@ static ASN1_TYPE *asn1_multi(int utype, const char *section, X509V3_CTX *cnf,
static ASN1_TYPE *asn1_str2type(const char *str, int format, int utype);
static int asn1_str2tag(const char *tagstr, int len);
ASN1_TYPE *ASN1_generate_nconf(char *str, CONF *nconf)
ASN1_TYPE *ASN1_generate_nconf(const char *str, CONF *nconf)
{
X509V3_CTX cnf;
@@ -147,7 +147,7 @@ ASN1_TYPE *ASN1_generate_nconf(char *str, CONF *nconf)
return ASN1_generate_v3(str, &cnf);
}
ASN1_TYPE *ASN1_generate_v3(char *str, X509V3_CTX *cnf)
ASN1_TYPE *ASN1_generate_v3(const char *str, X509V3_CTX *cnf)
{
int err = 0;
ASN1_TYPE *ret = generate_v3(str, cnf, 0, &err);
@@ -156,7 +156,7 @@ ASN1_TYPE *ASN1_generate_v3(char *str, X509V3_CTX *cnf)
return ret;
}
static ASN1_TYPE *generate_v3(char *str, X509V3_CTX *cnf, int depth,
static ASN1_TYPE *generate_v3(const char *str, X509V3_CTX *cnf, int depth,
int *perr)
{
ASN1_TYPE *ret;
@@ -65,73 +65,6 @@
* it to avoid downstream churn. */
OPENSSL_DECLARE_ERROR_REASON(X509, UNSUPPORTED_ALGORITHM)
int PKCS8_pkey_set0(PKCS8_PRIV_KEY_INFO *priv, ASN1_OBJECT *aobj, int version,
int ptype, void *pval, uint8_t *penc, int penclen) {
uint8_t **ppenc = NULL;
if (version >= 0) {
if (!ASN1_INTEGER_set(priv->version, version)) {
return 0;
}
}
if (penc) {
int pmtype;
ASN1_OCTET_STRING *oct;
oct = ASN1_OCTET_STRING_new();
if (!oct) {
return 0;
}
oct->data = penc;
ppenc = &oct->data;
oct->length = penclen;
if (priv->broken == PKCS8_NO_OCTET) {
pmtype = V_ASN1_SEQUENCE;
} else {
pmtype = V_ASN1_OCTET_STRING;
}
ASN1_TYPE_set(priv->pkey, pmtype, oct);
}
if (!X509_ALGOR_set0(priv->pkeyalg, aobj, ptype, pval)) {
/* If call fails do not swallow 'enc' */
if (ppenc) {
*ppenc = NULL;
}
return 0;
}
return 1;
}
int PKCS8_pkey_get0(ASN1_OBJECT **ppkalg, const uint8_t **pk, int *ppklen,
X509_ALGOR **pa, PKCS8_PRIV_KEY_INFO *p8) {
if (ppkalg) {
*ppkalg = p8->pkeyalg->algorithm;
}
if (p8->pkey->type == V_ASN1_OCTET_STRING) {
p8->broken = PKCS8_OK;
if (pk) {
*pk = p8->pkey->value.octet_string->data;
*ppklen = p8->pkey->value.octet_string->length;
}
} else if (p8->pkey->type == V_ASN1_SEQUENCE) {
p8->broken = PKCS8_NO_OCTET;
if (pk) {
*pk = p8->pkey->value.sequence->data;
*ppklen = p8->pkey->value.sequence->length;
}
} else {
return 0;
}
if (pa) {
*pa = p8->pkeyalg;
}
return 1;
}
int X509_signature_dump(BIO *bp, const ASN1_STRING *sig, int indent) {
const uint8_t *s;
int i, n;
@@ -67,6 +67,7 @@
#include <CCryptoBoringSSL_x509v3.h>
#include "../internal.h"
#include "../x509v3/internal.h"
int X509_issuer_and_serial_cmp(const X509 *a, const X509 *b)
@@ -175,12 +176,18 @@ unsigned long X509_subject_name_hash_old(X509 *x)
*/
int X509_cmp(const X509 *a, const X509 *b)
{
int rv;
/* ensure hash is valid */
X509_check_purpose((X509 *)a, -1, 0);
X509_check_purpose((X509 *)b, -1, 0);
/* Fill in the |sha1_hash| fields.
*
* TODO(davidben): This may fail, in which case the the hash will be all
* zeros. This produces a consistent comparison (failures are sticky), but
* not a good one. OpenSSL now returns -2, but this is not a consistent
* comparison and may cause misbehaving sorts by transitivity. For now, we
* retain the old OpenSSL behavior, which was to ignore the error. See
* https://crbug.com/boringssl/355. */
x509v3_cache_extensions((X509 *)a);
x509v3_cache_extensions((X509 *)b);
rv = OPENSSL_memcmp(a->sha1_hash, b->sha1_hash, SHA_DIGEST_LENGTH);
int rv = OPENSSL_memcmp(a->sha1_hash, b->sha1_hash, SHA_DIGEST_LENGTH);
if (rv)
return rv;
/* Check for match against stored encoding too */
@@ -107,6 +107,16 @@ X509_REQ *X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey, const EVP_MD *md)
return (NULL);
}
long X509_REQ_get_version(const X509_REQ *req)
{
return ASN1_INTEGER_get(req->req_info->version);
}
X509_NAME *X509_REQ_get_subject_name(const X509_REQ *req)
{
return req->req_info->subject;
}
EVP_PKEY *X509_REQ_get_pubkey(X509_REQ *req)
{
if ((req == NULL) || (req->req_info == NULL))
@@ -60,6 +60,16 @@
#include <CCryptoBoringSSL_obj.h>
#include <CCryptoBoringSSL_x509.h>
long X509_get_version(const X509 *x509)
{
return ASN1_INTEGER_get(x509->cert_info->version);
}
X509_CINF *X509_get_cert_info(const X509 *x509)
{
return x509->cert_info;
}
int X509_set_version(X509 *x, long version)
{
if (x == NULL)
@@ -137,6 +147,14 @@ ASN1_TIME *X509_getm_notBefore(X509 *x)
return x->cert_info->validity->notBefore;
}
ASN1_TIME *X509_get_notBefore(const X509 *x509)
{
// In OpenSSL, this function is an alias for |X509_getm_notBefore|, but our
// |X509_getm_notBefore| is const-correct. |X509_get_notBefore| was
// originally a macro, so it needs to capture both get0 and getm use cases.
return x509->cert_info->validity->notBefore;
}
int X509_set_notAfter(X509 *x, const ASN1_TIME *tm)
{
ASN1_TIME *in;
@@ -167,6 +185,14 @@ ASN1_TIME *X509_getm_notAfter(X509 *x)
return x->cert_info->validity->notAfter;
}
ASN1_TIME *X509_get_notAfter(const X509 *x509)
{
// In OpenSSL, this function is an alias for |X509_getm_notAfter|, but our
// |X509_getm_notAfter| is const-correct. |X509_get_notAfter| was
// originally a macro, so it needs to capture both get0 and getm use cases.
return x509->cert_info->validity->notAfter;
}
int X509_set_pubkey(X509 *x, EVP_PKEY *pkey)
{
if ((x == NULL) || (x->cert_info == NULL))
@@ -183,3 +209,18 @@ const X509_ALGOR *X509_get0_tbs_sigalg(const X509 *x)
{
return x->cert_info->signature;
}
void X509_CINF_set_modified(X509_CINF *cinf)
{
cinf->enc.modified = 1;
}
const X509_ALGOR *X509_CINF_get_signature(const X509_CINF *cinf)
{
return cinf->signature;
}
X509_PUBKEY *X509_get_X509_PUBKEY(const X509 *x509)
{
return x509->cert_info->key;
}
@@ -59,6 +59,8 @@
#include <CCryptoBoringSSL_obj.h>
#include <CCryptoBoringSSL_x509v3.h>
#include "../x509v3/internal.h"
static int tr_cmp(const X509_TRUST **a, const X509_TRUST **b);
static void trtable_free(X509_TRUST *p);
@@ -293,7 +295,8 @@ static int trust_1oid(X509_TRUST *trust, X509 *x, int flags)
static int trust_compat(X509_TRUST *trust, X509 *x, int flags)
{
X509_check_purpose(x, -1, 0);
if (!x509v3_cache_extensions(x))
return X509_TRUST_UNTRUSTED;
if (x->ex_flags & EXFLAG_SS)
return X509_TRUST_TRUSTED;
else
@@ -146,14 +146,16 @@ static int null_callback(int ok, X509_STORE_CTX *e)
return ok;
}
/* Return 1 is a certificate is self signed */
static int cert_self_signed(X509 *x)
/* cert_self_signed checks if |x| is self-signed. If |x| is valid, it returns
* one and sets |*out_is_self_signed| to the result. If |x| is invalid, it
* returns zero. */
static int cert_self_signed(X509 *x, int *out_is_self_signed)
{
X509_check_purpose(x, -1, 0);
if (x->ex_flags & EXFLAG_SS)
return 1;
else
if (!x509v3_cache_extensions(x)) {
return 0;
}
*out_is_self_signed = (x->ex_flags & EXFLAG_SS) != 0;
return 1;
}
/* Given a certificate try and find an exact match in the store */
@@ -263,8 +265,14 @@ int X509_verify_cert(X509_STORE_CTX *ctx)
* X509_V_ERR_CERT_CHAIN_TOO_LONG error code
* later. */
int is_self_signed;
if (!cert_self_signed(x, &is_self_signed)) {
ctx->error = X509_V_ERR_INVALID_EXTENSION;
goto end;
}
/* If we are self signed, we break */
if (cert_self_signed(x))
if (is_self_signed)
break;
/*
* If asked see if we can find issuer in trusted store first
@@ -323,7 +331,14 @@ int X509_verify_cert(X509_STORE_CTX *ctx)
*/
i = sk_X509_num(ctx->chain);
x = sk_X509_value(ctx->chain, i - 1);
if (cert_self_signed(x)) {
int is_self_signed;
if (!cert_self_signed(x, &is_self_signed)) {
ctx->error = X509_V_ERR_INVALID_EXTENSION;
goto end;
}
if (is_self_signed) {
/* we have a self signed certificate */
if (sk_X509_num(ctx->chain) == 1) {
/*
@@ -368,8 +383,12 @@ int X509_verify_cert(X509_STORE_CTX *ctx)
/* If we have enough, we break */
if (depth < num)
break;
if (!cert_self_signed(x, &is_self_signed)) {
ctx->error = X509_V_ERR_INVALID_EXTENSION;
goto end;
}
/* If we are self signed, we break */
if (cert_self_signed(x))
if (is_self_signed)
break;
ok = ctx->get_issuer(&xtmp, ctx, x);
@@ -135,6 +135,11 @@ int X509_CRL_up_ref(X509_CRL *crl)
return 1;
}
long X509_CRL_get_version(const X509_CRL *crl)
{
return ASN1_INTEGER_get(crl->crl->version);
}
const ASN1_TIME *X509_CRL_get0_lastUpdate(const X509_CRL *crl)
{
return crl->crl->lastUpdate;
@@ -145,6 +150,26 @@ const ASN1_TIME *X509_CRL_get0_nextUpdate(const X509_CRL *crl)
return crl->crl->nextUpdate;
}
ASN1_TIME *X509_CRL_get_lastUpdate(X509_CRL *crl)
{
return crl->crl->lastUpdate;
}
ASN1_TIME *X509_CRL_get_nextUpdate(X509_CRL *crl)
{
return crl->crl->nextUpdate;
}
X509_NAME *X509_CRL_get_issuer(const X509_CRL *crl)
{
return crl->crl->issuer;
}
STACK_OF(X509_REVOKED) *X509_CRL_get_REVOKED(X509_CRL *crl)
{
return crl->crl->revoked;
}
void X509_CRL_get0_signature(const X509_CRL *crl, const ASN1_BIT_STRING **psig,
const X509_ALGOR **palg)
{
+35 -13
View File
@@ -86,7 +86,7 @@ struct x509_crl_method_st {
};
static int X509_REVOKED_cmp(const X509_REVOKED **a, const X509_REVOKED **b);
static void setup_idp(X509_CRL *crl, ISSUING_DIST_POINT *idp);
static int setup_idp(X509_CRL *crl, ISSUING_DIST_POINT *idp);
ASN1_SEQUENCE(X509_REVOKED) = {
ASN1_SIMPLE(X509_REVOKED,serialNumber, ASN1_INTEGER),
@@ -126,6 +126,9 @@ static int crl_inf_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
* affect the output of X509_CRL_print().
*/
case ASN1_OP_D2I_POST:
/* TODO(davidben): Check that default |versions| are never encoded and
* that |extensions| is only present in v2. */
(void)sk_X509_REVOKED_set_cmp_func(a->revoked, X509_REVOKED_cmp);
break;
}
@@ -226,6 +229,7 @@ static int crl_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
STACK_OF(X509_EXTENSION) *exts;
X509_EXTENSION *ext;
size_t idx;
int i;
switch (operation) {
case ASN1_OP_NEW_POST:
@@ -242,26 +246,44 @@ static int crl_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
break;
case ASN1_OP_D2I_POST:
X509_CRL_digest(crl, EVP_sha1(), crl->sha1_hash, NULL);
if (!X509_CRL_digest(crl, EVP_sha1(), crl->sha1_hash, NULL)) {
return 0;
}
crl->idp = X509_CRL_get_ext_d2i(crl,
NID_issuing_distribution_point, NULL,
NID_issuing_distribution_point, &i,
NULL);
if (crl->idp)
setup_idp(crl, crl->idp);
if (crl->idp != NULL) {
if (!setup_idp(crl, crl->idp)) {
return 0;
}
} else if (i != -1) {
return 0;
}
crl->akid = X509_CRL_get_ext_d2i(crl,
NID_authority_key_identifier, NULL,
NID_authority_key_identifier, &i,
NULL);
if (crl->akid == NULL && i != -1) {
return 0;
}
crl->crl_number = X509_CRL_get_ext_d2i(crl,
NID_crl_number, NULL, NULL);
NID_crl_number, &i, NULL);
if (crl->crl_number == NULL && i != -1) {
return 0;
}
crl->base_crl_number = X509_CRL_get_ext_d2i(crl,
NID_delta_crl, NULL,
crl->base_crl_number = X509_CRL_get_ext_d2i(crl, NID_delta_crl, &i,
NULL);
if (crl->base_crl_number == NULL && i != -1) {
return 0;
}
/* Delta CRLs must have CRL number */
if (crl->base_crl_number && !crl->crl_number)
crl->flags |= EXFLAG_INVALID;
if (crl->base_crl_number && !crl->crl_number) {
OPENSSL_PUT_ERROR(X509, X509_R_DELTA_CRL_WITHOUT_CRL_NUMBER);
return 0;
}
/*
* See if we have any unhandled critical CRL extensions and indicate
@@ -319,7 +341,7 @@ static int crl_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
/* Convert IDP into a more convenient form */
static void setup_idp(X509_CRL *crl, ISSUING_DIST_POINT *idp)
static int setup_idp(X509_CRL *crl, ISSUING_DIST_POINT *idp)
{
int idp_only = 0;
/* Set various flags according to IDP */
@@ -352,7 +374,7 @@ static void setup_idp(X509_CRL *crl, ISSUING_DIST_POINT *idp)
crl->idp_reasons &= CRLDP_ALL_REASONS;
}
DIST_POINT_set_dpname(idp->distpoint, X509_CRL_get_issuer(crl));
return DIST_POINT_set_dpname(idp->distpoint, X509_CRL_get_issuer(crl));
}
ASN1_SEQUENCE_ref(X509_CRL, crl_cb) = {
@@ -180,160 +180,6 @@ EVP_PKEY *X509_PUBKEY_get(X509_PUBKEY *key)
return NULL;
}
/*
* Now two pseudo ASN1 routines that take an EVP_PKEY structure and encode or
* decode as X509_PUBKEY
*/
EVP_PKEY *d2i_PUBKEY(EVP_PKEY **a, const unsigned char **pp, long length)
{
X509_PUBKEY *xpk;
EVP_PKEY *pktmp;
xpk = d2i_X509_PUBKEY(NULL, pp, length);
if (!xpk)
return NULL;
pktmp = X509_PUBKEY_get(xpk);
X509_PUBKEY_free(xpk);
if (!pktmp)
return NULL;
if (a) {
EVP_PKEY_free(*a);
*a = pktmp;
}
return pktmp;
}
int i2d_PUBKEY(const EVP_PKEY *a, unsigned char **pp)
{
X509_PUBKEY *xpk = NULL;
int ret;
if (!a)
return 0;
if (!X509_PUBKEY_set(&xpk, (EVP_PKEY *)a))
return 0;
ret = i2d_X509_PUBKEY(xpk, pp);
X509_PUBKEY_free(xpk);
return ret;
}
/*
* The following are equivalents but which return RSA and DSA keys
*/
RSA *d2i_RSA_PUBKEY(RSA **a, const unsigned char **pp, long length)
{
EVP_PKEY *pkey;
RSA *key;
const unsigned char *q;
q = *pp;
pkey = d2i_PUBKEY(NULL, &q, length);
if (!pkey)
return NULL;
key = EVP_PKEY_get1_RSA(pkey);
EVP_PKEY_free(pkey);
if (!key)
return NULL;
*pp = q;
if (a) {
RSA_free(*a);
*a = key;
}
return key;
}
int i2d_RSA_PUBKEY(const RSA *a, unsigned char **pp)
{
EVP_PKEY *pktmp;
int ret;
if (!a)
return 0;
pktmp = EVP_PKEY_new();
if (!pktmp) {
OPENSSL_PUT_ERROR(X509, ERR_R_MALLOC_FAILURE);
return 0;
}
EVP_PKEY_set1_RSA(pktmp, (RSA *)a);
ret = i2d_PUBKEY(pktmp, pp);
EVP_PKEY_free(pktmp);
return ret;
}
#ifndef OPENSSL_NO_DSA
DSA *d2i_DSA_PUBKEY(DSA **a, const unsigned char **pp, long length)
{
EVP_PKEY *pkey;
DSA *key;
const unsigned char *q;
q = *pp;
pkey = d2i_PUBKEY(NULL, &q, length);
if (!pkey)
return NULL;
key = EVP_PKEY_get1_DSA(pkey);
EVP_PKEY_free(pkey);
if (!key)
return NULL;
*pp = q;
if (a) {
DSA_free(*a);
*a = key;
}
return key;
}
int i2d_DSA_PUBKEY(const DSA *a, unsigned char **pp)
{
EVP_PKEY *pktmp;
int ret;
if (!a)
return 0;
pktmp = EVP_PKEY_new();
if (!pktmp) {
OPENSSL_PUT_ERROR(X509, ERR_R_MALLOC_FAILURE);
return 0;
}
EVP_PKEY_set1_DSA(pktmp, (DSA *)a);
ret = i2d_PUBKEY(pktmp, pp);
EVP_PKEY_free(pktmp);
return ret;
}
#endif
EC_KEY *d2i_EC_PUBKEY(EC_KEY **a, const unsigned char **pp, long length)
{
EVP_PKEY *pkey;
EC_KEY *key;
const unsigned char *q;
q = *pp;
pkey = d2i_PUBKEY(NULL, &q, length);
if (!pkey)
return (NULL);
key = EVP_PKEY_get1_EC_KEY(pkey);
EVP_PKEY_free(pkey);
if (!key)
return (NULL);
*pp = q;
if (a) {
EC_KEY_free(*a);
*a = key;
}
return (key);
}
int i2d_EC_PUBKEY(const EC_KEY *a, unsigned char **pp)
{
EVP_PKEY *pktmp;
int ret;
if (!a)
return (0);
if ((pktmp = EVP_PKEY_new()) == NULL) {
OPENSSL_PUT_ERROR(X509, ERR_R_MALLOC_FAILURE);
return (0);
}
EVP_PKEY_set1_EC_KEY(pktmp, (EC_KEY *)a);
ret = i2d_PUBKEY(pktmp, pp);
EVP_PKEY_free(pktmp);
return (ret);
}
int X509_PUBKEY_set0_param(X509_PUBKEY *pub, const ASN1_OBJECT *aobj,
int ptype, void *pval,
unsigned char *penc, int penclen)
+28 -6
View File
@@ -98,7 +98,6 @@ static int x509_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
switch (operation) {
case ASN1_OP_NEW_POST:
ret->name = NULL;
ret->ex_flags = 0;
ret->ex_pathlen = -1;
ret->skid = NULL;
@@ -115,11 +114,35 @@ static int x509_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
ret->buf = NULL;
break;
case ASN1_OP_D2I_POST:
if (ret->name != NULL)
OPENSSL_free(ret->name);
ret->name = X509_NAME_oneline(ret->cert_info->subject, NULL, 0);
case ASN1_OP_D2I_POST: {
/* The version must be one of v1(0), v2(1), or v3(2). */
long version = 0;
if (ret->cert_info->version != NULL) {
version = ASN1_INTEGER_get(ret->cert_info->version);
/* TODO(https://crbug.com/boringssl/364): |version| = 0 should also
* be rejected. This means an explicitly-encoded X.509v1 version.
* v1 is DEFAULT, so DER requires it be omitted. */
if (version < 0 || version > 2) {
OPENSSL_PUT_ERROR(X509, X509_R_INVALID_VERSION);
return 0;
}
}
/* Per RFC5280, section 4.1.2.8, these fields require v2 or v3. */
if (version == 0 && (ret->cert_info->issuerUID != NULL ||
ret->cert_info->subjectUID != NULL)) {
OPENSSL_PUT_ERROR(X509, X509_R_INVALID_FIELD_FOR_VERSION);
return 0;
}
/* Per RFC5280, section 4.1.2.9, extensions require v3. */
if (version != 2 && ret->cert_info->extensions != NULL) {
OPENSSL_PUT_ERROR(X509, X509_R_INVALID_FIELD_FOR_VERSION);
return 0;
}
break;
}
case ASN1_OP_FREE_POST:
CRYPTO_MUTEX_cleanup(&ret->lock);
@@ -132,7 +155,6 @@ static int x509_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
GENERAL_NAMES_free(ret->altname);
NAME_CONSTRAINTS_free(ret->nc);
CRYPTO_BUFFER_free(ret->buf);
OPENSSL_free(ret->name);
break;
}
@@ -48,6 +48,11 @@ int x509v3_name_cmp(const char *name, const char *cmp);
OPENSSL_EXPORT int x509v3_looks_like_dns_name(const unsigned char *in,
size_t len);
// x509v3_cache_extensions fills in a number of fields relating to X.509
// extensions in |x|. It returns one on success and zero if some extensions were
// invalid.
int x509v3_cache_extensions(X509 *x);
#if defined(__cplusplus)
} /* extern C */
@@ -68,6 +68,7 @@
#include <CCryptoBoringSSL_x509v3.h>
#include "../internal.h"
#include "internal.h"
#define V1_ROOT (EXFLAG_V1|EXFLAG_SS)
#define ku_reject(x, usage) \
@@ -77,8 +78,6 @@
#define ns_reject(x, usage) \
(((x)->ex_flags & EXFLAG_NSCERT) && !((x)->ex_nscert & (usage)))
static void x509v3_cache_extensions(X509 *x);
static int check_purpose_ssl_client(const X509_PURPOSE *xp, const X509 *x,
int ca);
static int check_purpose_ssl_server(const X509_PURPOSE *xp, const X509 *x,
@@ -144,7 +143,10 @@ int X509_check_purpose(X509 *x, int id, int ca)
{
int idx;
const X509_PURPOSE *pt;
x509v3_cache_extensions(x);
if (!x509v3_cache_extensions(x)) {
return -1;
}
if (id == -1)
return 1;
idx = X509_PURPOSE_get_by_id(id);
@@ -368,7 +370,7 @@ int X509_supported_extension(X509_EXTENSION *ex)
return 0;
}
static void setup_dp(X509 *x, DIST_POINT *dp)
static int setup_dp(X509 *x, DIST_POINT *dp)
{
X509_NAME *iname = NULL;
size_t i;
@@ -381,7 +383,7 @@ static void setup_dp(X509 *x, DIST_POINT *dp)
} else
dp->dp_reasons = CRLDP_ALL_REASONS;
if (!dp->distpoint || (dp->distpoint->type != 1))
return;
return 1;
for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
if (gen->type == GEN_DIRNAME) {
@@ -392,19 +394,25 @@ static void setup_dp(X509 *x, DIST_POINT *dp)
if (!iname)
iname = X509_get_issuer_name(x);
DIST_POINT_set_dpname(dp->distpoint, iname);
return DIST_POINT_set_dpname(dp->distpoint, iname);
}
static void setup_crldp(X509 *x)
static int setup_crldp(X509 *x)
{
size_t i;
x->crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++)
setup_dp(x, sk_DIST_POINT_value(x->crldp, i));
int j;
x->crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, &j, NULL);
if (x->crldp == NULL && j != -1) {
return 0;
}
for (size_t i = 0; i < sk_DIST_POINT_num(x->crldp); i++) {
if (!setup_dp(x, sk_DIST_POINT_value(x->crldp, i))) {
return 0;
}
}
return 1;
}
static void x509v3_cache_extensions(X509 *x)
int x509v3_cache_extensions(X509 *x)
{
BASIC_CONSTRAINTS *bs;
PROXY_CERT_INFO_EXTENSION *pci;
@@ -420,21 +428,22 @@ static void x509v3_cache_extensions(X509 *x)
CRYPTO_MUTEX_unlock_read(&x->lock);
if (is_set) {
return;
return (x->ex_flags & EXFLAG_INVALID) == 0;
}
CRYPTO_MUTEX_lock_write(&x->lock);
if (x->ex_flags & EXFLAG_SET) {
CRYPTO_MUTEX_unlock_write(&x->lock);
return;
return (x->ex_flags & EXFLAG_INVALID) == 0;
}
X509_digest(x, EVP_sha1(), x->sha1_hash, NULL);
if (!X509_digest(x, EVP_sha1(), x->sha1_hash, NULL))
x->ex_flags |= EXFLAG_INVALID;
/* V1 should mean no extensions ... */
if (!X509_get_version(x))
x->ex_flags |= EXFLAG_V1;
/* Handle basic constraints */
if ((bs = X509_get_ext_d2i(x, NID_basic_constraints, NULL, NULL))) {
if ((bs = X509_get_ext_d2i(x, NID_basic_constraints, &j, NULL))) {
if (bs->ca)
x->ex_flags |= EXFLAG_CA;
if (bs->pathlen) {
@@ -448,9 +457,11 @@ static void x509v3_cache_extensions(X509 *x)
x->ex_pathlen = -1;
BASIC_CONSTRAINTS_free(bs);
x->ex_flags |= EXFLAG_BCONS;
} else if (j != -1) {
x->ex_flags |= EXFLAG_INVALID;
}
/* Handle proxy certificates */
if ((pci = X509_get_ext_d2i(x, NID_proxyCertInfo, NULL, NULL))) {
if ((pci = X509_get_ext_d2i(x, NID_proxyCertInfo, &j, NULL))) {
if (x->ex_flags & EXFLAG_CA
|| X509_get_ext_by_NID(x, NID_subject_alt_name, -1) >= 0
|| X509_get_ext_by_NID(x, NID_issuer_alt_name, -1) >= 0) {
@@ -462,9 +473,11 @@ static void x509v3_cache_extensions(X509 *x)
x->ex_pcpathlen = -1;
PROXY_CERT_INFO_EXTENSION_free(pci);
x->ex_flags |= EXFLAG_PROXY;
} else if (j != -1) {
x->ex_flags |= EXFLAG_INVALID;
}
/* Handle key usage */
if ((usage = X509_get_ext_d2i(x, NID_key_usage, NULL, NULL))) {
if ((usage = X509_get_ext_d2i(x, NID_key_usage, &j, NULL))) {
if (usage->length > 0) {
x->ex_kusage = usage->data[0];
if (usage->length > 1)
@@ -473,9 +486,11 @@ static void x509v3_cache_extensions(X509 *x)
x->ex_kusage = 0;
x->ex_flags |= EXFLAG_KUSAGE;
ASN1_BIT_STRING_free(usage);
} else if (j != -1) {
x->ex_flags |= EXFLAG_INVALID;
}
x->ex_xkusage = 0;
if ((extusage = X509_get_ext_d2i(x, NID_ext_key_usage, NULL, NULL))) {
if ((extusage = X509_get_ext_d2i(x, NID_ext_key_usage, &j, NULL))) {
x->ex_flags |= EXFLAG_XKUSAGE;
for (i = 0; i < sk_ASN1_OBJECT_num(extusage); i++) {
switch (OBJ_obj2nid(sk_ASN1_OBJECT_value(extusage, i))) {
@@ -518,18 +533,28 @@ static void x509v3_cache_extensions(X509 *x)
}
}
sk_ASN1_OBJECT_pop_free(extusage, ASN1_OBJECT_free);
} else if (j != -1) {
x->ex_flags |= EXFLAG_INVALID;
}
if ((ns = X509_get_ext_d2i(x, NID_netscape_cert_type, NULL, NULL))) {
if ((ns = X509_get_ext_d2i(x, NID_netscape_cert_type, &j, NULL))) {
if (ns->length > 0)
x->ex_nscert = ns->data[0];
else
x->ex_nscert = 0;
x->ex_flags |= EXFLAG_NSCERT;
ASN1_BIT_STRING_free(ns);
} else if (j != -1) {
x->ex_flags |= EXFLAG_INVALID;
}
x->skid = X509_get_ext_d2i(x, NID_subject_key_identifier, &j, NULL);
if (x->skid == NULL && j != -1) {
x->ex_flags |= EXFLAG_INVALID;
}
x->akid = X509_get_ext_d2i(x, NID_authority_key_identifier, &j, NULL);
if (x->akid == NULL && j != -1) {
x->ex_flags |= EXFLAG_INVALID;
}
x->skid = X509_get_ext_d2i(x, NID_subject_key_identifier, NULL, NULL);
x->akid = X509_get_ext_d2i(x, NID_authority_key_identifier, NULL, NULL);
/* Does subject name match issuer ? */
if (!X509_NAME_cmp(X509_get_subject_name(x), X509_get_issuer_name(x))) {
x->ex_flags |= EXFLAG_SI;
@@ -538,11 +563,17 @@ static void x509v3_cache_extensions(X509 *x)
!ku_reject(x, KU_KEY_CERT_SIGN))
x->ex_flags |= EXFLAG_SS;
}
x->altname = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
x->nc = X509_get_ext_d2i(x, NID_name_constraints, &j, NULL);
if (!x->nc && (j != -1))
x->altname = X509_get_ext_d2i(x, NID_subject_alt_name, &j, NULL);
if (x->altname == NULL && j != -1) {
x->ex_flags |= EXFLAG_INVALID;
setup_crldp(x);
}
x->nc = X509_get_ext_d2i(x, NID_name_constraints, &j, NULL);
if (x->nc == NULL && j != -1) {
x->ex_flags |= EXFLAG_INVALID;
}
if (!setup_crldp(x)) {
x->ex_flags |= EXFLAG_INVALID;
}
for (j = 0; j < X509_get_ext_count(x); j++) {
ex = X509_get_ext(x, j);
@@ -559,6 +590,7 @@ static void x509v3_cache_extensions(X509 *x)
x->ex_flags |= EXFLAG_SET;
CRYPTO_MUTEX_unlock_write(&x->lock);
return (x->ex_flags & EXFLAG_INVALID) == 0;
}
/* check_ca returns one if |x| should be considered a CA certificate and zero
@@ -579,7 +611,9 @@ static int check_ca(const X509 *x)
int X509_check_ca(X509 *x)
{
x509v3_cache_extensions(x);
if (!x509v3_cache_extensions(x)) {
return 0;
}
return check_ca(x);
}
@@ -761,8 +795,10 @@ int X509_check_issued(X509 *issuer, X509 *subject)
if (X509_NAME_cmp(X509_get_subject_name(issuer),
X509_get_issuer_name(subject)))
return X509_V_ERR_SUBJECT_ISSUER_MISMATCH;
x509v3_cache_extensions(issuer);
x509v3_cache_extensions(subject);
if (!x509v3_cache_extensions(issuer) ||
!x509v3_cache_extensions(subject)) {
return X509_V_ERR_UNSPECIFIED;
}
if (subject->akid) {
int ret = X509_check_akid(issuer, subject->akid);
@@ -819,15 +855,17 @@ int X509_check_akid(X509 *issuer, AUTHORITY_KEYID *akid)
uint32_t X509_get_extension_flags(X509 *x)
{
/* Call for side-effect of computing hash and caching extensions */
X509_check_purpose(x, -1, -1);
if (!x509v3_cache_extensions(x)) {
return 0;
}
return x->ex_flags;
}
uint32_t X509_get_key_usage(X509 *x)
{
/* Call for side-effect of computing hash and caching extensions */
X509_check_purpose(x, -1, -1);
if (!x509v3_cache_extensions(x)) {
return 0;
}
if (x->ex_flags & EXFLAG_KUSAGE)
return x->ex_kusage;
return UINT32_MAX;
@@ -835,8 +873,9 @@ uint32_t X509_get_key_usage(X509 *x)
uint32_t X509_get_extended_key_usage(X509 *x)
{
/* Call for side-effect of computing hash and caching extensions */
X509_check_purpose(x, -1, -1);
if (!x509v3_cache_extensions(x)) {
return 0;
}
if (x->ex_flags & EXFLAG_XKUSAGE)
return x->ex_xkusage;
return UINT32_MAX;
+1 -1
View File
@@ -1 +1 @@
This directory is derived from BoringSSL cloned from https://boringssl.googlesource.com/boringssl at revision 53a17f55247101105ae35767d5c5a6c311843a8e
This directory is derived from BoringSSL cloned from https://boringssl.googlesource.com/boringssl at revision 54858b63c1d886f6c8d903d4a4f594f1485de189
@@ -106,7 +106,10 @@ OPENSSL_EXPORT void AES_decrypt(const uint8_t *in, uint8_t *out,
// AES_ctr128_encrypt encrypts (or decrypts, it's the same in CTR mode) |len|
// bytes from |in| to |out|. The |num| parameter must be set to zero on the
// first call and |ivec| will be incremented.
// first call and |ivec| will be incremented. This function may be called
// in-place with |in| equal to |out|, but otherwise the buffers may not
// partially overlap. A partial overlap may overwrite input data before it is
// read.
OPENSSL_EXPORT void AES_ctr128_encrypt(const uint8_t *in, uint8_t *out,
size_t len, const AES_KEY *key,
uint8_t ivec[AES_BLOCK_SIZE],
@@ -114,26 +117,35 @@ OPENSSL_EXPORT void AES_ctr128_encrypt(const uint8_t *in, uint8_t *out,
unsigned int *num);
// AES_ecb_encrypt encrypts (or decrypts, if |enc| == |AES_DECRYPT|) a single,
// 16 byte block from |in| to |out|.
// 16 byte block from |in| to |out|. This function may be called in-place with
// |in| equal to |out|, but otherwise the buffers may not partially overlap. A
// partial overlap may overwrite input data before it is read.
OPENSSL_EXPORT void AES_ecb_encrypt(const uint8_t *in, uint8_t *out,
const AES_KEY *key, const int enc);
// AES_cbc_encrypt encrypts (or decrypts, if |enc| == |AES_DECRYPT|) |len|
// bytes from |in| to |out|. The length must be a multiple of the block size.
// This function may be called in-place with |in| equal to |out|, but otherwise
// the buffers may not partially overlap. A partial overlap may overwrite input
// data before it is read.
OPENSSL_EXPORT void AES_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t len,
const AES_KEY *key, uint8_t *ivec,
const int enc);
// AES_ofb128_encrypt encrypts (or decrypts, it's the same in OFB mode) |len|
// bytes from |in| to |out|. The |num| parameter must be set to zero on the
// first call.
// first call. This function may be called in-place with |in| equal to |out|,
// but otherwise the buffers may not partially overlap. A partial overlap may
// overwrite input data before it is read.
OPENSSL_EXPORT void AES_ofb128_encrypt(const uint8_t *in, uint8_t *out,
size_t len, const AES_KEY *key,
uint8_t *ivec, int *num);
// AES_cfb128_encrypt encrypts (or decrypts, if |enc| == |AES_DECRYPT|) |len|
// bytes from |in| to |out|. The |num| parameter must be set to zero on the
// first call.
// first call. This function may be called in-place with |in| equal to |out|,
// but otherwise the buffers may not partially overlap. A partial overlap may
// overwrite input data before it is read.
OPENSSL_EXPORT void AES_cfb128_encrypt(const uint8_t *in, uint8_t *out,
size_t len, const AES_KEY *key,
uint8_t *ivec, int *num, int enc);
@@ -619,14 +619,14 @@ typedef struct BIT_STRING_BITNAME_st {
DECLARE_ASN1_FUNCTIONS_fname(ASN1_TYPE, ASN1_ANY, ASN1_TYPE)
OPENSSL_EXPORT int ASN1_TYPE_get(ASN1_TYPE *a);
OPENSSL_EXPORT int ASN1_TYPE_get(const ASN1_TYPE *a);
OPENSSL_EXPORT void ASN1_TYPE_set(ASN1_TYPE *a, int type, void *value);
OPENSSL_EXPORT int ASN1_TYPE_set1(ASN1_TYPE *a, int type, const void *value);
OPENSSL_EXPORT int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b);
OPENSSL_EXPORT ASN1_OBJECT * ASN1_OBJECT_new(void );
OPENSSL_EXPORT void ASN1_OBJECT_free(ASN1_OBJECT *a);
OPENSSL_EXPORT int i2d_ASN1_OBJECT(ASN1_OBJECT *a,unsigned char **pp);
OPENSSL_EXPORT int i2d_ASN1_OBJECT(const ASN1_OBJECT *a,unsigned char **pp);
OPENSSL_EXPORT ASN1_OBJECT * c2i_ASN1_OBJECT(ASN1_OBJECT **a,const unsigned char **pp,
long length);
OPENSSL_EXPORT ASN1_OBJECT * d2i_ASN1_OBJECT(ASN1_OBJECT **a,const unsigned char **pp,
@@ -648,23 +648,23 @@ OPENSSL_EXPORT int ASN1_STRING_set(ASN1_STRING *str, const void *data, int len
OPENSSL_EXPORT void ASN1_STRING_set0(ASN1_STRING *str, void *data, int len);
OPENSSL_EXPORT int ASN1_STRING_length(const ASN1_STRING *x);
OPENSSL_EXPORT void ASN1_STRING_length_set(ASN1_STRING *x, int n);
OPENSSL_EXPORT int ASN1_STRING_type(ASN1_STRING *x);
OPENSSL_EXPORT int ASN1_STRING_type(const ASN1_STRING *x);
OPENSSL_EXPORT unsigned char * ASN1_STRING_data(ASN1_STRING *x);
OPENSSL_EXPORT const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *x);
DECLARE_ASN1_FUNCTIONS(ASN1_BIT_STRING)
OPENSSL_EXPORT int i2c_ASN1_BIT_STRING(ASN1_BIT_STRING *a,unsigned char **pp);
OPENSSL_EXPORT int i2c_ASN1_BIT_STRING(const ASN1_BIT_STRING *a,unsigned char **pp);
OPENSSL_EXPORT ASN1_BIT_STRING *c2i_ASN1_BIT_STRING(ASN1_BIT_STRING **a,const unsigned char **pp, long length);
OPENSSL_EXPORT int ASN1_BIT_STRING_set(ASN1_BIT_STRING *a, unsigned char *d, int length );
OPENSSL_EXPORT int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value);
OPENSSL_EXPORT int ASN1_BIT_STRING_get_bit(ASN1_BIT_STRING *a, int n);
OPENSSL_EXPORT int ASN1_BIT_STRING_check(ASN1_BIT_STRING *a, unsigned char *flags, int flags_len);
OPENSSL_EXPORT int ASN1_BIT_STRING_get_bit(const ASN1_BIT_STRING *a, int n);
OPENSSL_EXPORT int ASN1_BIT_STRING_check(const ASN1_BIT_STRING *a, unsigned char *flags, int flags_len);
OPENSSL_EXPORT int i2d_ASN1_BOOLEAN(int a,unsigned char **pp);
OPENSSL_EXPORT int d2i_ASN1_BOOLEAN(int *a,const unsigned char **pp,long length);
DECLARE_ASN1_FUNCTIONS(ASN1_INTEGER)
OPENSSL_EXPORT int i2c_ASN1_INTEGER(ASN1_INTEGER *a,unsigned char **pp);
OPENSSL_EXPORT int i2c_ASN1_INTEGER(const ASN1_INTEGER *a,unsigned char **pp);
OPENSSL_EXPORT ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **a,const unsigned char **pp, long length);
OPENSSL_EXPORT ASN1_INTEGER * ASN1_INTEGER_dup(const ASN1_INTEGER *x);
OPENSSL_EXPORT int ASN1_INTEGER_cmp(const ASN1_INTEGER *x, const ASN1_INTEGER *y);
@@ -713,15 +713,15 @@ DECLARE_ASN1_ITEM(ASN1_OCTET_STRING_NDEF)
OPENSSL_EXPORT ASN1_TIME *ASN1_TIME_set(ASN1_TIME *s,time_t t);
OPENSSL_EXPORT ASN1_TIME *ASN1_TIME_adj(ASN1_TIME *s,time_t t, int offset_day, long offset_sec);
OPENSSL_EXPORT int ASN1_TIME_check(ASN1_TIME *t);
OPENSSL_EXPORT ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(ASN1_TIME *t, ASN1_GENERALIZEDTIME **out);
OPENSSL_EXPORT int ASN1_TIME_check(const ASN1_TIME *t);
OPENSSL_EXPORT ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(const ASN1_TIME *t, ASN1_GENERALIZEDTIME **out);
OPENSSL_EXPORT int ASN1_TIME_set_string(ASN1_TIME *s, const char *str);
OPENSSL_EXPORT int i2a_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *a);
OPENSSL_EXPORT int i2a_ASN1_ENUMERATED(BIO *bp, ASN1_ENUMERATED *a);
OPENSSL_EXPORT int i2a_ASN1_OBJECT(BIO *bp,ASN1_OBJECT *a);
OPENSSL_EXPORT int i2a_ASN1_STRING(BIO *bp, ASN1_STRING *a, int type);
OPENSSL_EXPORT int i2t_ASN1_OBJECT(char *buf,int buf_len,ASN1_OBJECT *a);
OPENSSL_EXPORT int i2a_ASN1_INTEGER(BIO *bp, const ASN1_INTEGER *a);
OPENSSL_EXPORT int i2a_ASN1_ENUMERATED(BIO *bp, const ASN1_ENUMERATED *a);
OPENSSL_EXPORT int i2a_ASN1_OBJECT(BIO *bp, const ASN1_OBJECT *a);
OPENSSL_EXPORT int i2a_ASN1_STRING(BIO *bp, const ASN1_STRING *a, int type);
OPENSSL_EXPORT int i2t_ASN1_OBJECT(char *buf,int buf_len, const ASN1_OBJECT *a);
OPENSSL_EXPORT ASN1_OBJECT *ASN1_OBJECT_create(int nid, unsigned char *data,int len, const char *sn, const char *ln);
@@ -732,9 +732,9 @@ OPENSSL_EXPORT ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *
OPENSSL_EXPORT BIGNUM *ASN1_INTEGER_to_BN(const ASN1_INTEGER *ai,BIGNUM *bn);
OPENSSL_EXPORT int ASN1_ENUMERATED_set(ASN1_ENUMERATED *a, long v);
OPENSSL_EXPORT long ASN1_ENUMERATED_get(ASN1_ENUMERATED *a);
OPENSSL_EXPORT ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(BIGNUM *bn, ASN1_ENUMERATED *ai);
OPENSSL_EXPORT BIGNUM *ASN1_ENUMERATED_to_BN(ASN1_ENUMERATED *ai,BIGNUM *bn);
OPENSSL_EXPORT long ASN1_ENUMERATED_get(const ASN1_ENUMERATED *a);
OPENSSL_EXPORT ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(const BIGNUM *bn, ASN1_ENUMERATED *ai);
OPENSSL_EXPORT BIGNUM *ASN1_ENUMERATED_to_BN(const ASN1_ENUMERATED *ai,BIGNUM *bn);
/* General */
/* given a string, return the correct type, max is the maximum length */
@@ -753,7 +753,7 @@ OPENSSL_EXPORT void *ASN1_item_dup(const ASN1_ITEM *it, void *x);
#ifndef OPENSSL_NO_FP_API
OPENSSL_EXPORT void *ASN1_item_d2i_fp(const ASN1_ITEM *it, FILE *in, void *x);
OPENSSL_EXPORT int ASN1_item_i2d_fp(const ASN1_ITEM *it, FILE *out, void *x);
OPENSSL_EXPORT int ASN1_STRING_print_ex_fp(FILE *fp, ASN1_STRING *str, unsigned long flags);
OPENSSL_EXPORT int ASN1_STRING_print_ex_fp(FILE *fp, const ASN1_STRING *str, unsigned long flags);
#endif
OPENSSL_EXPORT int ASN1_STRING_to_UTF8(unsigned char **out, ASN1_STRING *in);
@@ -764,12 +764,12 @@ OPENSSL_EXPORT int ASN1_UTCTIME_print(BIO *fp, const ASN1_UTCTIME *a);
OPENSSL_EXPORT int ASN1_GENERALIZEDTIME_print(BIO *fp, const ASN1_GENERALIZEDTIME *a);
OPENSSL_EXPORT int ASN1_TIME_print(BIO *fp, const ASN1_TIME *a);
OPENSSL_EXPORT int ASN1_STRING_print(BIO *bp, const ASN1_STRING *v);
OPENSSL_EXPORT int ASN1_STRING_print_ex(BIO *out, ASN1_STRING *str, unsigned long flags);
OPENSSL_EXPORT int ASN1_STRING_print_ex(BIO *out, const ASN1_STRING *str, unsigned long flags);
OPENSSL_EXPORT const char *ASN1_tag2str(int tag);
/* Used to load and write netscape format cert */
OPENSSL_EXPORT void *ASN1_item_unpack(ASN1_STRING *oct, const ASN1_ITEM *it);
OPENSSL_EXPORT void *ASN1_item_unpack(const ASN1_STRING *oct, const ASN1_ITEM *it);
OPENSSL_EXPORT ASN1_STRING *ASN1_item_pack(void *obj, const ASN1_ITEM *it, ASN1_OCTET_STRING **oct);
@@ -793,8 +793,8 @@ OPENSSL_EXPORT ASN1_VALUE * ASN1_item_d2i(ASN1_VALUE **val, const unsigned char
OPENSSL_EXPORT int ASN1_item_i2d(ASN1_VALUE *val, unsigned char **out, const ASN1_ITEM *it);
OPENSSL_EXPORT int ASN1_item_ndef_i2d(ASN1_VALUE *val, unsigned char **out, const ASN1_ITEM *it);
OPENSSL_EXPORT ASN1_TYPE *ASN1_generate_nconf(char *str, CONF *nconf);
OPENSSL_EXPORT ASN1_TYPE *ASN1_generate_v3(char *str, X509V3_CTX *cnf);
OPENSSL_EXPORT ASN1_TYPE *ASN1_generate_nconf(const char *str, CONF *nconf);
OPENSSL_EXPORT ASN1_TYPE *ASN1_generate_v3(const char *str, X509V3_CTX *cnf);
#ifdef __cplusplus
@@ -95,7 +95,7 @@ extern "C" {
#elif defined(__x86) || defined(__i386) || defined(__i386__) || defined(_M_IX86)
#define OPENSSL_32_BIT
#define OPENSSL_X86
#elif defined(__aarch64__)
#elif defined(__aarch64__) || defined(_M_ARM64)
#define OPENSSL_64_BIT
#define OPENSSL_AARCH64
#elif defined(__arm) || defined(__arm__) || defined(_M_ARM)
@@ -1573,7 +1573,6 @@
#define TRUST_TOKEN_ISSUER_set_metadata_key BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, TRUST_TOKEN_ISSUER_set_metadata_key)
#define TRUST_TOKEN_ISSUER_set_srr_key BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, TRUST_TOKEN_ISSUER_set_srr_key)
#define TRUST_TOKEN_decode_private_metadata BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, TRUST_TOKEN_decode_private_metadata)
#define TRUST_TOKEN_experiment_v0 BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, TRUST_TOKEN_experiment_v0)
#define TRUST_TOKEN_experiment_v1 BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, TRUST_TOKEN_experiment_v1)
#define TRUST_TOKEN_free BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, TRUST_TOKEN_free)
#define TRUST_TOKEN_generate_key BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, TRUST_TOKEN_generate_key)
@@ -1653,8 +1652,10 @@
#define X509_CERT_AUX_new BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CERT_AUX_new)
#define X509_CERT_AUX_print BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CERT_AUX_print)
#define X509_CINF_free BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CINF_free)
#define X509_CINF_get_signature BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CINF_get_signature)
#define X509_CINF_it BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CINF_it)
#define X509_CINF_new BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CINF_new)
#define X509_CINF_set_modified BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CINF_set_modified)
#define X509_CRL_INFO_free BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_INFO_free)
#define X509_CRL_INFO_it BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_INFO_it)
#define X509_CRL_INFO_new BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_INFO_new)
@@ -1675,14 +1676,19 @@
#define X509_CRL_get0_lastUpdate BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_get0_lastUpdate)
#define X509_CRL_get0_nextUpdate BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_get0_nextUpdate)
#define X509_CRL_get0_signature BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_get0_signature)
#define X509_CRL_get_REVOKED BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_get_REVOKED)
#define X509_CRL_get_ext BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_get_ext)
#define X509_CRL_get_ext_by_NID BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_get_ext_by_NID)
#define X509_CRL_get_ext_by_OBJ BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_get_ext_by_OBJ)
#define X509_CRL_get_ext_by_critical BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_get_ext_by_critical)
#define X509_CRL_get_ext_count BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_get_ext_count)
#define X509_CRL_get_ext_d2i BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_get_ext_d2i)
#define X509_CRL_get_issuer BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_get_issuer)
#define X509_CRL_get_lastUpdate BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_get_lastUpdate)
#define X509_CRL_get_meth_data BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_get_meth_data)
#define X509_CRL_get_nextUpdate BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_get_nextUpdate)
#define X509_CRL_get_signature_nid BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_get_signature_nid)
#define X509_CRL_get_version BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_get_version)
#define X509_CRL_it BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_it)
#define X509_CRL_match BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_match)
#define X509_CRL_new BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_CRL_new)
@@ -1817,6 +1823,8 @@
#define X509_REQ_get_extensions BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_REQ_get_extensions)
#define X509_REQ_get_pubkey BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_REQ_get_pubkey)
#define X509_REQ_get_signature_nid BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_REQ_get_signature_nid)
#define X509_REQ_get_subject_name BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_REQ_get_subject_name)
#define X509_REQ_get_version BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_REQ_get_version)
#define X509_REQ_it BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_REQ_it)
#define X509_REQ_new BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_REQ_new)
#define X509_REQ_print BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_REQ_print)
@@ -2006,6 +2014,8 @@
#define X509_get0_tbs_sigalg BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_get0_tbs_sigalg)
#define X509_get1_email BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_get1_email)
#define X509_get1_ocsp BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_get1_ocsp)
#define X509_get_X509_PUBKEY BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_get_X509_PUBKEY)
#define X509_get_cert_info BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_get_cert_info)
#define X509_get_default_cert_area BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_get_default_cert_area)
#define X509_get_default_cert_dir BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_get_default_cert_dir)
#define X509_get_default_cert_dir_env BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_get_default_cert_dir_env)
@@ -2024,10 +2034,13 @@
#define X509_get_extension_flags BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_get_extension_flags)
#define X509_get_issuer_name BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_get_issuer_name)
#define X509_get_key_usage BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_get_key_usage)
#define X509_get_notAfter BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_get_notAfter)
#define X509_get_notBefore BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_get_notBefore)
#define X509_get_pubkey BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_get_pubkey)
#define X509_get_serialNumber BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_get_serialNumber)
#define X509_get_signature_nid BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_get_signature_nid)
#define X509_get_subject_name BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_get_subject_name)
#define X509_get_version BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_get_version)
#define X509_getm_notAfter BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_getm_notAfter)
#define X509_getm_notBefore BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_getm_notBefore)
#define X509_gmtime_adj BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, X509_gmtime_adj)
@@ -2422,9 +2435,7 @@
#define ec_get_x_coordinate_as_scalar BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, ec_get_x_coordinate_as_scalar)
#define ec_group_new BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, ec_group_new)
#define ec_hash_to_curve_p384_xmd_sha512_sswu_draft07 BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, ec_hash_to_curve_p384_xmd_sha512_sswu_draft07)
#define ec_hash_to_curve_p521_xmd_sha512_sswu_draft06 BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, ec_hash_to_curve_p521_xmd_sha512_sswu_draft06)
#define ec_hash_to_scalar_p384_xmd_sha512_draft07 BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, ec_hash_to_scalar_p384_xmd_sha512_draft07)
#define ec_hash_to_scalar_p521_xmd_sha512_draft06 BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, ec_hash_to_scalar_p521_xmd_sha512_draft06)
#define ec_init_precomp BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, ec_init_precomp)
#define ec_jacobian_to_affine BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, ec_jacobian_to_affine)
#define ec_jacobian_to_affine_batch BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, ec_jacobian_to_affine_batch)
@@ -2659,13 +2670,6 @@
#define pkcs7_bundle BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, pkcs7_bundle)
#define pkcs7_parse_header BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, pkcs7_parse_header)
#define pkcs8_pbe_decrypt BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, pkcs8_pbe_decrypt)
#define pmbtoken_exp0_blind BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, pmbtoken_exp0_blind)
#define pmbtoken_exp0_client_key_from_bytes BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, pmbtoken_exp0_client_key_from_bytes)
#define pmbtoken_exp0_generate_key BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, pmbtoken_exp0_generate_key)
#define pmbtoken_exp0_issuer_key_from_bytes BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, pmbtoken_exp0_issuer_key_from_bytes)
#define pmbtoken_exp0_read BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, pmbtoken_exp0_read)
#define pmbtoken_exp0_sign BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, pmbtoken_exp0_sign)
#define pmbtoken_exp0_unblind BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, pmbtoken_exp0_unblind)
#define pmbtoken_exp1_blind BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, pmbtoken_exp1_blind)
#define pmbtoken_exp1_client_key_from_bytes BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, pmbtoken_exp1_client_key_from_bytes)
#define pmbtoken_exp1_generate_key BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, pmbtoken_exp1_generate_key)
@@ -2780,6 +2784,7 @@
#define x509_rsa_ctx_to_pss BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, x509_rsa_ctx_to_pss)
#define x509_rsa_pss_to_ctx BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, x509_rsa_pss_to_ctx)
#define x509v3_bytes_to_hex BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, x509v3_bytes_to_hex)
#define x509v3_cache_extensions BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, x509v3_cache_extensions)
#define x509v3_hex_to_bytes BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, x509v3_hex_to_bytes)
#define x509v3_looks_like_dns_name BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, x509v3_looks_like_dns_name)
#define x509v3_name_cmp BORINGSSL_ADD_PREFIX(BORINGSSL_PREFIX, x509v3_name_cmp)
@@ -1578,7 +1578,6 @@
#define _TRUST_TOKEN_ISSUER_set_metadata_key BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, TRUST_TOKEN_ISSUER_set_metadata_key)
#define _TRUST_TOKEN_ISSUER_set_srr_key BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, TRUST_TOKEN_ISSUER_set_srr_key)
#define _TRUST_TOKEN_decode_private_metadata BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, TRUST_TOKEN_decode_private_metadata)
#define _TRUST_TOKEN_experiment_v0 BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, TRUST_TOKEN_experiment_v0)
#define _TRUST_TOKEN_experiment_v1 BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, TRUST_TOKEN_experiment_v1)
#define _TRUST_TOKEN_free BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, TRUST_TOKEN_free)
#define _TRUST_TOKEN_generate_key BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, TRUST_TOKEN_generate_key)
@@ -1658,8 +1657,10 @@
#define _X509_CERT_AUX_new BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CERT_AUX_new)
#define _X509_CERT_AUX_print BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CERT_AUX_print)
#define _X509_CINF_free BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CINF_free)
#define _X509_CINF_get_signature BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CINF_get_signature)
#define _X509_CINF_it BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CINF_it)
#define _X509_CINF_new BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CINF_new)
#define _X509_CINF_set_modified BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CINF_set_modified)
#define _X509_CRL_INFO_free BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_INFO_free)
#define _X509_CRL_INFO_it BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_INFO_it)
#define _X509_CRL_INFO_new BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_INFO_new)
@@ -1680,14 +1681,19 @@
#define _X509_CRL_get0_lastUpdate BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_get0_lastUpdate)
#define _X509_CRL_get0_nextUpdate BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_get0_nextUpdate)
#define _X509_CRL_get0_signature BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_get0_signature)
#define _X509_CRL_get_REVOKED BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_get_REVOKED)
#define _X509_CRL_get_ext BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_get_ext)
#define _X509_CRL_get_ext_by_NID BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_get_ext_by_NID)
#define _X509_CRL_get_ext_by_OBJ BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_get_ext_by_OBJ)
#define _X509_CRL_get_ext_by_critical BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_get_ext_by_critical)
#define _X509_CRL_get_ext_count BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_get_ext_count)
#define _X509_CRL_get_ext_d2i BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_get_ext_d2i)
#define _X509_CRL_get_issuer BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_get_issuer)
#define _X509_CRL_get_lastUpdate BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_get_lastUpdate)
#define _X509_CRL_get_meth_data BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_get_meth_data)
#define _X509_CRL_get_nextUpdate BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_get_nextUpdate)
#define _X509_CRL_get_signature_nid BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_get_signature_nid)
#define _X509_CRL_get_version BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_get_version)
#define _X509_CRL_it BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_it)
#define _X509_CRL_match BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_match)
#define _X509_CRL_new BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_CRL_new)
@@ -1822,6 +1828,8 @@
#define _X509_REQ_get_extensions BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_REQ_get_extensions)
#define _X509_REQ_get_pubkey BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_REQ_get_pubkey)
#define _X509_REQ_get_signature_nid BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_REQ_get_signature_nid)
#define _X509_REQ_get_subject_name BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_REQ_get_subject_name)
#define _X509_REQ_get_version BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_REQ_get_version)
#define _X509_REQ_it BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_REQ_it)
#define _X509_REQ_new BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_REQ_new)
#define _X509_REQ_print BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_REQ_print)
@@ -2011,6 +2019,8 @@
#define _X509_get0_tbs_sigalg BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_get0_tbs_sigalg)
#define _X509_get1_email BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_get1_email)
#define _X509_get1_ocsp BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_get1_ocsp)
#define _X509_get_X509_PUBKEY BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_get_X509_PUBKEY)
#define _X509_get_cert_info BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_get_cert_info)
#define _X509_get_default_cert_area BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_get_default_cert_area)
#define _X509_get_default_cert_dir BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_get_default_cert_dir)
#define _X509_get_default_cert_dir_env BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_get_default_cert_dir_env)
@@ -2029,10 +2039,13 @@
#define _X509_get_extension_flags BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_get_extension_flags)
#define _X509_get_issuer_name BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_get_issuer_name)
#define _X509_get_key_usage BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_get_key_usage)
#define _X509_get_notAfter BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_get_notAfter)
#define _X509_get_notBefore BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_get_notBefore)
#define _X509_get_pubkey BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_get_pubkey)
#define _X509_get_serialNumber BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_get_serialNumber)
#define _X509_get_signature_nid BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_get_signature_nid)
#define _X509_get_subject_name BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_get_subject_name)
#define _X509_get_version BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_get_version)
#define _X509_getm_notAfter BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_getm_notAfter)
#define _X509_getm_notBefore BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_getm_notBefore)
#define _X509_gmtime_adj BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, X509_gmtime_adj)
@@ -2427,9 +2440,7 @@
#define _ec_get_x_coordinate_as_scalar BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, ec_get_x_coordinate_as_scalar)
#define _ec_group_new BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, ec_group_new)
#define _ec_hash_to_curve_p384_xmd_sha512_sswu_draft07 BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, ec_hash_to_curve_p384_xmd_sha512_sswu_draft07)
#define _ec_hash_to_curve_p521_xmd_sha512_sswu_draft06 BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, ec_hash_to_curve_p521_xmd_sha512_sswu_draft06)
#define _ec_hash_to_scalar_p384_xmd_sha512_draft07 BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, ec_hash_to_scalar_p384_xmd_sha512_draft07)
#define _ec_hash_to_scalar_p521_xmd_sha512_draft06 BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, ec_hash_to_scalar_p521_xmd_sha512_draft06)
#define _ec_init_precomp BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, ec_init_precomp)
#define _ec_jacobian_to_affine BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, ec_jacobian_to_affine)
#define _ec_jacobian_to_affine_batch BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, ec_jacobian_to_affine_batch)
@@ -2664,13 +2675,6 @@
#define _pkcs7_bundle BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, pkcs7_bundle)
#define _pkcs7_parse_header BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, pkcs7_parse_header)
#define _pkcs8_pbe_decrypt BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, pkcs8_pbe_decrypt)
#define _pmbtoken_exp0_blind BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, pmbtoken_exp0_blind)
#define _pmbtoken_exp0_client_key_from_bytes BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, pmbtoken_exp0_client_key_from_bytes)
#define _pmbtoken_exp0_generate_key BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, pmbtoken_exp0_generate_key)
#define _pmbtoken_exp0_issuer_key_from_bytes BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, pmbtoken_exp0_issuer_key_from_bytes)
#define _pmbtoken_exp0_read BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, pmbtoken_exp0_read)
#define _pmbtoken_exp0_sign BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, pmbtoken_exp0_sign)
#define _pmbtoken_exp0_unblind BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, pmbtoken_exp0_unblind)
#define _pmbtoken_exp1_blind BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, pmbtoken_exp1_blind)
#define _pmbtoken_exp1_client_key_from_bytes BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, pmbtoken_exp1_client_key_from_bytes)
#define _pmbtoken_exp1_generate_key BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, pmbtoken_exp1_generate_key)
@@ -2785,6 +2789,7 @@
#define _x509_rsa_ctx_to_pss BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, x509_rsa_ctx_to_pss)
#define _x509_rsa_pss_to_ctx BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, x509_rsa_pss_to_ctx)
#define _x509v3_bytes_to_hex BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, x509v3_bytes_to_hex)
#define _x509v3_cache_extensions BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, x509v3_cache_extensions)
#define _x509v3_hex_to_bytes BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, x509v3_hex_to_bytes)
#define _x509v3_looks_like_dns_name BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, x509v3_looks_like_dns_name)
#define _x509v3_name_cmp BORINGSSL_ADD_PREFIX_MAC_ASM(BORINGSSL_PREFIX, x509v3_name_cmp)
@@ -947,6 +947,75 @@ OPENSSL_EXPORT int EVP_PKEY_CTX_set_rsa_pss_keygen_saltlen(EVP_PKEY_CTX *ctx,
OPENSSL_EXPORT int EVP_PKEY_CTX_set_rsa_pss_keygen_mgf1_md(EVP_PKEY_CTX *ctx,
const EVP_MD *md);
// i2d_PUBKEY marshals a public key from |pkey| as a DER-encoded
// SubjectPublicKeyInfo. If |outp| is not NULL, the result is written to |*outp|
// and |*outp| is advanced just past the output. It returns the number of bytes
// in the result, whether written or not, or a negative value on error.
//
// Use |EVP_marshal_public_key| instead.
OPENSSL_EXPORT int i2d_PUBKEY(const EVP_PKEY *pkey, uint8_t **outp);
// d2i_PUBKEY parses a DER-encoded SubjectPublicKeyInfo from |len| bytes at
// |*inp|. It returns a newly-allocated result, or NULL on error. On success,
// |*inp| is advanced past the DER structure. If |out| is not NULL, it also
// frees any existing object pointed by |*out| and writes the result.
//
// Use |EVP_parse_public_key| instead.
OPENSSL_EXPORT EVP_PKEY *d2i_PUBKEY(EVP_PKEY **out, const uint8_t **inp,
long len);
// i2d_RSA_PUBKEY marshals |rsa| as a DER-encoded SubjectPublicKeyInfo. If
// |outp| is not NULL, the result is written to |*outp| and
// |*outp| is advanced just past the output. It returns the number of bytes in
// the result, whether written or not, or a negative value on error.
//
// Use |EVP_marshal_public_key| instead.
OPENSSL_EXPORT int i2d_RSA_PUBKEY(const RSA *rsa, uint8_t **outp);
// d2i_RSA_PUBKEY parses an RSA public key as a DER-encoded SubjectPublicKeyInfo
// from |len| bytes at |*inp|. It returns a newly-allocated result, or NULL on
// error. On success, |*inp| is advanced past the DER structure. If |out| is not
// NULL, it also frees any existing object pointed by |*out| and writes the
// result.
//
// Use |EVP_parse_public_key| instead.
OPENSSL_EXPORT RSA *d2i_RSA_PUBKEY(RSA **out, const uint8_t **inp, long len);
// i2d_DSA_PUBKEY marshals |dsa| as a DER-encoded SubjectPublicKeyInfo. If
// |outp| is not NULL, the result is written to |*outp| and |*outp| is advanced
// just past the output. It returns the number of bytes in the result, whether
// written or not, or a negative value on error.
//
// Use |EVP_marshal_public_key| instead.
OPENSSL_EXPORT int i2d_DSA_PUBKEY(const DSA *dsa, uint8_t **outp);
// d2i_DSA_PUBKEY parses a DSA public key as a DER-encoded SubjectPublicKeyInfo
// from |len| bytes at |*inp|. It returns a newly-allocated result, or NULL on
// error. On success, |*inp| is advanced past the DER structure. If |out| is not
// NULL, it also frees any existing object pointed by |*out| and writes the
// result.
//
// Use |EVP_parse_public_key| instead.
OPENSSL_EXPORT DSA *d2i_DSA_PUBKEY(DSA **out, const uint8_t **inp, long len);
// i2d_EC_PUBKEY marshals |ec_key| as a DER-encoded SubjectPublicKeyInfo. If
// |outp| is not NULL, the result is written to |*outp| and |*outp| is advanced
// just past the output. It returns the number of bytes in the result, whether
// written or not, or a negative value on error.
//
// Use |EVP_marshal_public_key| instead.
OPENSSL_EXPORT int i2d_EC_PUBKEY(const EC_KEY *ec_key, uint8_t **outp);
// d2i_EC_PUBKEY parses an EC public key as a DER-encoded SubjectPublicKeyInfo
// from |len| bytes at |*inp|. It returns a newly-allocated result, or NULL on
// error. On success, |*inp| is advanced past the DER structure. If |out| is not
// NULL, it also frees any existing object pointed by |*out| and writes the
// result.
//
// Use |EVP_parse_public_key| instead.
OPENSSL_EXPORT EC_KEY *d2i_EC_PUBKEY(EC_KEY **out, const uint8_t **inp,
long len);
// Preprocessor compatibility section (hidden).
//
@@ -36,13 +36,8 @@ extern "C" {
//
// WARNING: This API is unstable and subject to change.
// TRUST_TOKEN_experiment_v0 is an experimental Trust Tokens protocol using
// PMBTokens and P-521.
OPENSSL_EXPORT const TRUST_TOKEN_METHOD *TRUST_TOKEN_experiment_v0(void);
// TRUST_TOKEN_experiment_v1 is an experimental Trust Tokens protocol using
// PMBTokens and P-384. This version is still under developement and should not
// be used yet.
// PMBTokens and P-384.
OPENSSL_EXPORT const TRUST_TOKEN_METHOD *TRUST_TOKEN_experiment_v1(void);
// trust_token_st represents a single-use token for the Trust Token protocol.
@@ -234,9 +229,6 @@ OPENSSL_EXPORT int TRUST_TOKEN_ISSUER_issue(
// returning the SRR to the client. If the value has been reused, the caller
// must discard the SRR and report an error to the caller. Returning an SRR with
// replayed values allows an attacker to double-spend tokens.
//
// The private metadata construction in |TRUST_TOKEN_experiment_v0| does not
// keep the value secret and should not be used when secrecy is required.
OPENSSL_EXPORT int TRUST_TOKEN_ISSUER_redeem(
const TRUST_TOKEN_ISSUER *ctx, uint8_t **out, size_t *out_len,
TRUST_TOKEN **out_token, uint8_t **out_client_data,
@@ -246,7 +238,6 @@ OPENSSL_EXPORT int TRUST_TOKEN_ISSUER_redeem(
// TRUST_TOKEN_decode_private_metadata decodes |encrypted_bit| using the
// private metadata key specified by a |key| buffer of length |key_len| and the
// nonce by a |nonce| buffer of length |nonce_len|. The nonce in
// |TRUST_TOKEN_experiment_v0| is the client-data field of the SRR. The nonce in
// |TRUST_TOKEN_experiment_v1| is the token-hash field of the SRR. |*out_value|
// is set to the decrypted value, either zero or one. It returns one on success
// and zero on error.
File diff suppressed because it is too large. Load diff
@@ -1570,7 +1570,6 @@
%xdefine _TRUST_TOKEN_ISSUER_set_metadata_key _ %+ BORINGSSL_PREFIX %+ _TRUST_TOKEN_ISSUER_set_metadata_key
%xdefine _TRUST_TOKEN_ISSUER_set_srr_key _ %+ BORINGSSL_PREFIX %+ _TRUST_TOKEN_ISSUER_set_srr_key
%xdefine _TRUST_TOKEN_decode_private_metadata _ %+ BORINGSSL_PREFIX %+ _TRUST_TOKEN_decode_private_metadata
%xdefine _TRUST_TOKEN_experiment_v0 _ %+ BORINGSSL_PREFIX %+ _TRUST_TOKEN_experiment_v0
%xdefine _TRUST_TOKEN_experiment_v1 _ %+ BORINGSSL_PREFIX %+ _TRUST_TOKEN_experiment_v1
%xdefine _TRUST_TOKEN_free _ %+ BORINGSSL_PREFIX %+ _TRUST_TOKEN_free
%xdefine _TRUST_TOKEN_generate_key _ %+ BORINGSSL_PREFIX %+ _TRUST_TOKEN_generate_key
@@ -1650,8 +1649,10 @@
%xdefine _X509_CERT_AUX_new _ %+ BORINGSSL_PREFIX %+ _X509_CERT_AUX_new
%xdefine _X509_CERT_AUX_print _ %+ BORINGSSL_PREFIX %+ _X509_CERT_AUX_print
%xdefine _X509_CINF_free _ %+ BORINGSSL_PREFIX %+ _X509_CINF_free
%xdefine _X509_CINF_get_signature _ %+ BORINGSSL_PREFIX %+ _X509_CINF_get_signature
%xdefine _X509_CINF_it _ %+ BORINGSSL_PREFIX %+ _X509_CINF_it
%xdefine _X509_CINF_new _ %+ BORINGSSL_PREFIX %+ _X509_CINF_new
%xdefine _X509_CINF_set_modified _ %+ BORINGSSL_PREFIX %+ _X509_CINF_set_modified
%xdefine _X509_CRL_INFO_free _ %+ BORINGSSL_PREFIX %+ _X509_CRL_INFO_free
%xdefine _X509_CRL_INFO_it _ %+ BORINGSSL_PREFIX %+ _X509_CRL_INFO_it
%xdefine _X509_CRL_INFO_new _ %+ BORINGSSL_PREFIX %+ _X509_CRL_INFO_new
@@ -1672,14 +1673,19 @@
%xdefine _X509_CRL_get0_lastUpdate _ %+ BORINGSSL_PREFIX %+ _X509_CRL_get0_lastUpdate
%xdefine _X509_CRL_get0_nextUpdate _ %+ BORINGSSL_PREFIX %+ _X509_CRL_get0_nextUpdate
%xdefine _X509_CRL_get0_signature _ %+ BORINGSSL_PREFIX %+ _X509_CRL_get0_signature
%xdefine _X509_CRL_get_REVOKED _ %+ BORINGSSL_PREFIX %+ _X509_CRL_get_REVOKED
%xdefine _X509_CRL_get_ext _ %+ BORINGSSL_PREFIX %+ _X509_CRL_get_ext
%xdefine _X509_CRL_get_ext_by_NID _ %+ BORINGSSL_PREFIX %+ _X509_CRL_get_ext_by_NID
%xdefine _X509_CRL_get_ext_by_OBJ _ %+ BORINGSSL_PREFIX %+ _X509_CRL_get_ext_by_OBJ
%xdefine _X509_CRL_get_ext_by_critical _ %+ BORINGSSL_PREFIX %+ _X509_CRL_get_ext_by_critical
%xdefine _X509_CRL_get_ext_count _ %+ BORINGSSL_PREFIX %+ _X509_CRL_get_ext_count
%xdefine _X509_CRL_get_ext_d2i _ %+ BORINGSSL_PREFIX %+ _X509_CRL_get_ext_d2i
%xdefine _X509_CRL_get_issuer _ %+ BORINGSSL_PREFIX %+ _X509_CRL_get_issuer
%xdefine _X509_CRL_get_lastUpdate _ %+ BORINGSSL_PREFIX %+ _X509_CRL_get_lastUpdate
%xdefine _X509_CRL_get_meth_data _ %+ BORINGSSL_PREFIX %+ _X509_CRL_get_meth_data
%xdefine _X509_CRL_get_nextUpdate _ %+ BORINGSSL_PREFIX %+ _X509_CRL_get_nextUpdate
%xdefine _X509_CRL_get_signature_nid _ %+ BORINGSSL_PREFIX %+ _X509_CRL_get_signature_nid
%xdefine _X509_CRL_get_version _ %+ BORINGSSL_PREFIX %+ _X509_CRL_get_version
%xdefine _X509_CRL_it _ %+ BORINGSSL_PREFIX %+ _X509_CRL_it
%xdefine _X509_CRL_match _ %+ BORINGSSL_PREFIX %+ _X509_CRL_match
%xdefine _X509_CRL_new _ %+ BORINGSSL_PREFIX %+ _X509_CRL_new
@@ -1814,6 +1820,8 @@
%xdefine _X509_REQ_get_extensions _ %+ BORINGSSL_PREFIX %+ _X509_REQ_get_extensions
%xdefine _X509_REQ_get_pubkey _ %+ BORINGSSL_PREFIX %+ _X509_REQ_get_pubkey
%xdefine _X509_REQ_get_signature_nid _ %+ BORINGSSL_PREFIX %+ _X509_REQ_get_signature_nid
%xdefine _X509_REQ_get_subject_name _ %+ BORINGSSL_PREFIX %+ _X509_REQ_get_subject_name
%xdefine _X509_REQ_get_version _ %+ BORINGSSL_PREFIX %+ _X509_REQ_get_version
%xdefine _X509_REQ_it _ %+ BORINGSSL_PREFIX %+ _X509_REQ_it
%xdefine _X509_REQ_new _ %+ BORINGSSL_PREFIX %+ _X509_REQ_new
%xdefine _X509_REQ_print _ %+ BORINGSSL_PREFIX %+ _X509_REQ_print
@@ -2003,6 +2011,8 @@
%xdefine _X509_get0_tbs_sigalg _ %+ BORINGSSL_PREFIX %+ _X509_get0_tbs_sigalg
%xdefine _X509_get1_email _ %+ BORINGSSL_PREFIX %+ _X509_get1_email
%xdefine _X509_get1_ocsp _ %+ BORINGSSL_PREFIX %+ _X509_get1_ocsp
%xdefine _X509_get_X509_PUBKEY _ %+ BORINGSSL_PREFIX %+ _X509_get_X509_PUBKEY
%xdefine _X509_get_cert_info _ %+ BORINGSSL_PREFIX %+ _X509_get_cert_info
%xdefine _X509_get_default_cert_area _ %+ BORINGSSL_PREFIX %+ _X509_get_default_cert_area
%xdefine _X509_get_default_cert_dir _ %+ BORINGSSL_PREFIX %+ _X509_get_default_cert_dir
%xdefine _X509_get_default_cert_dir_env _ %+ BORINGSSL_PREFIX %+ _X509_get_default_cert_dir_env
@@ -2021,10 +2031,13 @@
%xdefine _X509_get_extension_flags _ %+ BORINGSSL_PREFIX %+ _X509_get_extension_flags
%xdefine _X509_get_issuer_name _ %+ BORINGSSL_PREFIX %+ _X509_get_issuer_name
%xdefine _X509_get_key_usage _ %+ BORINGSSL_PREFIX %+ _X509_get_key_usage
%xdefine _X509_get_notAfter _ %+ BORINGSSL_PREFIX %+ _X509_get_notAfter
%xdefine _X509_get_notBefore _ %+ BORINGSSL_PREFIX %+ _X509_get_notBefore
%xdefine _X509_get_pubkey _ %+ BORINGSSL_PREFIX %+ _X509_get_pubkey
%xdefine _X509_get_serialNumber _ %+ BORINGSSL_PREFIX %+ _X509_get_serialNumber
%xdefine _X509_get_signature_nid _ %+ BORINGSSL_PREFIX %+ _X509_get_signature_nid
%xdefine _X509_get_subject_name _ %+ BORINGSSL_PREFIX %+ _X509_get_subject_name
%xdefine _X509_get_version _ %+ BORINGSSL_PREFIX %+ _X509_get_version
%xdefine _X509_getm_notAfter _ %+ BORINGSSL_PREFIX %+ _X509_getm_notAfter
%xdefine _X509_getm_notBefore _ %+ BORINGSSL_PREFIX %+ _X509_getm_notBefore
%xdefine _X509_gmtime_adj _ %+ BORINGSSL_PREFIX %+ _X509_gmtime_adj
@@ -2419,9 +2432,7 @@
%xdefine _ec_get_x_coordinate_as_scalar _ %+ BORINGSSL_PREFIX %+ _ec_get_x_coordinate_as_scalar
%xdefine _ec_group_new _ %+ BORINGSSL_PREFIX %+ _ec_group_new
%xdefine _ec_hash_to_curve_p384_xmd_sha512_sswu_draft07 _ %+ BORINGSSL_PREFIX %+ _ec_hash_to_curve_p384_xmd_sha512_sswu_draft07
%xdefine _ec_hash_to_curve_p521_xmd_sha512_sswu_draft06 _ %+ BORINGSSL_PREFIX %+ _ec_hash_to_curve_p521_xmd_sha512_sswu_draft06
%xdefine _ec_hash_to_scalar_p384_xmd_sha512_draft07 _ %+ BORINGSSL_PREFIX %+ _ec_hash_to_scalar_p384_xmd_sha512_draft07
%xdefine _ec_hash_to_scalar_p521_xmd_sha512_draft06 _ %+ BORINGSSL_PREFIX %+ _ec_hash_to_scalar_p521_xmd_sha512_draft06
%xdefine _ec_init_precomp _ %+ BORINGSSL_PREFIX %+ _ec_init_precomp
%xdefine _ec_jacobian_to_affine _ %+ BORINGSSL_PREFIX %+ _ec_jacobian_to_affine
%xdefine _ec_jacobian_to_affine_batch _ %+ BORINGSSL_PREFIX %+ _ec_jacobian_to_affine_batch
@@ -2656,13 +2667,6 @@
%xdefine _pkcs7_bundle _ %+ BORINGSSL_PREFIX %+ _pkcs7_bundle
%xdefine _pkcs7_parse_header _ %+ BORINGSSL_PREFIX %+ _pkcs7_parse_header
%xdefine _pkcs8_pbe_decrypt _ %+ BORINGSSL_PREFIX %+ _pkcs8_pbe_decrypt
%xdefine _pmbtoken_exp0_blind _ %+ BORINGSSL_PREFIX %+ _pmbtoken_exp0_blind
%xdefine _pmbtoken_exp0_client_key_from_bytes _ %+ BORINGSSL_PREFIX %+ _pmbtoken_exp0_client_key_from_bytes
%xdefine _pmbtoken_exp0_generate_key _ %+ BORINGSSL_PREFIX %+ _pmbtoken_exp0_generate_key
%xdefine _pmbtoken_exp0_issuer_key_from_bytes _ %+ BORINGSSL_PREFIX %+ _pmbtoken_exp0_issuer_key_from_bytes
%xdefine _pmbtoken_exp0_read _ %+ BORINGSSL_PREFIX %+ _pmbtoken_exp0_read
%xdefine _pmbtoken_exp0_sign _ %+ BORINGSSL_PREFIX %+ _pmbtoken_exp0_sign
%xdefine _pmbtoken_exp0_unblind _ %+ BORINGSSL_PREFIX %+ _pmbtoken_exp0_unblind
%xdefine _pmbtoken_exp1_blind _ %+ BORINGSSL_PREFIX %+ _pmbtoken_exp1_blind
%xdefine _pmbtoken_exp1_client_key_from_bytes _ %+ BORINGSSL_PREFIX %+ _pmbtoken_exp1_client_key_from_bytes
%xdefine _pmbtoken_exp1_generate_key _ %+ BORINGSSL_PREFIX %+ _pmbtoken_exp1_generate_key
@@ -2777,6 +2781,7 @@
%xdefine _x509_rsa_ctx_to_pss _ %+ BORINGSSL_PREFIX %+ _x509_rsa_ctx_to_pss
%xdefine _x509_rsa_pss_to_ctx _ %+ BORINGSSL_PREFIX %+ _x509_rsa_pss_to_ctx
%xdefine _x509v3_bytes_to_hex _ %+ BORINGSSL_PREFIX %+ _x509v3_bytes_to_hex
%xdefine _x509v3_cache_extensions _ %+ BORINGSSL_PREFIX %+ _x509v3_cache_extensions
%xdefine _x509v3_hex_to_bytes _ %+ BORINGSSL_PREFIX %+ _x509v3_hex_to_bytes
%xdefine _x509v3_looks_like_dns_name _ %+ BORINGSSL_PREFIX %+ _x509v3_looks_like_dns_name
%xdefine _x509v3_name_cmp _ %+ BORINGSSL_PREFIX %+ _x509v3_name_cmp
@@ -4337,7 +4342,6 @@
%xdefine TRUST_TOKEN_ISSUER_set_metadata_key BORINGSSL_PREFIX %+ _TRUST_TOKEN_ISSUER_set_metadata_key
%xdefine TRUST_TOKEN_ISSUER_set_srr_key BORINGSSL_PREFIX %+ _TRUST_TOKEN_ISSUER_set_srr_key
%xdefine TRUST_TOKEN_decode_private_metadata BORINGSSL_PREFIX %+ _TRUST_TOKEN_decode_private_metadata
%xdefine TRUST_TOKEN_experiment_v0 BORINGSSL_PREFIX %+ _TRUST_TOKEN_experiment_v0
%xdefine TRUST_TOKEN_experiment_v1 BORINGSSL_PREFIX %+ _TRUST_TOKEN_experiment_v1
%xdefine TRUST_TOKEN_free BORINGSSL_PREFIX %+ _TRUST_TOKEN_free
%xdefine TRUST_TOKEN_generate_key BORINGSSL_PREFIX %+ _TRUST_TOKEN_generate_key
@@ -4417,8 +4421,10 @@
%xdefine X509_CERT_AUX_new BORINGSSL_PREFIX %+ _X509_CERT_AUX_new
%xdefine X509_CERT_AUX_print BORINGSSL_PREFIX %+ _X509_CERT_AUX_print
%xdefine X509_CINF_free BORINGSSL_PREFIX %+ _X509_CINF_free
%xdefine X509_CINF_get_signature BORINGSSL_PREFIX %+ _X509_CINF_get_signature
%xdefine X509_CINF_it BORINGSSL_PREFIX %+ _X509_CINF_it
%xdefine X509_CINF_new BORINGSSL_PREFIX %+ _X509_CINF_new
%xdefine X509_CINF_set_modified BORINGSSL_PREFIX %+ _X509_CINF_set_modified
%xdefine X509_CRL_INFO_free BORINGSSL_PREFIX %+ _X509_CRL_INFO_free
%xdefine X509_CRL_INFO_it BORINGSSL_PREFIX %+ _X509_CRL_INFO_it
%xdefine X509_CRL_INFO_new BORINGSSL_PREFIX %+ _X509_CRL_INFO_new
@@ -4439,14 +4445,19 @@
%xdefine X509_CRL_get0_lastUpdate BORINGSSL_PREFIX %+ _X509_CRL_get0_lastUpdate
%xdefine X509_CRL_get0_nextUpdate BORINGSSL_PREFIX %+ _X509_CRL_get0_nextUpdate
%xdefine X509_CRL_get0_signature BORINGSSL_PREFIX %+ _X509_CRL_get0_signature
%xdefine X509_CRL_get_REVOKED BORINGSSL_PREFIX %+ _X509_CRL_get_REVOKED
%xdefine X509_CRL_get_ext BORINGSSL_PREFIX %+ _X509_CRL_get_ext
%xdefine X509_CRL_get_ext_by_NID BORINGSSL_PREFIX %+ _X509_CRL_get_ext_by_NID
%xdefine X509_CRL_get_ext_by_OBJ BORINGSSL_PREFIX %+ _X509_CRL_get_ext_by_OBJ
%xdefine X509_CRL_get_ext_by_critical BORINGSSL_PREFIX %+ _X509_CRL_get_ext_by_critical
%xdefine X509_CRL_get_ext_count BORINGSSL_PREFIX %+ _X509_CRL_get_ext_count
%xdefine X509_CRL_get_ext_d2i BORINGSSL_PREFIX %+ _X509_CRL_get_ext_d2i
%xdefine X509_CRL_get_issuer BORINGSSL_PREFIX %+ _X509_CRL_get_issuer
%xdefine X509_CRL_get_lastUpdate BORINGSSL_PREFIX %+ _X509_CRL_get_lastUpdate
%xdefine X509_CRL_get_meth_data BORINGSSL_PREFIX %+ _X509_CRL_get_meth_data
%xdefine X509_CRL_get_nextUpdate BORINGSSL_PREFIX %+ _X509_CRL_get_nextUpdate
%xdefine X509_CRL_get_signature_nid BORINGSSL_PREFIX %+ _X509_CRL_get_signature_nid
%xdefine X509_CRL_get_version BORINGSSL_PREFIX %+ _X509_CRL_get_version
%xdefine X509_CRL_it BORINGSSL_PREFIX %+ _X509_CRL_it
%xdefine X509_CRL_match BORINGSSL_PREFIX %+ _X509_CRL_match
%xdefine X509_CRL_new BORINGSSL_PREFIX %+ _X509_CRL_new
@@ -4581,6 +4592,8 @@
%xdefine X509_REQ_get_extensions BORINGSSL_PREFIX %+ _X509_REQ_get_extensions
%xdefine X509_REQ_get_pubkey BORINGSSL_PREFIX %+ _X509_REQ_get_pubkey
%xdefine X509_REQ_get_signature_nid BORINGSSL_PREFIX %+ _X509_REQ_get_signature_nid
%xdefine X509_REQ_get_subject_name BORINGSSL_PREFIX %+ _X509_REQ_get_subject_name
%xdefine X509_REQ_get_version BORINGSSL_PREFIX %+ _X509_REQ_get_version
%xdefine X509_REQ_it BORINGSSL_PREFIX %+ _X509_REQ_it
%xdefine X509_REQ_new BORINGSSL_PREFIX %+ _X509_REQ_new
%xdefine X509_REQ_print BORINGSSL_PREFIX %+ _X509_REQ_print
@@ -4770,6 +4783,8 @@
%xdefine X509_get0_tbs_sigalg BORINGSSL_PREFIX %+ _X509_get0_tbs_sigalg
%xdefine X509_get1_email BORINGSSL_PREFIX %+ _X509_get1_email
%xdefine X509_get1_ocsp BORINGSSL_PREFIX %+ _X509_get1_ocsp
%xdefine X509_get_X509_PUBKEY BORINGSSL_PREFIX %+ _X509_get_X509_PUBKEY
%xdefine X509_get_cert_info BORINGSSL_PREFIX %+ _X509_get_cert_info
%xdefine X509_get_default_cert_area BORINGSSL_PREFIX %+ _X509_get_default_cert_area
%xdefine X509_get_default_cert_dir BORINGSSL_PREFIX %+ _X509_get_default_cert_dir
%xdefine X509_get_default_cert_dir_env BORINGSSL_PREFIX %+ _X509_get_default_cert_dir_env
@@ -4788,10 +4803,13 @@
%xdefine X509_get_extension_flags BORINGSSL_PREFIX %+ _X509_get_extension_flags
%xdefine X509_get_issuer_name BORINGSSL_PREFIX %+ _X509_get_issuer_name
%xdefine X509_get_key_usage BORINGSSL_PREFIX %+ _X509_get_key_usage
%xdefine X509_get_notAfter BORINGSSL_PREFIX %+ _X509_get_notAfter
%xdefine X509_get_notBefore BORINGSSL_PREFIX %+ _X509_get_notBefore
%xdefine X509_get_pubkey BORINGSSL_PREFIX %+ _X509_get_pubkey
%xdefine X509_get_serialNumber BORINGSSL_PREFIX %+ _X509_get_serialNumber
%xdefine X509_get_signature_nid BORINGSSL_PREFIX %+ _X509_get_signature_nid
%xdefine X509_get_subject_name BORINGSSL_PREFIX %+ _X509_get_subject_name
%xdefine X509_get_version BORINGSSL_PREFIX %+ _X509_get_version
%xdefine X509_getm_notAfter BORINGSSL_PREFIX %+ _X509_getm_notAfter
%xdefine X509_getm_notBefore BORINGSSL_PREFIX %+ _X509_getm_notBefore
%xdefine X509_gmtime_adj BORINGSSL_PREFIX %+ _X509_gmtime_adj
@@ -5186,9 +5204,7 @@
%xdefine ec_get_x_coordinate_as_scalar BORINGSSL_PREFIX %+ _ec_get_x_coordinate_as_scalar
%xdefine ec_group_new BORINGSSL_PREFIX %+ _ec_group_new
%xdefine ec_hash_to_curve_p384_xmd_sha512_sswu_draft07 BORINGSSL_PREFIX %+ _ec_hash_to_curve_p384_xmd_sha512_sswu_draft07
%xdefine ec_hash_to_curve_p521_xmd_sha512_sswu_draft06 BORINGSSL_PREFIX %+ _ec_hash_to_curve_p521_xmd_sha512_sswu_draft06
%xdefine ec_hash_to_scalar_p384_xmd_sha512_draft07 BORINGSSL_PREFIX %+ _ec_hash_to_scalar_p384_xmd_sha512_draft07
%xdefine ec_hash_to_scalar_p521_xmd_sha512_draft06 BORINGSSL_PREFIX %+ _ec_hash_to_scalar_p521_xmd_sha512_draft06
%xdefine ec_init_precomp BORINGSSL_PREFIX %+ _ec_init_precomp
%xdefine ec_jacobian_to_affine BORINGSSL_PREFIX %+ _ec_jacobian_to_affine
%xdefine ec_jacobian_to_affine_batch BORINGSSL_PREFIX %+ _ec_jacobian_to_affine_batch
@@ -5423,13 +5439,6 @@
%xdefine pkcs7_bundle BORINGSSL_PREFIX %+ _pkcs7_bundle
%xdefine pkcs7_parse_header BORINGSSL_PREFIX %+ _pkcs7_parse_header
%xdefine pkcs8_pbe_decrypt BORINGSSL_PREFIX %+ _pkcs8_pbe_decrypt
%xdefine pmbtoken_exp0_blind BORINGSSL_PREFIX %+ _pmbtoken_exp0_blind
%xdefine pmbtoken_exp0_client_key_from_bytes BORINGSSL_PREFIX %+ _pmbtoken_exp0_client_key_from_bytes
%xdefine pmbtoken_exp0_generate_key BORINGSSL_PREFIX %+ _pmbtoken_exp0_generate_key
%xdefine pmbtoken_exp0_issuer_key_from_bytes BORINGSSL_PREFIX %+ _pmbtoken_exp0_issuer_key_from_bytes
%xdefine pmbtoken_exp0_read BORINGSSL_PREFIX %+ _pmbtoken_exp0_read
%xdefine pmbtoken_exp0_sign BORINGSSL_PREFIX %+ _pmbtoken_exp0_sign
%xdefine pmbtoken_exp0_unblind BORINGSSL_PREFIX %+ _pmbtoken_exp0_unblind
%xdefine pmbtoken_exp1_blind BORINGSSL_PREFIX %+ _pmbtoken_exp1_blind
%xdefine pmbtoken_exp1_client_key_from_bytes BORINGSSL_PREFIX %+ _pmbtoken_exp1_client_key_from_bytes
%xdefine pmbtoken_exp1_generate_key BORINGSSL_PREFIX %+ _pmbtoken_exp1_generate_key
@@ -5544,6 +5553,7 @@
%xdefine x509_rsa_ctx_to_pss BORINGSSL_PREFIX %+ _x509_rsa_ctx_to_pss
%xdefine x509_rsa_pss_to_ctx BORINGSSL_PREFIX %+ _x509_rsa_pss_to_ctx
%xdefine x509v3_bytes_to_hex BORINGSSL_PREFIX %+ _x509v3_bytes_to_hex
%xdefine x509v3_cache_extensions BORINGSSL_PREFIX %+ _x509v3_cache_extensions
%xdefine x509v3_hex_to_bytes BORINGSSL_PREFIX %+ _x509v3_hex_to_bytes
%xdefine x509v3_looks_like_dns_name BORINGSSL_PREFIX %+ _x509v3_looks_like_dns_name
%xdefine x509v3_name_cmp BORINGSSL_PREFIX %+ _x509v3_name_cmp
+2 -3
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -85,7 +85,6 @@ extension AES {
}
extension AES.GCM {
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public struct SealedBox: AEADSealedBox {
private let combinedRepresentation: Data
private let nonceByteCount: Int
@@ -124,7 +123,7 @@ extension AES.GCM {
// While we have these values in the internal APIs, we can't use it in inlinable code.
let aesGCMOverhead = 12 + 16
if (combined.count < aesGCMOverhead) {
if combined.count < aesGCMOverhead {
throw CryptoKitError.incorrectParameterSize
}
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -24,7 +24,6 @@ typealias ChaChaPolyImpl = OpenSSLChaChaPolyImpl
import Foundation
/// ChaCha20-Poly1305 as described in RFC 7539 with 96-bit nonces.
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public enum ChaChaPoly: Cipher {
static let tagByteCount = 16
static let keyBitsCount = 256
@@ -87,7 +86,6 @@ public enum ChaChaPoly: Cipher {
extension ChaChaPoly {
@frozen
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public struct SealedBox: AEADSealedBox {
/// The combined representation ( nonce || ciphertext || tag)
public let combined: Data
@@ -110,7 +108,7 @@ extension ChaChaPoly {
// While we have these values in the internal APIs, we can't use it in inlinable code.
let chachaPolyOverhead = 12 + 16
if (combined.count < chachaPolyOverhead) {
if combined.count < chachaPolyOverhead {
throw CryptoKitError.incorrectParameterSize
}
+1 -1
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
+1 -1
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
+1 -1
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
+587
View File
@@ -0,0 +1,587 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_exported import CryptoKit
#else
import Foundation
// This module implements "just enough" ASN.1. Specifically, we implement exactly enough ASN.1 DER parsing to handle
// the following use-cases:
//
// 1. Being able to parse the SPKI format for EC public keys
// 2. Being able to parse the PKCS#8 format for EC private keys
// 3. Being able to parse the SEC 1 format for EC private keys (produced by `openssl ec`)
//
// Let's talk about the DER encoding of ASN.1. DER is fundamentally a TLV (type length value) encoding. Each element is
// made of up some bytes that identify its type, some bytes that identify the length, and then the contents. In the full
// scheme of ASN.1 we care about a lot of things about its structure, but for our case we only care about a few kinds of
// tag. To work out the tag we need, we can look at the X.509 representation of an EC key public key, from RFC 5480 (for case 1), as
// well as the SEC 1 format for private keys and the PKCS#8 format for private keys.
//
// ### RFC 5480 SPKI:
//
// SubjectPublicKeyInfo ::= SEQUENCE {
// algorithm AlgorithmIdentifier,
// subjectPublicKey BIT STRING
// }
//
// ### SEC 1
//
// For private keys, SEC 1 uses:
//
// ECPrivateKey ::= SEQUENCE {
// version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
// privateKey OCTET STRING,
// parameters [0] EXPLICIT ECDomainParameters OPTIONAL,
// publicKey [1] EXPLICIT BIT STRING OPTIONAL
// }
//
// ### PKCS#8
//
// For PKCS#8 we need the following for the private key:
//
// PrivateKeyInfo ::= SEQUENCE {
// version Version,
// privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
// privateKey PrivateKey,
// attributes [0] IMPLICIT Attributes OPTIONAL }
//
// Version ::= INTEGER
//
// PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
//
// PrivateKey ::= OCTET STRING
//
// Attributes ::= SET OF Attribute
//
// ### Common
//
// Several of the above use formats defined here:
//
// AlgorithmIdentifier ::= SEQUENCE {
// algorithm OBJECT IDENTIFIER,
// parameters ANY DEFINED BY algorithm OPTIONAL
// }
//
// ECParameters ::= CHOICE {
// namedCurve OBJECT IDENTIFIER
// -- implicitCurve NULL
// -- specifiedCurve SpecifiedECDomain
// }
//
// For us, we expect the ECParameters structure to be using the namedCurve representation only: as we support only the NIST curves with ASN.1
// there is no reason for the curve to ever not be named.
//
// Conveniently, this requires only a few data types from us: SEQUENCE, BIT STRING, OCTET STRING, and OBJECT IDENTIFIER. All three are
// universal objects for ASN.1. Their relevant characteristics are:
//
// ┌───────────────────┬────────────┬────────────────────────────────────────────────┬────────────────┬───────────┐
// │ Name │ Tag Number │ Primitive │ Encoding Class │ Tag Bytes │
// ├───────────────────┼────────────┼────────────────────────────────────────────────┼────────────────┼───────────┤
// │ SEQUENCE │ 0x10 │ N │ Universal │ 0x30 │
// │ BIT STRING │ 0x03 │ Y (we don't support constructed bit strings) │ Universal │ 0x03 │
// │ OBJECT IDENTIFIER │ 0x06 │ Y │ Universal │ 0x06 │
// | OCTET STRING | 0x04 | Y (we don't support constructed octet strings) | Universal | 0x04 |
// | INTEGER | 0x02 | Y | Universal | 0x02 |
// └───────────────────┴────────────┴────────────────────────────────────────────────┴────────────────┴───────────┘
//
// The subjectPublicKey is required to be in x9.62 format, either compressed or uncompressed, so we can pass it directly to the
// initializers for CryptoKit once we've done the extraction.
//
// This is the complete set of things we need to be able to parse. To make our lives easier we try to parse this set of things somewhat
// generally: that is, we don't hard-code special knowledge of these formats as part of the parsing process. Instead we have written a
// parser that can divide the world of ASN.1 into parseable chunks, and then we try to decode specific formats from those chunks. This
// allows us to extend things in the future without too much pain.
internal enum ASN1 { }
// MARK: - Parser Node
extension ASN1 {
/// An `ASN1ParserNode` is a representation of a parsed ASN.1 TLV section. An `ASN1ParserNode` may be primitive, or may be composed of other `ASN1ParserNode`s.
/// In our representation, we keep track of this by storing a node "depth", which allows rapid forward and backward scans to hop over sections
/// we're uninterested in.
///
/// This type is not exposed to users of the API: it is only used internally for implementation of the user-level API.
fileprivate struct ASN1ParserNode {
/// The identifier.
var identifier: ASN1Identifier
/// The depth of this node.
var depth: Int
/// The data bytes for this node, if it is primitive.
var dataBytes: ArraySlice<UInt8>?
}
}
extension ASN1.ASN1ParserNode: Hashable { }
extension ASN1.ASN1ParserNode: CustomStringConvertible {
var description: String {
return "ASN1.ASN1ParserNode(identifier: \(self.identifier), depth: \(self.depth), dataBytes: \(self.dataBytes?.count ?? 0))"
}
}
// MARK: - Sequence
extension ASN1 {
/// Parse the node as an ASN.1 sequence.
internal static func sequence<T>(_ node: ASN1Node, _ builder: (inout ASN1.ASN1NodeCollection.Iterator) throws -> T) throws -> T {
guard node.identifier == .sequence, case .constructed(let nodes) = node.content else {
throw CryptoKitASN1Error.unexpectedFieldType
}
var iterator = nodes.makeIterator()
let result = try builder(&iterator)
guard iterator.next() == nil else {
throw CryptoKitASN1Error.invalidASN1Object
}
return result
}
}
// MARK: - Optional explicitly tagged
extension ASN1 {
/// Parses an optional explicitly tagged element. Throws on a tag mismatch, returns nil if the element simply isn't there.
///
/// Expects to be used with the `ASN1.sequence` helper function.
internal static func optionalExplicitlyTagged<T>(_ nodes: inout ASN1.ASN1NodeCollection.Iterator, tagNumber: Int, tagClass: ASN1.ASN1Identifier.TagClass, _ builder: (ASN1Node) throws -> T) throws -> T? {
var localNodesCopy = nodes
guard let node = localNodesCopy.next() else {
// Node not present, return nil.
return nil
}
let expectedNodeID = ASN1.ASN1Identifier(explicitTagWithNumber: tagNumber, tagClass: tagClass)
assert(expectedNodeID.constructed)
guard node.identifier == expectedNodeID else {
// Node is a mismatch, with the wrong tag. Our optional isn't present.
return nil
}
// We have the right optional, so let's consume it.
nodes = localNodesCopy
// We expect a single child.
guard case .constructed(let nodes) = node.content else {
// This error is an internal parser error: the tag above is always constructed.
preconditionFailure("Explicit tags are always constructed")
}
var nodeIterator = nodes.makeIterator()
guard let child = nodeIterator.next(), nodeIterator.next() == nil else {
throw CryptoKitASN1Error.invalidASN1Object
}
return try builder(child)
}
}
// MARK: - Parsing
extension ASN1 {
/// A parsed representation of ASN.1.
fileprivate struct ASN1ParseResult {
private static let maximumNodeDepth = 10
var nodes: ArraySlice<ASN1ParserNode>
private init(_ nodes: ArraySlice<ASN1ParserNode>) {
self.nodes = nodes
}
fileprivate static func parse(_ data: ArraySlice<UInt8>) throws -> ASN1ParseResult {
var data = data
var nodes = [ASN1ParserNode]()
nodes.reserveCapacity(16)
try parseNode(from: &data, depth: 1, into: &nodes)
guard data.count == 0 else {
throw CryptoKitASN1Error.invalidASN1Object
}
return ASN1ParseResult(nodes[...])
}
/// Parses a single ASN.1 node from the data and appends it to the buffer. This may recursively
/// call itself when there are child nodes for constructed nodes.
private static func parseNode(from data: inout ArraySlice<UInt8>, depth: Int, into nodes: inout [ASN1ParserNode]) throws {
guard depth <= ASN1.ASN1ParseResult.maximumNodeDepth else {
// We defend ourselves against stack overflow by refusing to allocate more than 10 stack frames to
// the parsing.
throw CryptoKitASN1Error.invalidASN1Object
}
guard let rawIdentifier = data.popFirst() else {
throw CryptoKitASN1Error.truncatedASN1Field
}
let identifier = try ASN1Identifier(rawIdentifier: rawIdentifier)
guard let wideLength = try data.readASN1Length() else {
throw CryptoKitASN1Error.truncatedASN1Field
}
// UInt is sometimes too large for us!
guard let length = Int(exactly: wideLength) else {
throw CryptoKitASN1Error.invalidASN1Object
}
var subData = data.prefix(length)
data = data.dropFirst(length)
guard subData.count == length else {
throw CryptoKitASN1Error.truncatedASN1Field
}
if identifier.constructed {
nodes.append(ASN1ParserNode(identifier: identifier, depth: depth, dataBytes: nil))
while subData.count > 0 {
try parseNode(from: &subData, depth: depth + 1, into: &nodes)
}
} else {
nodes.append(ASN1ParserNode(identifier: identifier, depth: depth, dataBytes: subData))
}
}
}
}
extension ASN1.ASN1ParseResult: Hashable { }
extension ASN1 {
static func parse(_ data: [UInt8]) throws -> ASN1Node {
return try parse(data[...])
}
static func parse(_ data: ArraySlice<UInt8>) throws -> ASN1Node {
var result = try ASN1ParseResult.parse(data)
// There will always be at least one node if the above didn't throw, so we can safely just removeFirst here.
let firstNode = result.nodes.removeFirst()
let rootNode: ASN1Node
if firstNode.identifier.constructed {
// We need to feed it the next set of nodes.
let nodeCollection = result.nodes.prefix { $0.depth > firstNode.depth }
result.nodes = result.nodes.dropFirst(nodeCollection.count)
rootNode = ASN1.ASN1Node(identifier: firstNode.identifier, content: .constructed(.init(nodes: nodeCollection, depth: firstNode.depth)))
} else {
rootNode = ASN1.ASN1Node(identifier: firstNode.identifier, content: .primitive(firstNode.dataBytes!))
}
precondition(result.nodes.count == 0, "ASN1ParseResult unexpectedly allowed multiple root nodes")
return rootNode
}
}
// MARK: - ASN1NodeCollection
extension ASN1 {
/// Represents a collection of ASN.1 nodes contained in a constructed ASN.1 node.
///
/// Constructed ASN.1 nodes are made up of multiple child nodes. This object represents the collection of those child nodes.
/// It allows us to lazily construct the child nodes, potentially skipping over them when we don't care about them.
internal struct ASN1NodeCollection {
private var nodes: ArraySlice<ASN1ParserNode>
private var depth: Int
fileprivate init(nodes: ArraySlice<ASN1ParserNode>, depth: Int) {
self.nodes = nodes
self.depth = depth
precondition(self.nodes.allSatisfy({ $0.depth > depth }))
if let firstDepth = self.nodes.first?.depth {
precondition(firstDepth == depth + 1)
}
}
}
}
extension ASN1.ASN1NodeCollection: Sequence {
struct Iterator: IteratorProtocol {
private var nodes: ArraySlice<ASN1.ASN1ParserNode>
private var depth: Int
fileprivate init(nodes: ArraySlice<ASN1.ASN1ParserNode>, depth: Int) {
self.nodes = nodes
self.depth = depth
}
mutating func next() -> ASN1.ASN1Node? {
guard let nextNode = self.nodes.popFirst() else {
return nil
}
assert(nextNode.depth == self.depth + 1)
if nextNode.identifier.constructed {
// We need to feed it the next set of nodes.
let nodeCollection = self.nodes.prefix { $0.depth > nextNode.depth }
self.nodes = self.nodes.dropFirst(nodeCollection.count)
return ASN1.ASN1Node(identifier: nextNode.identifier, content: .constructed(.init(nodes: nodeCollection, depth: nextNode.depth)))
} else {
// There must be data bytes here, even if they're empty.
return ASN1.ASN1Node(identifier: nextNode.identifier, content: .primitive(nextNode.dataBytes!))
}
}
}
func makeIterator() -> Iterator {
return Iterator(nodes: self.nodes, depth: self.depth)
}
}
// MARK: - ASN1Node
extension ASN1 {
/// An `ASN1Node` is a single entry in the ASN.1 representation of a data structure.
///
/// Conceptually, an ASN.1 data structure is rooted in a single node, which may itself contain zero or more
/// other nodes. ASN.1 nodes are either "constructed", meaning they contain other nodes, or "primitive", meaning they
/// store a base data type of some kind.
///
/// In this way, ASN.1 objects tend to form a "tree", where each object is represented by a single top-level constructed
/// node that contains other objects and primitives, eventually reaching the bottom which is made up of primitive objects.
internal struct ASN1Node {
internal var identifier: ASN1Identifier
internal var content: Content
}
}
// MARK: - ASN1Node.Content
extension ASN1.ASN1Node {
/// The content of a single ASN1Node.
enum Content {
case constructed(ASN1.ASN1NodeCollection)
case primitive(ArraySlice<UInt8>)
}
}
// MARK: - Serializing
extension ASN1 {
struct Serializer {
private(set) var serializedBytes: [UInt8]
init() {
// We allocate a 1kB array because that should cover us most of the time.
self.serializedBytes = []
self.serializedBytes.reserveCapacity(1024)
}
/// Appends a single, non-constructed node to the content.
mutating func appendPrimitiveNode(identifier: ASN1.ASN1Identifier, _ contentWriter: (inout [UInt8]) throws -> Void) rethrows {
assert(identifier.primitive)
try self._appendNode(identifier: identifier) { try contentWriter(&$0.serializedBytes) }
}
mutating func appendConstructedNode(identifier: ASN1.ASN1Identifier, _ contentWriter: (inout Serializer) throws -> Void) rethrows {
assert(identifier.constructed)
try self._appendNode(identifier: identifier, contentWriter)
}
mutating func serialize<T: ASN1Serializable>(_ node: T) throws {
try node.serialize(into: &self)
}
mutating func serialize<T: ASN1Serializable>(_ node: T, explicitlyTaggedWithTagNumber tagNumber: Int, tagClass: ASN1.ASN1Identifier.TagClass) throws {
let identifier = ASN1Identifier(explicitTagWithNumber: tagNumber, tagClass: tagClass)
try self.appendConstructedNode(identifier: identifier) { coder in
try coder.serialize(node)
}
}
// This is the base logical function that all other append methods are built on. This one has most of the logic, and doesn't
// police what we expect to happen in the content writer.
private mutating func _appendNode(identifier: ASN1.ASN1Identifier, _ contentWriter: (inout Serializer) throws -> Void) rethrows {
// This is a tricky game to play. We want to write the identifier and the length, but we don't know what the
// length is here. To get around that, we _assume_ the length will be one byte, and let the writer write their content.
// If it turns out to have been longer, we recalculate how many bytes we need and shuffle them in the buffer,
// before updating the length. Most of the time we'll be right: occasionally we'll be wrong and have to shuffle.
self.serializedBytes.writeIdentifier(identifier)
// Write a zero for the length.
self.serializedBytes.append(0)
// Save the indices and write.
let originalEndIndex = self.serializedBytes.endIndex
let lengthIndex = self.serializedBytes.index(before: originalEndIndex)
try contentWriter(&self)
let contentLength = self.serializedBytes.distance(from: originalEndIndex, to: self.serializedBytes.endIndex)
let lengthBytesNeeded = contentLength.bytesNeededToEncode
if lengthBytesNeeded == 1 {
// We can just set this at the top, and we're done!
assert(contentLength <= 0x7F)
self.serializedBytes[lengthIndex] = UInt8(contentLength)
return
}
// Whoops, we need more than one byte to represent the length. That's annoying!
// To sort this out we want to "move" the memory to the right.
self.serializedBytes.moveRange(offset: lengthBytesNeeded - 1, range: originalEndIndex..<self.serializedBytes.endIndex)
// Now we can write the length bytes back. We first write the number of length bytes
// we needed, setting the high bit. Then we write the bytes of the length.
self.serializedBytes[lengthIndex] = 0x80 | UInt8(lengthBytesNeeded - 1)
var writeIndex = lengthIndex
for shift in (0..<(lengthBytesNeeded - 1)).reversed() {
// Shift and mask the integer.
self.serializedBytes.formIndex(after: &writeIndex)
self.serializedBytes[writeIndex] = UInt8((contentLength >> (shift * 8)) | 0x80 )
}
assert(writeIndex == self.serializedBytes.index(lengthIndex, offsetBy: lengthBytesNeeded - 1))
}
}
}
// MARK: - Helpers
internal protocol ASN1Parseable {
init(asn1Encoded: ASN1.ASN1Node) throws
}
extension ASN1Parseable {
internal init(asn1Encoded sequenceNodeIterator: inout ASN1.ASN1NodeCollection.Iterator) throws {
guard let node = sequenceNodeIterator.next() else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = try .init(asn1Encoded: node)
}
internal init(asn1Encoded: [UInt8]) throws {
self = try .init(asn1Encoded: ASN1.parse(asn1Encoded))
}
}
internal protocol ASN1Serializable {
func serialize(into coder: inout ASN1.Serializer) throws
}
extension ArraySlice where Element == UInt8 {
fileprivate mutating func readASN1Length() throws -> UInt? {
guard let firstByte = self.popFirst() else {
return nil
}
switch firstByte {
case 0x80:
// Indefinite form. Unsupported.
throw CryptoKitASN1Error.unsupportedFieldLength
case let val where val & 0x80 == 0x80:
// Top bit is set, this is the long form. The remaining 7 bits of this octet
// determine how long the length field is.
let fieldLength = Int(val & 0x7F)
guard self.count >= fieldLength else {
return nil
}
// We need to read the length bytes
let lengthBytes = self.prefix(fieldLength)
self = self.dropFirst(fieldLength)
let length = try UInt(bigEndianBytes: lengthBytes)
// DER requires that we enforce that the length field was encoded in the minimum number of octets necessary.
let requiredBits = UInt.bitWidth - length.leadingZeroBitCount
switch requiredBits {
case 0...7:
// For 0 to 7 bits, the long form is unnacceptable and we require the short.
throw CryptoKitASN1Error.unsupportedFieldLength
case 8...:
// For 8 or more bits, fieldLength should be the minimum required.
let requiredBytes = (requiredBits + 7) / 8
if fieldLength > requiredBytes {
throw CryptoKitASN1Error.unsupportedFieldLength
}
default:
// This is not reachable, but we'll error anyway.
throw CryptoKitASN1Error.unsupportedFieldLength
}
return length
case let val:
// Short form, the length is only one 7-bit integer.
return UInt(val)
}
}
}
extension FixedWidthInteger {
internal init<Bytes: Collection>(bigEndianBytes bytes: Bytes) throws where Bytes.Element == UInt8 {
guard bytes.count <= (Self.bitWidth / 8) else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = 0
let shiftSizes = stride(from: 0, to: bytes.count * 8, by: 8).reversed()
var index = bytes.startIndex
for shift in shiftSizes {
self |= Self(truncatingIfNeeded: bytes[index]) << shift
bytes.formIndex(after: &index)
}
}
}
extension Array where Element == UInt8 {
fileprivate mutating func writeIdentifier(_ identifier: ASN1.ASN1Identifier) {
self.append(identifier.baseTag)
}
fileprivate mutating func moveRange(offset: Int, range: Range<Index>) {
// We only bothered to implement this for positive offsets for now, the algorithm
// generalises.
precondition(offset > 0)
let distanceFromEndOfRangeToEndOfSelf = self.distance(from: range.endIndex, to: self.endIndex)
if distanceFromEndOfRangeToEndOfSelf < offset {
// We begin by writing some zeroes out to the size we need.
for _ in 0..<(offset - distanceFromEndOfRangeToEndOfSelf) {
self.append(0)
}
}
// Now we walk the range backwards, moving the elements.
for index in range.reversed() {
self[index + offset] = self[index]
}
}
}
extension Int {
fileprivate var bytesNeededToEncode: Int {
// ASN.1 lengths are in two forms. If we can store the length in 7 bits, we should:
// that requires only one byte. Otherwise, we need multiple bytes: work out how many,
// plus one for the length of the length bytes.
if self <= 0x7F {
return 1
} else {
// We need to work out how many bytes we need. There are many fancy bit-twiddling
// ways of doing this, but honestly we don't do this enough to need them, so we'll
// do it the easy way. This math is done on UInt because it makes the shift semantics clean.
// We save a branch here because we can never overflow this addition.
return UInt(self).neededBytes &+ 1
}
}
}
extension FixedWidthInteger {
// Bytes needed to store a given integer.
internal var neededBytes: Int {
let neededBits = self.bitWidth - self.leadingZeroBitCount
return (neededBits + 7) / 8
}
}
#endif // Linux or !SwiftPM
@@ -0,0 +1,63 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_exported import CryptoKit
#else
import Foundation
extension ASN1 {
/// A bitstring is a representation of...well...some bits.
struct ASN1BitString: ASN1Parseable, ASN1Serializable {
var bytes: ArraySlice<UInt8>
init(asn1Encoded node: ASN1.ASN1Node) throws {
guard node.identifier == .primitiveBitString else {
throw CryptoKitASN1Error.unexpectedFieldType
}
guard case .primitive(let content) = node.content else {
preconditionFailure("ASN.1 parser generated primitive node with constructed content")
}
// The initial octet explains how many of the bits in the _final_ octet are not part of the bitstring.
// The only value we support here is 0.
guard content.first == 0 else {
throw CryptoKitASN1Error.invalidASN1Object
}
self.bytes = content.dropFirst()
}
init(bytes: ArraySlice<UInt8>) {
self.bytes = bytes
}
func serialize(into coder: inout ASN1.Serializer) throws {
coder.appendPrimitiveNode(identifier: .primitiveBitString) { bytes in
bytes.append(0)
bytes.append(contentsOf: self.bytes)
}
}
}
}
extension ASN1.ASN1BitString: Hashable { }
extension ASN1.ASN1BitString: ContiguousBytes {
func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
return try self.bytes.withUnsafeBytes(body)
}
}
#endif // Linux or !SwiftPM
@@ -0,0 +1,108 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_exported import CryptoKit
#else
import Foundation
extension ASN1 {
/// An `ASN1Identifier` is a representation of the abstract notion of an ASN.1 identifier. Identifiers have a number of properties that relate to both the specific
/// tag number as well as the properties of the identifier in the stream.
internal struct ASN1Identifier {
/// The base tag. In a general ASN.1 implementation we'd need an arbitrary precision integer here as the tag number can be arbitrarily large, but
/// we don't need the full generality here.
private(set) var baseTag: UInt8
/// Whether this tag is primitive.
var primitive: Bool {
return self.baseTag & 0x20 == 0
}
/// Whether this tag is constructed.
var constructed: Bool {
return !self.primitive
}
enum TagClass {
case universal
case application
case contextSpecific
case `private`
}
/// The class of this tag.
var tagClass: TagClass {
switch self.baseTag >> 6 {
case 0x00:
return .universal
case 0x01:
return .application
case 0x02:
return .contextSpecific
case 0x03:
return .private
default:
fatalError("Unreachable")
}
}
init(rawIdentifier: UInt8) throws {
// We don't support multibyte identifiers, which are signalled when the bottom 5 bits are all 1.
guard rawIdentifier & 0x1F != 0x1F else {
throw CryptoKitASN1Error.invalidFieldIdentifier
}
self.baseTag = rawIdentifier
}
init(explicitTagWithNumber number: Int, tagClass: TagClass) {
precondition(number >= 0)
precondition(number < 0x1F)
self.baseTag = UInt8(number)
switch tagClass {
case .universal:
preconditionFailure("Explicit tags may not be universal")
case .application:
self.baseTag |= 1 << 6
case .contextSpecific:
self.baseTag |= 2 << 6
case .private:
self.baseTag |= 3 << 6
}
// Explicit tags are always constructed.
self.baseTag |= 0x20
}
}
}
extension ASN1.ASN1Identifier {
internal static let objectIdentifier = try! ASN1.ASN1Identifier(rawIdentifier: 0x06)
internal static let primitiveBitString = try! ASN1.ASN1Identifier(rawIdentifier: 0x03)
internal static let primitiveOctetString = try! ASN1.ASN1Identifier(rawIdentifier: 0x04)
internal static let integer = try! ASN1.ASN1Identifier(rawIdentifier: 0x02)
internal static let sequence = try! ASN1.ASN1Identifier(rawIdentifier: 0x30)
}
extension ASN1.ASN1Identifier: Hashable { }
extension ASN1.ASN1Identifier: CustomStringConvertible {
var description: String {
return "ASN1Identifier(\(self.baseTag))"
}
}
#endif // Linux or !SwiftPM
@@ -0,0 +1,268 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_exported import CryptoKit
#else
import Foundation
/// A protocol that represents any internal object that can present itself as a INTEGER, or be parsed from
/// a INTEGER.
///
/// This is not a very good solution for a fully-fledged ASN.1 library: we'd rather have a better numerics
/// protocol that could both initialize from and serialize to either bytes or words. However, no such
/// protocol exists today.
protocol ASN1IntegerRepresentable: ASN1Parseable, ASN1Serializable {
associatedtype IntegerBytes: RandomAccessCollection where IntegerBytes.Element == UInt8
/// Whether this type can represent signed integers. If this is set to false, the serializer and
/// parser will automatically handle padding with leading zero bytes as needed.
static var isSigned: Bool { get }
init(asn1IntegerBytes: ArraySlice<UInt8>) throws
func withBigEndianIntegerBytes<ReturnType>(_ body: (IntegerBytes) throws -> ReturnType) rethrows -> ReturnType
}
extension ASN1IntegerRepresentable {
internal init(asn1Encoded node: ASN1.ASN1Node) throws {
guard node.identifier == .integer else {
throw CryptoKitASN1Error.unexpectedFieldType
}
guard case .primitive(var dataBytes) = node.content else {
preconditionFailure("ASN.1 parser generated primitive node with constructed content")
}
// Zero bytes of integer is not an acceptable encoding.
guard dataBytes.count > 0 else {
throw CryptoKitASN1Error.invalidASN1IntegerEncoding
}
// 8.3.2 If the contents octets of an integer value encoding consist of more than one octet, then the bits of the first octet and bit 8 of the second octet:
//
// a) shall not all be ones; and
// b) shall not all be zero.
//
// NOTE – These rules ensure that an integer value is always encoded in the smallest possible number of octets.
if let first = dataBytes.first, let second = dataBytes.dropFirst().first {
if (first == 0xFF) && second.topBitSet ||
(first == 0x00) && !second.topBitSet {
throw CryptoKitASN1Error.invalidASN1IntegerEncoding
}
}
// If the type we're trying to decode is unsigned, and the top byte is zero, we should strip it.
// If the top bit is set, however, this is an invalid conversion: the number needs to be positive!
if !Self.isSigned, let first = dataBytes.first {
if first == 0x00 {
dataBytes = dataBytes.dropFirst()
} else if first & 0x80 == 0x80 {
throw CryptoKitASN1Error.invalidASN1IntegerEncoding
}
}
self = try Self(asn1IntegerBytes: dataBytes)
}
internal func serialize(into coder: inout ASN1.Serializer) throws {
coder.appendPrimitiveNode(identifier: .integer) { bytes in
self.withBigEndianIntegerBytes { integerBytes in
// If the number of bytes is 0, we're encoding a zero. That actually _does_ require one byte.
if integerBytes.count == 0 {
bytes.append(0)
return
}
// If self is unsigned and the first byte has the top bit set, we need to prepend a 0 byte.
if !Self.isSigned, let topByte = integerBytes.first, topByte.topBitSet {
bytes.append(0)
bytes.append(contentsOf: integerBytes)
} else {
// Either self is signed, or the top bit isn't set. Either way, trim to make sure the representation is minimal.
bytes.append(contentsOf: integerBytes.trimLeadingExcessBytes())
}
}
}
}
}
// MARK: - Auto-conformance for FixedWidthInteger with fixed width magnitude.
extension ASN1IntegerRepresentable where Self: FixedWidthInteger {
init(asn1IntegerBytes bytes: ArraySlice<UInt8>) throws {
// Defer to the FixedWidthInteger constructor.
// There's a wrinkle here: if this is a signed integer, and the top bit of the data bytes was set,
// then we need to 1-extend the bytes. This is because ASN.1 tries to delete redundant bytes that
// are all 1.
self = try Self(bigEndianBytes: bytes)
if Self.isSigned, let first = bytes.first, first.topBitSet {
for shift in stride(from: self.bitWidth - self.leadingZeroBitCount, to: self.bitWidth, by: 8) {
self |= 0xFF << shift
}
}
}
func withBigEndianIntegerBytes<ReturnType>(_ body: (IntegerBytesCollection<Self>) throws -> ReturnType) rethrows -> ReturnType {
return try body(IntegerBytesCollection(self))
}
}
struct IntegerBytesCollection<Integer: FixedWidthInteger> {
private var integer: Integer
init(_ integer: Integer) {
self.integer = integer
}
}
extension IntegerBytesCollection: RandomAccessCollection {
struct Index {
fileprivate var byteNumber: Int
fileprivate init(byteNumber: Int) {
self.byteNumber = byteNumber
}
fileprivate var shift: Integer {
// As byte number 0 is the end index, the byte number is one byte too large for the shift.
return Integer((self.byteNumber - 1) * 8)
}
}
var startIndex: Index {
return Index(byteNumber: Int(self.integer.neededBytes))
}
var endIndex: Index {
return Index(byteNumber: 0)
}
var count: Int {
return Int(self.integer.neededBytes)
}
subscript(index: Index) -> UInt8 {
// We perform the bitwise operations in magnitude space.
let shifted = Integer.Magnitude(truncatingIfNeeded: self.integer) >> index.shift
let masked = shifted & 0xFF
return UInt8(masked)
}
}
extension IntegerBytesCollection.Index: Equatable { }
extension IntegerBytesCollection.Index: Comparable {
// Comparable here is backwards to the original ordering.
static func <(lhs: Self, rhs: Self) -> Bool {
return lhs.byteNumber > rhs.byteNumber
}
static func >(lhs: Self, rhs: Self) -> Bool {
return lhs.byteNumber < rhs.byteNumber
}
static func <=(lhs: Self, rhs: Self) -> Bool {
return lhs.byteNumber >= rhs.byteNumber
}
static func >=(lhs: Self, rhs: Self) -> Bool {
return lhs.byteNumber <= rhs.byteNumber
}
}
extension IntegerBytesCollection.Index: Strideable {
func advanced(by n: Int) -> IntegerBytesCollection<Integer>.Index {
return IntegerBytesCollection.Index(byteNumber: self.byteNumber - n)
}
func distance(to other: IntegerBytesCollection<Integer>.Index) -> Int {
// Remember that early indices have high byte numbers and later indices have low ones.
return self.byteNumber - other.byteNumber
}
}
extension Int8: ASN1IntegerRepresentable { }
extension UInt8: ASN1IntegerRepresentable { }
extension Int16: ASN1IntegerRepresentable { }
extension UInt16: ASN1IntegerRepresentable { }
extension Int32: ASN1IntegerRepresentable { }
extension UInt32: ASN1IntegerRepresentable { }
extension Int64: ASN1IntegerRepresentable { }
extension UInt64: ASN1IntegerRepresentable { }
extension Int: ASN1IntegerRepresentable { }
extension UInt: ASN1IntegerRepresentable { }
extension RandomAccessCollection where Element == UInt8 {
fileprivate func trimLeadingExcessBytes() -> SubSequence {
var slice = self[...]
guard let first = slice.first else {
// Easy case, empty.
return slice
}
let wholeByte: UInt8
switch first {
case 0:
wholeByte = 0
case 0xFF:
wholeByte = 0xFF
default:
// We're already fine, this is maximally compact. We need the whole thing.
return slice
}
// We never trim this to less than one byte, as that's always the smallest representation.
while slice.count > 1 {
// If the first byte is equal to our original first byte, and the top bit
// of the next byte is also equal to that, then we need to drop the byte and
// go again.
if slice.first != wholeByte {
break
}
guard let second = slice.dropFirst().first else {
preconditionFailure("Loop condition violated: must be at least two bytes left")
}
if second & 0x80 != wholeByte & 0x80 {
// Different top bit, we need the leading byte.
break
}
// Both the first byte and the top bit of the next are all zero or all 1, drop the leading
// byte.
slice = slice.dropFirst()
}
return slice
}
}
extension UInt8 {
fileprivate var topBitSet: Bool {
return (self & 0x80) != 0
}
}
#endif // Linux or !SwiftPM
@@ -0,0 +1,56 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_exported import CryptoKit
#else
import Foundation
extension ASN1 {
/// An octet string is a representation of a string of octets.
struct ASN1OctetString: ASN1Parseable, ASN1Serializable {
var bytes: ArraySlice<UInt8>
init(asn1Encoded node: ASN1.ASN1Node) throws {
guard node.identifier == .primitiveOctetString else {
throw CryptoKitASN1Error.unexpectedFieldType
}
guard case .primitive(let content) = node.content else {
preconditionFailure("ASN.1 parser generated primitive node with constructed content")
}
self.bytes = content
}
init(contentBytes: ArraySlice<UInt8>) {
self.bytes = contentBytes
}
func serialize(into coder: inout ASN1.Serializer) throws {
coder.appendPrimitiveNode(identifier: .primitiveOctetString) { bytes in
bytes.append(contentsOf: self.bytes)
}
}
}
}
extension ASN1.ASN1OctetString: Hashable { }
extension ASN1.ASN1OctetString: ContiguousBytes {
func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
return try self.bytes.withUnsafeBytes(body)
}
}
#endif // Linux or !SwiftPM
@@ -0,0 +1,37 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_exported import CryptoKit
#else
// For temporary purposes we pretend that ArraySlice is our "bigint" type. We don't really need anything else.
extension ArraySlice: ASN1Serializable where Element == UInt8 { }
extension ArraySlice: ASN1Parseable where Element == UInt8 { }
extension ArraySlice: ASN1IntegerRepresentable where Element == UInt8 {
// We only use unsigned "bigint"s
static var isSigned: Bool {
return false
}
init(asn1IntegerBytes: ArraySlice<UInt8>) throws {
self = asn1IntegerBytes
}
func withBigEndianIntegerBytes<ReturnType>(_ body: (ArraySlice<UInt8>) throws -> ReturnType) rethrows -> ReturnType {
return try body(self)
}
}
#endif
@@ -0,0 +1,186 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_exported import CryptoKit
#else
import Foundation
extension ASN1 {
/// An Object Identifier is a representation of some kind of object: really any kind of object.
///
/// It represents a node in an OID hierarchy, and is usually represented as an ordered sequence of numbers.
///
/// We mostly don't care about the semantics of the thing, we just care about being able to store and compare them.
struct ASN1ObjectIdentifier: ASN1Parseable, ASN1Serializable {
private var oidComponents: [UInt]
init(asn1Encoded node: ASN1.ASN1Node) throws {
guard node.identifier == .objectIdentifier else {
throw CryptoKitASN1Error.unexpectedFieldType
}
guard case .primitive(var content) = node.content else {
preconditionFailure("ASN.1 parser generated primitive node with constructed content")
}
// We have to parse the content. From the spec:
//
// > Each subidentifier is represented as a series of (one or more) octets. Bit 8 of each octet indicates whether it
// > is the last in the series: bit 8 of the last octet is zero, bit 8 of each preceding octet is one. Bits 7 to 1 of
// > the octets in the series collectively encode the subidentifier. Conceptually, these groups of bits are concatenated
// > to form an unsigned binary number whose most significant bit is bit 7 of the first octet and whose least significant
// > bit is bit 1 of the last octet. The subidentifier shall be encoded in the fewest possible octets[...].
// >
// > The number of subidentifiers (N) shall be one less than the number of object identifier components in the object identifier
// > value being encoded.
// >
// > The numerical value of the first subidentifier is derived from the values of the first _two_ object identifier components
// > in the object identifier value being encoded, using the formula:
// >
// > (X*40) + Y
// >
// > where X is the value of the first object identifier component and Y is the value of the second object identifier component.
//
// Yeah, this is a bit bananas, but basically there are only 3 first OID components (0, 1, 2) and there are no more than 39 children
// of nodes 0 or 1. In my view this is too clever by half, but the ITU.T didn't ask for my opinion when they were coming up with this
// scheme, likely because I was in middle school at the time.
var subcomponents = [UInt]()
while content.count > 0 {
subcomponents.append(try content.readOIDSubidentifier())
}
guard subcomponents.count >= 2 else {
throw CryptoKitASN1Error.invalidObjectIdentifier
}
// Now we need to expand the subcomponents out. This means we need to undo the step above. The first component will be in the range 0..<40
// when the first oidComponent is 0, 40..<80 when the first oidComponent is 1, and 80+ when the first oidComponent is 2.
var oidComponents = [UInt]()
oidComponents.reserveCapacity(subcomponents.count + 1)
switch subcomponents.first! {
case ..<40:
oidComponents.append(0)
oidComponents.append(subcomponents.first!)
case 40 ..< 80:
oidComponents.append(1)
oidComponents.append(subcomponents.first! - 40)
default:
oidComponents.append(2)
oidComponents.append(subcomponents.first! - 80)
}
oidComponents.append(contentsOf: subcomponents.dropFirst())
self.oidComponents = oidComponents
}
func serialize(into coder: inout ASN1.Serializer) throws {
coder.appendPrimitiveNode(identifier: .objectIdentifier) { bytes in
var components = self.oidComponents[...]
guard let firstComponent = components.popFirst(), let secondComponent = components.popFirst() else {
preconditionFailure("Invalid number of OID components: must be at least two!")
}
let serializedFirstComponent = (firstComponent * 40) + secondComponent
ASN1ObjectIdentifier.writeOIDSubidentifier(serializedFirstComponent, into: &bytes)
while let component = components.popFirst() {
ASN1ObjectIdentifier.writeOIDSubidentifier(component, into: &bytes)
}
}
}
private static func writeOIDSubidentifier(_ identifier: UInt, into array: inout [UInt8]) {
// An OID subidentifier is written as an integer over 7-bit bytes, where the last byte has the top bit unset.
// The first thing we need is to know how many bits we need to write
let bitsToWrite = UInt.bitWidth - identifier.leadingZeroBitCount
let bytesToWrite = (bitsToWrite + 6) / 7
guard bytesToWrite > 0 else {
// Just a zero.
array.append(0)
return
}
for byteNumber in (1..<bytesToWrite).reversed() {
let shift = byteNumber * 7
let byte = UInt8((identifier >> shift) & 0x7f) | 0x80
array.append(byte)
}
// Last byte to append here, we must unset the top bit.
let byte = UInt8((identifier & 0x7F))
array.append(byte)
}
}
}
extension ASN1.ASN1ObjectIdentifier: Hashable {}
extension ASN1.ASN1ObjectIdentifier: ExpressibleByArrayLiteral {
init(arrayLiteral elements: UInt...) {
self.oidComponents = elements
}
}
extension ASN1.ASN1ObjectIdentifier {
enum NamedCurves {
static let secp256r1: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 10_045, 3, 1, 7]
static let secp384r1: ASN1.ASN1ObjectIdentifier = [1, 3, 132, 0, 34]
static let secp521r1: ASN1.ASN1ObjectIdentifier = [1, 3, 132, 0, 35]
}
enum AlgorithmIdentifier {
static let idEcPublicKey: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 10_045, 2, 1]
}
}
extension ArraySlice where Element == UInt8 {
mutating fileprivate func readOIDSubidentifier() throws -> UInt {
// In principle OID subidentifiers can be too large to fit into a UInt. We are choosing to not care about that
// because for us it shouldn't matter.
guard let subidentifierEndIndex = self.firstIndex(where: { $0 & 0x80 == 0x00 }) else {
throw CryptoKitASN1Error.invalidASN1Object
}
let oidSlice = self[self.startIndex ... subidentifierEndIndex]
self = self[self.index(after: subidentifierEndIndex)...]
// We need to compact the bits. These are 7-bit integers, which is really awkward.
return try UInt(sevenBitBigEndianBytes: oidSlice)
}
}
extension UInt {
fileprivate init<Bytes: Collection>(sevenBitBigEndianBytes bytes: Bytes) throws where Bytes.Element == UInt8 {
// We need to know how many bytes we _need_ to store this "int".
guard ((bytes.count * 7) + 7) / 8 <= MemoryLayout<UInt>.size else {
throw CryptoKitASN1Error.invalidASN1Object
}
self = 0
let shiftSizes = stride(from: 0, to: bytes.count * 7, by: 7).reversed()
var index = bytes.startIndex
for shift in shiftSizes {
self |= UInt(bytes[index] & 0x7F) << shift
bytes.formIndex(after: &index)
}
}
}
#endif // Linux or !SwiftPM
+55
View File
@@ -0,0 +1,55 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_exported import CryptoKit
#else
import Foundation
extension ASN1 {
/// An ECDSA signature is laid out as follows:
///
/// ECDSASignature ::= SEQUENCE {
/// r INTEGER,
/// s INTEGER
/// }
///
/// This type is generic because our different backends want to use different bignum representations.
struct ECDSASignature<IntegerType: ASN1IntegerRepresentable>: ASN1Parseable, ASN1Serializable {
var r: IntegerType
var s: IntegerType
init(r: IntegerType, s: IntegerType) {
self.r = r
self.s = s
}
init(asn1Encoded rootNode: ASN1.ASN1Node) throws {
self = try ASN1.sequence(rootNode) { nodes in
let r = try IntegerType(asn1Encoded: &nodes)
let s = try IntegerType(asn1Encoded: &nodes)
return ECDSASignature(r: r, s: s)
}
}
func serialize(into coder: inout ASN1.Serializer) throws {
try coder.appendConstructedNode(identifier: .sequence) { coder in
try coder.serialize(self.r)
try coder.serialize(self.s)
}
}
}
}
#endif // Linux or !SwiftPM
+118
View File
@@ -0,0 +1,118 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_exported import CryptoKit
#else
import Foundation
extension ASN1 {
/// A PEM document is some data, and a discriminator type that is used to advertise the content.
struct PEMDocument {
private static let lineLength = 64
var type: String
var derBytes: Data
init(pemString: String) throws {
// A PEM document looks like this:
//
// -----BEGIN <SOME DISCRIMINATOR>-----
// <base64 encoded bytes, 64 characters per line>
// -----END <SOME DISCRIMINATOR>-----
//
// This function attempts to parse this string as a PEM document, and returns the discriminator type
// and the base64 decoded bytes.
var lines = pemString.split { $0.isNewline }[...]
guard let first = lines.first, let last = lines.last else {
throw CryptoKitASN1Error.invalidPEMDocument
}
guard let discriminator = first.pemStartDiscriminator, discriminator == last.pemEndDiscriminator else {
throw CryptoKitASN1Error.invalidPEMDocument
}
// All but the last line must be 64 bytes. The force unwrap is safe because we require the lines to be
// greater than zero.
lines = lines.dropFirst().dropLast()
guard lines.count > 0,
lines.dropLast().allSatisfy({ $0.utf8.count == PEMDocument.lineLength }),
lines.last!.utf8.count <= PEMDocument.lineLength else {
throw CryptoKitASN1Error.invalidPEMDocument
}
guard let derBytes = Data(base64Encoded: lines.joined()) else {
throw CryptoKitASN1Error.invalidPEMDocument
}
self.type = discriminator
self.derBytes = derBytes
}
init(type: String, derBytes: Data) {
self.type = type
self.derBytes = derBytes
}
var pemString: String {
var encoded = self.derBytes.base64EncodedString()[...]
let pemLineCount = (encoded.utf8.count + PEMDocument.lineLength) / PEMDocument.lineLength
var pemLines = [Substring]()
pemLines.reserveCapacity(pemLineCount + 2)
pemLines.append("-----BEGIN \(self.type)-----")
while encoded.count > 0 {
let prefixIndex = encoded.index(encoded.startIndex, offsetBy: PEMDocument.lineLength, limitedBy: encoded.endIndex) ?? encoded.endIndex
pemLines.append(encoded[..<prefixIndex])
encoded = encoded[prefixIndex...]
}
pemLines.append("-----END \(self.type)-----")
return pemLines.joined(separator: "\n")
}
}
}
extension Substring {
fileprivate var pemStartDiscriminator: String? {
return self.pemDiscriminator(expectedPrefix: "-----BEGIN ", expectedSuffix: "-----")
}
fileprivate var pemEndDiscriminator: String? {
return self.pemDiscriminator(expectedPrefix: "-----END ", expectedSuffix: "-----")
}
private func pemDiscriminator(expectedPrefix: String, expectedSuffix: String) -> String? {
var utf8Bytes = self.utf8[...]
// We want to split this sequence into three parts: the prefix, the middle, and the end
let prefixSize = expectedPrefix.utf8.count
let suffixSize = expectedSuffix.utf8.count
let prefix = utf8Bytes.prefix(prefixSize)
utf8Bytes = utf8Bytes.dropFirst(prefixSize)
let suffix = utf8Bytes.suffix(suffixSize)
utf8Bytes = utf8Bytes.dropLast(suffixSize)
guard prefix.elementsEqual(expectedPrefix.utf8), suffix.elementsEqual(expectedSuffix.utf8) else {
return nil
}
return String(utf8Bytes)
}
}
#endif // Linux or !SwiftPM
+99
View File
@@ -0,0 +1,99 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_exported import CryptoKit
#else
import Foundation
extension ASN1 {
// A PKCS#8 private key is one of two formats, depending on the version:
//
// For PKCS#8 we need the following for the private key:
//
// PrivateKeyInfo ::= SEQUENCE {
// version Version,
// privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
// privateKey PrivateKey,
// attributes [0] IMPLICIT Attributes OPTIONAL }
//
// Version ::= INTEGER
//
// PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
//
// PrivateKey ::= OCTET STRING
//
// Attributes ::= SET OF Attribute
//
// We disregard the attributes because we don't support them anyway.
//
// The private key octet string contains (surprise!) a SEC1-encoded private key! So we recursively invoke the
// ASN.1 parser and go again.
struct PKCS8PrivateKey: ASN1Parseable, ASN1Serializable {
var algorithm: RFC5480AlgorithmIdentifier
var privateKey: ASN1.SEC1PrivateKey
init(asn1Encoded rootNode: ASN1.ASN1Node) throws {
self = try ASN1.sequence(rootNode) { nodes in
let version = try Int(asn1Encoded: &nodes)
guard version == 0 else {
throw CryptoKitASN1Error.invalidASN1Object
}
let algorithm = try ASN1.RFC5480AlgorithmIdentifier(asn1Encoded: &nodes)
let privateKeyBytes = try ASN1.ASN1OctetString(asn1Encoded: &nodes)
// We ignore the attributes
_ = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { _ in }
let sec1PrivateKeyNode = try ASN1.parse(privateKeyBytes.bytes)
let sec1PrivateKey = try ASN1.SEC1PrivateKey(asn1Encoded: sec1PrivateKeyNode)
if let innerAlgorithm = sec1PrivateKey.algorithm, innerAlgorithm != algorithm {
throw CryptoKitASN1Error.invalidASN1Object
}
return try .init(algorithm: algorithm, privateKey: sec1PrivateKey)
}
}
private init(algorithm: ASN1.RFC5480AlgorithmIdentifier, privateKey: ASN1.SEC1PrivateKey) throws {
self.privateKey = privateKey
self.algorithm = algorithm
}
init(algorithm: ASN1.RFC5480AlgorithmIdentifier, privateKey: [UInt8], publicKey: [UInt8]) {
self.algorithm = algorithm
// We nil out the private key here. I don't really know why we do this, but OpenSSL does, and it seems
// safe enough to do: it certainly avoids the possibility of disagreeing on what it is!
self.privateKey = ASN1.SEC1PrivateKey(privateKey: privateKey, algorithm: nil, publicKey: publicKey)
}
func serialize(into coder: inout ASN1.Serializer) throws {
try coder.appendConstructedNode(identifier: .sequence) { coder in
try coder.serialize(0) // version
try coder.serialize(self.algorithm)
// Here's a weird one: we recursively serialize the private key, and then turn the bytes into an octet string.
var subCoder = ASN1.Serializer()
try subCoder.serialize(self.privateKey)
let serializedKey = ASN1.ASN1OctetString(contentBytes: subCoder.serializedBytes[...])
try coder.serialize(serializedKey)
}
}
}
}
#endif // Linux or !SwiftPM
+104
View File
@@ -0,0 +1,104 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_exported import CryptoKit
#else
import Foundation
extension ASN1 {
// For private keys, SEC 1 uses:
//
// ECPrivateKey ::= SEQUENCE {
// version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
// privateKey OCTET STRING,
// parameters [0] EXPLICIT ECDomainParameters OPTIONAL,
// publicKey [1] EXPLICIT BIT STRING OPTIONAL
// }
struct SEC1PrivateKey: ASN1Parseable, ASN1Serializable {
var algorithm: ASN1.RFC5480AlgorithmIdentifier?
var privateKey: ASN1.ASN1OctetString
var publicKey: ASN1.ASN1BitString?
init(asn1Encoded rootNode: ASN1.ASN1Node) throws {
self = try ASN1.sequence(rootNode) { nodes in
let version = try Int(asn1Encoded: &nodes)
guard 1 == version else {
throw CryptoKitASN1Error.invalidASN1Object
}
let privateKey = try ASN1OctetString(asn1Encoded: &nodes)
let parameters = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in
return try ASN1.ASN1ObjectIdentifier(asn1Encoded: node)
}
let publicKey = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) { node in
return try ASN1.ASN1BitString(asn1Encoded: node)
}
return try .init(privateKey: privateKey, algorithm: parameters, publicKey: publicKey)
}
}
private init(privateKey: ASN1.ASN1OctetString, algorithm: ASN1.ASN1ObjectIdentifier?, publicKey: ASN1.ASN1BitString?) throws {
self.privateKey = privateKey
self.publicKey = publicKey
self.algorithm = try algorithm.map { algorithmOID in
switch algorithmOID {
case ASN1ObjectIdentifier.NamedCurves.secp256r1:
return .ecdsaP256
case ASN1ObjectIdentifier.NamedCurves.secp384r1:
return .ecdsaP384
case ASN1ObjectIdentifier.NamedCurves.secp521r1:
return .ecdsaP521
default:
throw CryptoKitASN1Error.invalidASN1Object
}
}
}
init(privateKey: [UInt8], algorithm: RFC5480AlgorithmIdentifier?, publicKey: [UInt8]) {
self.privateKey = ASN1OctetString(contentBytes: privateKey[...])
self.algorithm = algorithm
self.publicKey = ASN1BitString(bytes: publicKey[...])
}
func serialize(into coder: inout ASN1.Serializer) throws {
try coder.appendConstructedNode(identifier: .sequence) { coder in
try coder.serialize(1) // version
try coder.serialize(self.privateKey)
if let algorithm = self.algorithm {
let oid: ASN1.ASN1ObjectIdentifier
switch algorithm {
case .ecdsaP256:
oid = ASN1ObjectIdentifier.NamedCurves.secp256r1
case .ecdsaP384:
oid = ASN1ObjectIdentifier.NamedCurves.secp384r1
case .ecdsaP521:
oid = ASN1ObjectIdentifier.NamedCurves.secp521r1
}
try coder.serialize(oid, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific)
}
if let publicKey = self.publicKey {
try coder.serialize(publicKey, explicitlyTaggedWithTagNumber: 1, tagClass: .contextSpecific)
}
}
}
}
}
#endif // Linux or !SwiftPM
@@ -0,0 +1,117 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_exported import CryptoKit
#else
import Foundation
extension ASN1 {
struct SubjectPublicKeyInfo: ASN1Parseable, ASN1Serializable {
var algorithmIdentifier: RFC5480AlgorithmIdentifier
var key: ASN1.ASN1BitString
init(asn1Encoded rootNode: ASN1.ASN1Node) throws {
// The SPKI block looks like this:
//
// SubjectPublicKeyInfo ::= SEQUENCE {
// algorithm AlgorithmIdentifier,
// subjectPublicKey BIT STRING
// }
self = try ASN1.sequence(rootNode) { nodes in
let algorithmIdentifier = try ASN1.RFC5480AlgorithmIdentifier(asn1Encoded: &nodes)
let key = try ASN1.ASN1BitString(asn1Encoded: &nodes)
return SubjectPublicKeyInfo(algorithmIdentifier: algorithmIdentifier, key: key)
}
}
private init(algorithmIdentifier: RFC5480AlgorithmIdentifier, key: ASN1.ASN1BitString) {
self.algorithmIdentifier = algorithmIdentifier
self.key = key
}
internal init(algorithmIdentifier: RFC5480AlgorithmIdentifier, key: [UInt8]) {
self.algorithmIdentifier = algorithmIdentifier
self.key = ASN1BitString(bytes: key[...])
}
func serialize(into coder: inout ASN1.Serializer) throws {
try coder.appendConstructedNode(identifier: .sequence) { coder in
try coder.serialize(self.algorithmIdentifier)
try coder.serialize(self.key)
}
}
}
enum RFC5480AlgorithmIdentifier: ASN1Parseable, ASN1Serializable {
case ecdsaP256
case ecdsaP384
case ecdsaP521
init(asn1Encoded rootNode: ASN1.ASN1Node) throws {
// The AlgorithmIdentifier block looks like this.
//
// AlgorithmIdentifier ::= SEQUENCE {
// algorithm OBJECT IDENTIFIER,
// parameters ANY DEFINED BY algorithm OPTIONAL
// }
//
// ECParameters ::= CHOICE {
// namedCurve OBJECT IDENTIFIER
// -- implicitCurve NULL
// -- specifiedCurve SpecifiedECDomain
// }
//
// We don't bother with helpers: we just try to decode it directly.
self = try ASN1.sequence(rootNode) { nodes in
let algorithmOID = try ASN1.ASN1ObjectIdentifier(asn1Encoded: &nodes)
guard algorithmOID == ASN1ObjectIdentifier.AlgorithmIdentifier.idEcPublicKey else {
throw CryptoKitASN1Error.invalidASN1Object
}
let curveNameOID = try ASN1.ASN1ObjectIdentifier(asn1Encoded: &nodes)
switch curveNameOID {
case ASN1ObjectIdentifier.NamedCurves.secp256r1:
return .ecdsaP256
case ASN1ObjectIdentifier.NamedCurves.secp384r1:
return .ecdsaP384
case ASN1ObjectIdentifier.NamedCurves.secp521r1:
return .ecdsaP521
default:
throw CryptoKitASN1Error.invalidASN1Object
}
}
}
func serialize(into coder: inout ASN1.Serializer) throws {
try coder.appendConstructedNode(identifier: .sequence) { coder in
try coder.serialize(ASN1ObjectIdentifier.AlgorithmIdentifier.idEcPublicKey)
switch self {
case .ecdsaP256:
try coder.serialize(ASN1ObjectIdentifier.NamedCurves.secp256r1)
case .ecdsaP384:
try coder.serialize(ASN1ObjectIdentifier.NamedCurves.secp384r1)
case .ecdsaP521:
try coder.serialize(ASN1ObjectIdentifier.NamedCurves.secp521r1)
}
}
}
}
}
#endif // Linux or !SwiftPM
+29 -2
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -19,11 +19,38 @@
/// - incorrectParameterSize: The number of bytes passed for a given argument is incorrect.
/// - authenticationFailure: The authentication tag or signature is incorrect.
/// - underlyingCoreCryptoError: An unexpected error at a lower-level occured.
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public enum CryptoKitError: Error {
case incorrectKeySize
case incorrectParameterSize
case authenticationFailure
case underlyingCoreCryptoError(error: Int32)
}
/// Errors encountered when parsing ASN.1 formatted keys.
public enum CryptoKitASN1Error: Error {
/// The ASN.1 tag for this field is invalid or unsupported.
case invalidFieldIdentifier
/// The ASN.1 tag for the parsed field does not match the required format.
case unexpectedFieldType
/// An invalid ASN.1 object identifier was encountered.
case invalidObjectIdentifier
/// The format of the parsed ASN.1 object does not match the format required for the data type
/// being decoded.
case invalidASN1Object
/// An ASN.1 integer was decoded that does not use the minimum number of bytes for its encoding.
case invalidASN1IntegerEncoding
/// An ASN.1 field was truncated and could not be decoded.
case truncatedASN1Field
/// The encoding used for the field length is not supported.
case unsupportedFieldLength
/// It was not possible to parse a string as a PEM document.
case invalidPEMDocument
}
#endif
+2 -3
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -17,7 +17,6 @@
import Foundation
/// A protocol defining requirements for digests
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public protocol Digest: Hashable, ContiguousBytes, CustomStringConvertible, Sequence where Element == UInt8 {
static var byteCount: Int { get }
}
@@ -33,7 +32,7 @@ extension DigestPrivate {
return Self(bufferPointer: bufferPointer)
}
if (some != nil) {
if some != nil {
self = some!
} else {
return nil
+3 -8
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -19,7 +19,6 @@
// see section `gyb` in `README` for details.
// MARK: - SHA256Digest + DigestPrivate
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public struct SHA256Digest: DigestPrivate {
let bytes: (UInt64, UInt64, UInt64, UInt64)
@@ -67,7 +66,6 @@ public struct SHA256Digest: DigestPrivate {
// MARK: - SHA384Digest + DigestPrivate
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public struct SHA384Digest: DigestPrivate {
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
@@ -117,7 +115,6 @@ public struct SHA384Digest: DigestPrivate {
// MARK: - SHA512Digest + DigestPrivate
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public struct SHA512Digest: DigestPrivate {
let bytes: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64)
@@ -167,9 +164,8 @@ public struct SHA512Digest: DigestPrivate {
}
}
extension Insecure {
extension Insecure{
// MARK: - SHA1Digest + DigestPrivate
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public struct SHA1Digest: DigestPrivate {
let bytes: (UInt64, UInt64, UInt64)
@@ -214,9 +210,8 @@ public struct SHA1Digest: DigestPrivate {
}
}
}
extension Insecure {
extension Insecure{
// MARK: - MD5Digest + DigestPrivate
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public struct MD5Digest: DigestPrivate {
let bytes: (UInt64, UInt64)
+3 -3
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -28,7 +28,8 @@ digests_and_length = [{"name": "SHA256", "count": 32},{"name": "SHA384","count":
}%
%{
if "prefix" in HF.keys():
protocol_prefix = "extension " + HF["prefix"] + " {"
protocol_prefix = ""
protocol_prefix = protocol_prefix + "extension " + HF["prefix"] + "{"
protocol_suffix = "}"
else:
protocol_prefix = ""
@@ -36,7 +37,6 @@ digests_and_length = [{"name": "SHA256", "count": 32},{"name": "SHA384","count":
}%
${protocol_prefix}
// MARK: - ${name}Digest + DigestPrivate
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public struct ${name}Digest: DigestPrivate {
let bytes: (${(wordsCount-1)*"UInt64, "+"UInt64"})
+1 -3
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -23,10 +23,8 @@ typealias DigestImpl = OpenSSLDigestImpl
import Foundation
/// Declares methods on cryptographic hash functions.
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public protocol HashFunction {
/// The block size of the hash function. It is different from the output size that can be retrieved from Digest.byteCount.
@available(iOS 13.2, macOS 10.15, watchOS 6.1, tvOS 13.2, macCatalyst 13.2, *)
static var blockByteCount: Int { get }
#if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
associatedtype Digest: CryptoKit.Digest
+34 -10
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -15,11 +15,19 @@
@_exported import CryptoKit
#else
/// The SHA-256 Hash Function
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public struct SHA256: HashFunctionImplementationDetails {
public static var blockByteCount: Int = 64
public static var blockByteCount: Int {
get { return 64 }
set { fatalError("Cannot set SHA256.blockByteCount") }
}
public static var byteCount: Int {
get { return 32 }
set { fatalError("Cannot set SHA256.byteCount") }
}
public typealias Digest = SHA256Digest
public static var byteCount = 32
var impl: DigestImpl<SHA256>
/// Initializes the hash function instance.
@@ -43,11 +51,19 @@ public struct SHA256: HashFunctionImplementationDetails {
}
/// The SHA-384 Hash Function
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public struct SHA384: HashFunctionImplementationDetails {
public static var blockByteCount: Int = 128
public static var blockByteCount: Int {
get { return 128 }
set { fatalError("Cannot set SHA384.blockByteCount") }
}
public static var byteCount: Int {
get { return 48 }
set { fatalError("Cannot set SHA384.byteCount") }
}
public typealias Digest = SHA384Digest
public static var byteCount = 48
var impl: DigestImpl<SHA384>
public init() {
@@ -67,11 +83,19 @@ public struct SHA384: HashFunctionImplementationDetails {
}
/// The SHA-512 Hash Function
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public struct SHA512: HashFunctionImplementationDetails {
public static var blockByteCount: Int = 128
public static var blockByteCount: Int {
get { return 128 }
set { fatalError("Cannot set SHA512.blockByteCount") }
}
public static var byteCount: Int {
get { return 64 }
set { fatalError("Cannot set SHA512.byteCount") }
}
public typealias Digest = SHA512Digest
public static var byteCount = 64
var impl: DigestImpl<SHA512>
/// Initializes the hash function instance.
+1 -2
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -16,6 +16,5 @@
#else
/// Algorithms that we support for legacy reasons but that are insecure to use.
/// Do not adopt in new protocols.
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public enum Insecure {}
#endif // Linux or !SwiftPM
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -18,9 +18,19 @@ extension Insecure {
/// The SHA-1 Hash Function.
/// ⚠️ Security Recommendation: The SHA-1 hash function is no longer considered secure. We strongly recommend using the SHA-256 hash function instead.
public struct SHA1: HashFunctionImplementationDetails {
public static var blockByteCount: Int = 64
public static var blockByteCount: Int {
get { return 64 }
set { fatalError("Cannot set SHA1.blockByteCount") }
}
public static var byteCount: Int {
get { return 20 }
set { fatalError("Cannot set SHA1.byteCount") }
}
public typealias Digest = Insecure.SHA1Digest
public static var byteCount = 20
var impl: DigestImpl<SHA1>
/// Initializes the hash function instance.
@@ -43,9 +53,18 @@ extension Insecure {
/// The MD5 Hash Function.
/// ⚠️ Security Recommendation: The MD5 hash function is no longer considered secure. We strongly recommend using the SHA-256 hash function instead.
public struct MD5: HashFunctionImplementationDetails {
public static var blockByteCount: Int = 64
public static var blockByteCount: Int {
get { return 64 }
set { fatalError("Cannot set MD5.blockByteCount") }
}
public static var byteCount: Int {
get { return 16 }
set { fatalError("Cannot set MD5.byteCount") }
}
public typealias Digest = Insecure.MD5Digest
public static var byteCount = 16
var impl: DigestImpl<MD5>
/// Initializes the hash function instance.
+2 -6
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -31,7 +31,6 @@ protocol DiffieHellmanKeyAgreement {
/// A Key Agreement Result
/// A SharedSecret has to go through a Key Derivation Function before being able to use by a symmetric key operation.
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public struct SharedSecret: ContiguousBytes {
var ss: SecureBytes
@@ -109,7 +108,7 @@ public struct SharedSecret: ContiguousBytes {
/// - outputByteCount: The length in bytes of resulting symmetric key.
/// - Returns: The derived symmetric key
public func hkdfDerivedSymmetricKey<H: HashFunction, Salt: DataProtocol, SI: DataProtocol>(using hashFunction: H.Type, salt: Salt, sharedInfo: SI, outputByteCount: Int) -> SymmetricKey {
return HKDF<H>.deriveKey(inputKeyMaterial: ss, salt: salt, info: sharedInfo, outputByteCount: outputByteCount)
return HKDF<H>.deriveKey(inputKeyMaterial: SymmetricKey(data: ss), salt: salt, info: sharedInfo, outputByteCount: outputByteCount)
}
}
@@ -141,14 +140,11 @@ extension SharedSecret: CustomStringConvertible, Equatable {
extension HashFunction {
// A wrapper function to keep the unsafe code in one place.
@usableFromInline
mutating func update(_ secret: SharedSecret) {
secret.withUnsafeBytes {
self.update(bufferPointer: $0)
}
}
@usableFromInline
mutating func update(_ counter: UInt32) {
withUnsafeBytes(of: counter) {
self.update(bufferPointer: $0)
+433 -1
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -47,6 +47,20 @@ extension P256 {
impl = try NISTCurvePublicKeyImpl(x963Representation: x963Representation)
}
public init(pemRepresentation: String) throws {
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
guard pem.type == "PUBLIC KEY" else {
throw CryptoKitASN1Error.invalidPEMDocument
}
self = try .init(derRepresentation: pem.derBytes)
}
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
let parsed = try ASN1.SubjectPublicKeyInfo(asn1Encoded: bytes)
self = try .init(x963Representation: parsed.key)
}
init(impl: NISTCurvePublicKeyImpl<P256.CurveDetails>) {
self.impl = impl
}
@@ -54,6 +68,20 @@ extension P256 {
public var compactRepresentation: Data? { impl.compactRepresentation }
public var rawRepresentation: Data { impl.rawRepresentation }
public var x963Representation: Data { impl.x963Representation }
public var derRepresentation: Data {
let spki = ASN1.SubjectPublicKeyInfo(algorithmIdentifier: .ecdsaP256, key: Array(self.x963Representation))
var serializer = ASN1.Serializer()
// Serializing these keys can't throw
try! serializer.serialize(spki)
return Data(serializer.serializedBytes)
}
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PUBLIC KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
}
public struct PrivateKey: NISTECPrivateKey {
@@ -71,6 +99,36 @@ extension P256 {
impl = try NISTCurvePrivateKeyImpl(data: rawRepresentation)
}
public init(pemRepresentation: String) throws {
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
switch pem.type {
case "EC PRIVATE KEY":
let parsed = try ASN1.SEC1PrivateKey(asn1Encoded: Array(pem.derBytes))
self = try .init(rawRepresentation: parsed.privateKey)
case "PRIVATE KEY":
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
default:
throw CryptoKitASN1Error.invalidPEMDocument
}
}
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
// We have to try to parse this twice because we have no informaton about what kind of key this is.
// We try with PKCS#8 first, and then fall back to SEC.1.
do {
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
self = try .init(rawRepresentation: key.privateKey.privateKey)
} catch {
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
self = try .init(rawRepresentation: key.privateKey)
}
}
init(impl: NISTCurvePrivateKeyImpl<P256.CurveDetails>) {
self.impl = impl
}
@@ -81,6 +139,20 @@ extension P256 {
public var rawRepresentation: Data { impl.rawRepresentation }
public var x963Representation: Data { impl.x963Representation }
public var derRepresentation: Data {
let pkey = ASN1.PKCS8PrivateKey(algorithm: .ecdsaP256, privateKey: Array(self.rawRepresentation), publicKey: Array(self.publicKey.x963Representation))
var serializer = ASN1.Serializer()
// Serializing these keys can't throw
try! serializer.serialize(pkey)
return Data(serializer.serializedBytes)
}
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PRIVATE KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
}
}
}
@@ -103,6 +175,20 @@ extension P256 {
impl = try NISTCurvePublicKeyImpl(x963Representation: x963Representation)
}
public init(pemRepresentation: String) throws {
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
guard pem.type == "PUBLIC KEY" else {
throw CryptoKitASN1Error.invalidPEMDocument
}
self = try .init(derRepresentation: pem.derBytes)
}
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
let parsed = try ASN1.SubjectPublicKeyInfo(asn1Encoded: bytes)
self = try .init(x963Representation: parsed.key)
}
init(impl: NISTCurvePublicKeyImpl<P256.CurveDetails>) {
self.impl = impl
}
@@ -110,6 +196,20 @@ extension P256 {
public var compactRepresentation: Data? { impl.compactRepresentation }
public var rawRepresentation: Data { impl.rawRepresentation }
public var x963Representation: Data { impl.x963Representation }
public var derRepresentation: Data {
let spki = ASN1.SubjectPublicKeyInfo(algorithmIdentifier: .ecdsaP256, key: Array(self.x963Representation))
var serializer = ASN1.Serializer()
// Serializing these keys can't throw
try! serializer.serialize(spki)
return Data(serializer.serializedBytes)
}
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PUBLIC KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
}
public struct PrivateKey: NISTECPrivateKey {
@@ -127,6 +227,36 @@ extension P256 {
impl = try NISTCurvePrivateKeyImpl(data: rawRepresentation)
}
public init(pemRepresentation: String) throws {
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
switch pem.type {
case "EC PRIVATE KEY":
let parsed = try ASN1.SEC1PrivateKey(asn1Encoded: Array(pem.derBytes))
self = try .init(rawRepresentation: parsed.privateKey)
case "PRIVATE KEY":
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
default:
throw CryptoKitASN1Error.invalidPEMDocument
}
}
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
// We have to try to parse this twice because we have no informaton about what kind of key this is.
// We try with PKCS#8 first, and then fall back to SEC.1.
do {
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
self = try .init(rawRepresentation: key.privateKey.privateKey)
} catch {
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
self = try .init(rawRepresentation: key.privateKey)
}
}
init(impl: NISTCurvePrivateKeyImpl<P256.CurveDetails>) {
self.impl = impl
}
@@ -137,6 +267,20 @@ extension P256 {
public var rawRepresentation: Data { impl.rawRepresentation }
public var x963Representation: Data { impl.x963Representation }
public var derRepresentation: Data {
let pkey = ASN1.PKCS8PrivateKey(algorithm: .ecdsaP256, privateKey: Array(self.rawRepresentation), publicKey: Array(self.publicKey.x963Representation))
var serializer = ASN1.Serializer()
// Serializing these keys can't throw
try! serializer.serialize(pkey)
return Data(serializer.serializedBytes)
}
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PRIVATE KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
}
}
}
@@ -159,6 +303,20 @@ extension P384 {
impl = try NISTCurvePublicKeyImpl(x963Representation: x963Representation)
}
public init(pemRepresentation: String) throws {
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
guard pem.type == "PUBLIC KEY" else {
throw CryptoKitASN1Error.invalidPEMDocument
}
self = try .init(derRepresentation: pem.derBytes)
}
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
let parsed = try ASN1.SubjectPublicKeyInfo(asn1Encoded: bytes)
self = try .init(x963Representation: parsed.key)
}
init(impl: NISTCurvePublicKeyImpl<P384.CurveDetails>) {
self.impl = impl
}
@@ -166,6 +324,20 @@ extension P384 {
public var compactRepresentation: Data? { impl.compactRepresentation }
public var rawRepresentation: Data { impl.rawRepresentation }
public var x963Representation: Data { impl.x963Representation }
public var derRepresentation: Data {
let spki = ASN1.SubjectPublicKeyInfo(algorithmIdentifier: .ecdsaP384, key: Array(self.x963Representation))
var serializer = ASN1.Serializer()
// Serializing these keys can't throw
try! serializer.serialize(spki)
return Data(serializer.serializedBytes)
}
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PUBLIC KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
}
public struct PrivateKey: NISTECPrivateKey {
@@ -183,6 +355,36 @@ extension P384 {
impl = try NISTCurvePrivateKeyImpl(data: rawRepresentation)
}
public init(pemRepresentation: String) throws {
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
switch pem.type {
case "EC PRIVATE KEY":
let parsed = try ASN1.SEC1PrivateKey(asn1Encoded: Array(pem.derBytes))
self = try .init(rawRepresentation: parsed.privateKey)
case "PRIVATE KEY":
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
default:
throw CryptoKitASN1Error.invalidPEMDocument
}
}
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
// We have to try to parse this twice because we have no informaton about what kind of key this is.
// We try with PKCS#8 first, and then fall back to SEC.1.
do {
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
self = try .init(rawRepresentation: key.privateKey.privateKey)
} catch {
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
self = try .init(rawRepresentation: key.privateKey)
}
}
init(impl: NISTCurvePrivateKeyImpl<P384.CurveDetails>) {
self.impl = impl
}
@@ -193,6 +395,20 @@ extension P384 {
public var rawRepresentation: Data { impl.rawRepresentation }
public var x963Representation: Data { impl.x963Representation }
public var derRepresentation: Data {
let pkey = ASN1.PKCS8PrivateKey(algorithm: .ecdsaP384, privateKey: Array(self.rawRepresentation), publicKey: Array(self.publicKey.x963Representation))
var serializer = ASN1.Serializer()
// Serializing these keys can't throw
try! serializer.serialize(pkey)
return Data(serializer.serializedBytes)
}
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PRIVATE KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
}
}
}
@@ -215,6 +431,20 @@ extension P384 {
impl = try NISTCurvePublicKeyImpl(x963Representation: x963Representation)
}
public init(pemRepresentation: String) throws {
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
guard pem.type == "PUBLIC KEY" else {
throw CryptoKitASN1Error.invalidPEMDocument
}
self = try .init(derRepresentation: pem.derBytes)
}
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
let parsed = try ASN1.SubjectPublicKeyInfo(asn1Encoded: bytes)
self = try .init(x963Representation: parsed.key)
}
init(impl: NISTCurvePublicKeyImpl<P384.CurveDetails>) {
self.impl = impl
}
@@ -222,6 +452,20 @@ extension P384 {
public var compactRepresentation: Data? { impl.compactRepresentation }
public var rawRepresentation: Data { impl.rawRepresentation }
public var x963Representation: Data { impl.x963Representation }
public var derRepresentation: Data {
let spki = ASN1.SubjectPublicKeyInfo(algorithmIdentifier: .ecdsaP384, key: Array(self.x963Representation))
var serializer = ASN1.Serializer()
// Serializing these keys can't throw
try! serializer.serialize(spki)
return Data(serializer.serializedBytes)
}
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PUBLIC KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
}
public struct PrivateKey: NISTECPrivateKey {
@@ -239,6 +483,36 @@ extension P384 {
impl = try NISTCurvePrivateKeyImpl(data: rawRepresentation)
}
public init(pemRepresentation: String) throws {
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
switch pem.type {
case "EC PRIVATE KEY":
let parsed = try ASN1.SEC1PrivateKey(asn1Encoded: Array(pem.derBytes))
self = try .init(rawRepresentation: parsed.privateKey)
case "PRIVATE KEY":
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
default:
throw CryptoKitASN1Error.invalidPEMDocument
}
}
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
// We have to try to parse this twice because we have no informaton about what kind of key this is.
// We try with PKCS#8 first, and then fall back to SEC.1.
do {
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
self = try .init(rawRepresentation: key.privateKey.privateKey)
} catch {
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
self = try .init(rawRepresentation: key.privateKey)
}
}
init(impl: NISTCurvePrivateKeyImpl<P384.CurveDetails>) {
self.impl = impl
}
@@ -249,6 +523,20 @@ extension P384 {
public var rawRepresentation: Data { impl.rawRepresentation }
public var x963Representation: Data { impl.x963Representation }
public var derRepresentation: Data {
let pkey = ASN1.PKCS8PrivateKey(algorithm: .ecdsaP384, privateKey: Array(self.rawRepresentation), publicKey: Array(self.publicKey.x963Representation))
var serializer = ASN1.Serializer()
// Serializing these keys can't throw
try! serializer.serialize(pkey)
return Data(serializer.serializedBytes)
}
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PRIVATE KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
}
}
}
@@ -271,6 +559,20 @@ extension P521 {
impl = try NISTCurvePublicKeyImpl(x963Representation: x963Representation)
}
public init(pemRepresentation: String) throws {
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
guard pem.type == "PUBLIC KEY" else {
throw CryptoKitASN1Error.invalidPEMDocument
}
self = try .init(derRepresentation: pem.derBytes)
}
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
let parsed = try ASN1.SubjectPublicKeyInfo(asn1Encoded: bytes)
self = try .init(x963Representation: parsed.key)
}
init(impl: NISTCurvePublicKeyImpl<P521.CurveDetails>) {
self.impl = impl
}
@@ -278,6 +580,20 @@ extension P521 {
public var compactRepresentation: Data? { impl.compactRepresentation }
public var rawRepresentation: Data { impl.rawRepresentation }
public var x963Representation: Data { impl.x963Representation }
public var derRepresentation: Data {
let spki = ASN1.SubjectPublicKeyInfo(algorithmIdentifier: .ecdsaP521, key: Array(self.x963Representation))
var serializer = ASN1.Serializer()
// Serializing these keys can't throw
try! serializer.serialize(spki)
return Data(serializer.serializedBytes)
}
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PUBLIC KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
}
public struct PrivateKey: NISTECPrivateKey {
@@ -295,6 +611,36 @@ extension P521 {
impl = try NISTCurvePrivateKeyImpl(data: rawRepresentation)
}
public init(pemRepresentation: String) throws {
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
switch pem.type {
case "EC PRIVATE KEY":
let parsed = try ASN1.SEC1PrivateKey(asn1Encoded: Array(pem.derBytes))
self = try .init(rawRepresentation: parsed.privateKey)
case "PRIVATE KEY":
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
default:
throw CryptoKitASN1Error.invalidPEMDocument
}
}
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
// We have to try to parse this twice because we have no informaton about what kind of key this is.
// We try with PKCS#8 first, and then fall back to SEC.1.
do {
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
self = try .init(rawRepresentation: key.privateKey.privateKey)
} catch {
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
self = try .init(rawRepresentation: key.privateKey)
}
}
init(impl: NISTCurvePrivateKeyImpl<P521.CurveDetails>) {
self.impl = impl
}
@@ -305,6 +651,20 @@ extension P521 {
public var rawRepresentation: Data { impl.rawRepresentation }
public var x963Representation: Data { impl.x963Representation }
public var derRepresentation: Data {
let pkey = ASN1.PKCS8PrivateKey(algorithm: .ecdsaP521, privateKey: Array(self.rawRepresentation), publicKey: Array(self.publicKey.x963Representation))
var serializer = ASN1.Serializer()
// Serializing these keys can't throw
try! serializer.serialize(pkey)
return Data(serializer.serializedBytes)
}
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PRIVATE KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
}
}
}
@@ -327,6 +687,20 @@ extension P521 {
impl = try NISTCurvePublicKeyImpl(x963Representation: x963Representation)
}
public init(pemRepresentation: String) throws {
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
guard pem.type == "PUBLIC KEY" else {
throw CryptoKitASN1Error.invalidPEMDocument
}
self = try .init(derRepresentation: pem.derBytes)
}
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
let parsed = try ASN1.SubjectPublicKeyInfo(asn1Encoded: bytes)
self = try .init(x963Representation: parsed.key)
}
init(impl: NISTCurvePublicKeyImpl<P521.CurveDetails>) {
self.impl = impl
}
@@ -334,6 +708,20 @@ extension P521 {
public var compactRepresentation: Data? { impl.compactRepresentation }
public var rawRepresentation: Data { impl.rawRepresentation }
public var x963Representation: Data { impl.x963Representation }
public var derRepresentation: Data {
let spki = ASN1.SubjectPublicKeyInfo(algorithmIdentifier: .ecdsaP521, key: Array(self.x963Representation))
var serializer = ASN1.Serializer()
// Serializing these keys can't throw
try! serializer.serialize(spki)
return Data(serializer.serializedBytes)
}
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PUBLIC KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
}
public struct PrivateKey: NISTECPrivateKey {
@@ -351,6 +739,36 @@ extension P521 {
impl = try NISTCurvePrivateKeyImpl(data: rawRepresentation)
}
public init(pemRepresentation: String) throws {
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
switch pem.type {
case "EC PRIVATE KEY":
let parsed = try ASN1.SEC1PrivateKey(asn1Encoded: Array(pem.derBytes))
self = try .init(rawRepresentation: parsed.privateKey)
case "PRIVATE KEY":
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
default:
throw CryptoKitASN1Error.invalidPEMDocument
}
}
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
// We have to try to parse this twice because we have no informaton about what kind of key this is.
// We try with PKCS#8 first, and then fall back to SEC.1.
do {
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
self = try .init(rawRepresentation: key.privateKey.privateKey)
} catch {
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
self = try .init(rawRepresentation: key.privateKey)
}
}
init(impl: NISTCurvePrivateKeyImpl<P521.CurveDetails>) {
self.impl = impl
}
@@ -361,6 +779,20 @@ extension P521 {
public var rawRepresentation: Data { impl.rawRepresentation }
public var x963Representation: Data { impl.x963Representation }
public var derRepresentation: Data {
let pkey = ASN1.PKCS8PrivateKey(algorithm: .ecdsaP521, privateKey: Array(self.rawRepresentation), publicKey: Array(self.publicKey.x963Representation))
var serializer = ASN1.Serializer()
// Serializing these keys can't throw
try! serializer.serialize(pkey)
return Data(serializer.serializedBytes)
}
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PRIVATE KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
}
}
}
+73 -1
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -53,6 +53,20 @@ extension ${CURVE} {
impl = try NISTCurvePublicKeyImpl(x963Representation: x963Representation)
}
public init(pemRepresentation: String) throws {
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
guard pem.type == "PUBLIC KEY" else {
throw CryptoKitASN1Error.invalidPEMDocument
}
self = try .init(derRepresentation: pem.derBytes)
}
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
let parsed = try ASN1.SubjectPublicKeyInfo(asn1Encoded: bytes)
self = try .init(x963Representation: parsed.key)
}
init(impl: NISTCurvePublicKeyImpl<${CURVE}.CurveDetails>) {
self.impl = impl
}
@@ -60,6 +74,20 @@ extension ${CURVE} {
public var compactRepresentation: Data? { impl.compactRepresentation }
public var rawRepresentation: Data { impl.rawRepresentation }
public var x963Representation: Data { impl.x963Representation }
public var derRepresentation: Data {
let spki = ASN1.SubjectPublicKeyInfo(algorithmIdentifier: .ecdsa${CURVE}, key: Array(self.x963Representation))
var serializer = ASN1.Serializer()
// Serializing these keys can't throw
try! serializer.serialize(spki)
return Data(serializer.serializedBytes)
}
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PUBLIC KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
}
public struct PrivateKey: NISTECPrivateKey {
@@ -77,6 +105,36 @@ extension ${CURVE} {
impl = try NISTCurvePrivateKeyImpl(data: rawRepresentation)
}
public init(pemRepresentation: String) throws {
let pem = try ASN1.PEMDocument(pemString: pemRepresentation)
switch pem.type {
case "EC PRIVATE KEY":
let parsed = try ASN1.SEC1PrivateKey(asn1Encoded: Array(pem.derBytes))
self = try .init(rawRepresentation: parsed.privateKey)
case "PRIVATE KEY":
let parsed = try ASN1.PKCS8PrivateKey(asn1Encoded: Array(pem.derBytes))
self = try .init(rawRepresentation: parsed.privateKey.privateKey)
default:
throw CryptoKitASN1Error.invalidPEMDocument
}
}
public init<Bytes: RandomAccessCollection>(derRepresentation: Bytes) throws where Bytes.Element == UInt8 {
let bytes = Array(derRepresentation)
// We have to try to parse this twice because we have no informaton about what kind of key this is.
// We try with PKCS#8 first, and then fall back to SEC.1.
do {
let key = try ASN1.PKCS8PrivateKey(asn1Encoded: bytes)
self = try .init(rawRepresentation: key.privateKey.privateKey)
} catch {
let key = try ASN1.SEC1PrivateKey(asn1Encoded: bytes)
self = try .init(rawRepresentation: key.privateKey)
}
}
init(impl: NISTCurvePrivateKeyImpl<${CURVE}.CurveDetails>) {
self.impl = impl
}
@@ -87,6 +145,20 @@ extension ${CURVE} {
public var rawRepresentation: Data { impl.rawRepresentation }
public var x963Representation: Data { impl.x963Representation }
public var derRepresentation: Data {
let pkey = ASN1.PKCS8PrivateKey(algorithm: .ecdsa${CURVE}, privateKey: Array(self.rawRepresentation), publicKey: Array(self.publicKey.x963Representation))
var serializer = ASN1.Serializer()
// Serializing these keys can't throw
try! serializer.serialize(pkey)
return Data(serializer.serializedBytes)
}
public var pemRepresentation: String {
let pemDocument = ASN1.PEMDocument(type: "PRIVATE KEY", derBytes: self.derRepresentation)
return pemDocument.pemString
}
}
}
}
+87 -23
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -16,52 +16,116 @@
#else
import Foundation
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
struct HKDF<H: HashFunction> {
/// Computes an HKDF using the parameterized Hash Function.
/// The HMAC-based Extract-and-Expand Key Derivation Function (IETF RFC 5869)
/// https://tools.ietf.org/html/rfc5869
public struct HKDF<H: HashFunction> {
/// Derives a symmetric key using the HKDF algorithm.
///
/// - Parameters:
/// - inputKeyMaterial: Input key material.
/// - salt: A non-secret random value.
/// - info: Context and application specific information.
/// - outputByteCount: The desired number of output bytes.
/// - Returns: Returns the derived key.
static func deriveKey<IKM: DataProtocol, Salt: DataProtocol, Info: DataProtocol>(inputKeyMaterial: IKM, salt: Salt, info: Info, outputByteCount: Int) -> SymmetricKey {
return expand(PRK: extract(salt: salt, ikm: inputKeyMaterial), info: info, L: outputByteCount)
/// - Returns: The derived key
public static func deriveKey<Salt: DataProtocol, Info: DataProtocol>(inputKeyMaterial: SymmetricKey,
salt: Salt,
info: Info,
outputByteCount: Int) -> SymmetricKey {
return expand(pseudoRandomKey: extract(inputKeyMaterial: inputKeyMaterial, salt: salt), info: info, outputByteCount: outputByteCount)
}
static func extract<S: DataProtocol, IKM: DataProtocol>(salt: S, ikm: IKM) -> HashedAuthenticationCode<H> {
/// Derives a symmetric key using the HKDF algorithm.
///
/// - Parameters:
/// - inputKeyMaterial: Input key material.
/// - info: Context and application specific information.
/// - outputByteCount: The desired number of output bytes.
/// - Returns: The derived key
public static func deriveKey<Info: DataProtocol>(inputKeyMaterial: SymmetricKey,
info: Info,
outputByteCount: Int) -> SymmetricKey {
return deriveKey(inputKeyMaterial: inputKeyMaterial, salt: [UInt8](), info: info, outputByteCount: outputByteCount)
}
/// Derives a symmetric key using the HKDF algorithm.
///
/// - Parameters:
/// - inputKeyMaterial: Input key material.
/// - salt: A non-secret random value.
/// - outputByteCount: The desired number of output bytes.
/// - Returns: The derived key
public static func deriveKey<Salt: DataProtocol>(inputKeyMaterial: SymmetricKey,
salt: Salt,
outputByteCount: Int) -> SymmetricKey {
return deriveKey(inputKeyMaterial: inputKeyMaterial, salt: salt, info: [UInt8](), outputByteCount: outputByteCount)
}
/// Derives a symmetric key using the HKDF algorithm.
///
/// - Parameters:
/// - inputKeyMaterial: Input key material.
/// - outputByteCount: The desired number of output bytes.
/// - Returns: The derived key
public static func deriveKey(inputKeyMaterial: SymmetricKey,
outputByteCount: Int) -> SymmetricKey {
return deriveKey(inputKeyMaterial: inputKeyMaterial, salt: [UInt8](), info: [UInt8](), outputByteCount: outputByteCount)
}
/// The extract function as defined by specification.
/// The goal of the extract function is to "concentrate" the possibly dispersed entropy of the input keying material into a short, but cryptographically strong, pseudorandom key.
/// Unless required by a specification, it is recommended to use the one-shot "deriveKey" API instead that performs both extraction and expansion.
///
/// - Parameters:
/// - inputKeyMaterial: Input key material.
/// - salt: A non-secret random value.
/// - Returns: The resulting secret
public static func extract<Salt: DataProtocol>(inputKeyMaterial: SymmetricKey, salt: Salt?) -> HashedAuthenticationCode<H> {
let key: SymmetricKey
if salt.regions.count != 1 {
let contiguousBytes = Array(salt)
key = SymmetricKey(data: contiguousBytes)
if let salt = salt {
if salt.regions.count != 1 {
let contiguousBytes = Array(salt)
key = SymmetricKey(data: contiguousBytes)
} else {
key = SymmetricKey(data: salt.regions.first!)
}
} else {
key = SymmetricKey(data: salt.regions.first!)
key = SymmetricKey(data: [UInt8]())
}
return HMAC<H>.authenticationCode(for: ikm, using: key)
return inputKeyMaterial.withUnsafeBytes { ikmBytes in
return HMAC<H>.authenticationCode(for: ikmBytes, using: key)
}
}
static func expand<Info: DataProtocol>(PRK: HashedAuthenticationCode<H>, info: Info?, L: Int) -> SymmetricKey {
let iterations = UInt8(ceil((Float(L) / Float(H.Digest.byteCount))))
/// The expand function as defined by the specification.
/// The goal of the expand function is to expand the pseudorandom key to the desired length.
/// Unless required by a specification, it is recommended to use the one-shot "deriveKey" API instead that performs both extraction and expansion.
///
/// - Parameters:
/// - pseudoRandomKey: The extracted pseudorandom key. This value is expected to be a high-entropy secret. In the HKDF specification it is obtained from the input key material and the salt using the extract method.
/// - info: Context and application specific information.
/// - outputByteCount: The desired number of output bytes.
/// - Returns: The expanded key bytes.
public static func expand<PRK: ContiguousBytes, Info: DataProtocol>(pseudoRandomKey prk: PRK, info: Info?, outputByteCount: Int) -> SymmetricKey {
let iterations: UInt8 = UInt8(ceil((Float(outputByteCount) / Float(H.Digest.byteCount))))
var output = SecureBytes()
let key = SymmetricKey(data: Data(PRK.digest))
let key = SymmetricKey(data: prk)
var TMinusOne = Data()
for i in 1...iterations {
var hmac = HMAC<H>(key: key)
hmac.update(data: TMinusOne)
if let infoData = info {
hmac.update(data: infoData)
if let info = info {
hmac.update(data: info)
}
withUnsafeBytes(of: i) { counter in
hmac.update(bufferPointer: counter)
}
TMinusOne = Data(hmac.finalize())
output.append(TMinusOne)
}
let expanded = SymmetricKey(data: output.prefix(L))
return expanded
return SymmetricKey(data: output.prefix(outputByteCount))
}
}
#endif // Linux or !SwiftPM
@@ -22,7 +22,7 @@ import Foundation
extension Curve25519.Signing {
@usableFromInline
struct OpenSSLCurve25519PrivateKeyImpl {
/* private but @usableFromInline */ @usableFromInline var _privateKey: SecureBytes
/* private but @usableFromInline */ var _privateKey: SecureBytes
/* private but @usableFromInline */ @usableFromInline var _publicKey: [UInt8]
@usableFromInline
@@ -46,7 +46,6 @@ extension Curve25519.Signing {
return OpenSSLCurve25519PublicKeyImpl(self._publicKey)
}
@usableFromInline
var key: SecureBytes {
return self._privateKey
}
@@ -163,7 +163,16 @@ class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
}
init<Bytes: ContiguousBytes>(x963Representation bytes: Bytes) throws {
self.key = try Curve.group.makeUnsafeOwnedECKey()
// Before we do anything, we validate that the x963 representation has the right number of bytes.
// This is because BoringSSL will quietly accept shorter byte counts, though it will reject longer ones.
// This brings our behaviour into line with CryptoKit
let group = Curve.group
let length = bytes.withUnsafeBytes { $0.count }
guard length == (group.coordinateByteCount * 3) + 1 else {
throw CryptoKitError.incorrectParameterSize
}
self.key = try group.makeUnsafeOwnedECKey()
// First, try to grab the numbers.
var (x, y, k) = try bytes.readx963PrivateNumbers()
@@ -176,6 +185,15 @@ class BoringSSLECPrivateKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
init<Bytes: ContiguousBytes>(rawRepresentation bytes: Bytes) throws {
let group = Curve.group
// Before we do anything, we validate that the raw representation has the right number of bytes.
// This is because BoringSSL will quietly accept shorter byte counts, though it will reject longer ones.
// This brings our behaviour into line with CryptoKit
let length = bytes.withUnsafeBytes { $0.count }
guard length == group.coordinateByteCount else {
throw CryptoKitError.incorrectParameterSize
}
self.key = try group.makeUnsafeOwnedECKey()
// The raw representation is just the bytes that make up k.
@@ -306,6 +324,15 @@ class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
init<Bytes: ContiguousBytes>(compactRepresentation bytes: Bytes) throws {
let group = Curve.group
// Before we do anything, we validate that the compact representation has the right number of bytes.
// This is because BoringSSL will quietly accept shorter byte counts, though it will reject longer ones.
// This brings our behaviour into line with CryptoKit
let length = bytes.withUnsafeBytes { $0.count }
guard length == group.coordinateByteCount else {
throw CryptoKitError.incorrectParameterSize
}
self.key = try group.makeUnsafeOwnedECKey()
// The compact representation is simply the X coordinate: deserializing then requires us to do a little math,
@@ -331,13 +358,32 @@ class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
}
init<Bytes: ContiguousBytes>(x963Representation bytes: Bytes) throws {
self.key = try Curve.group.makeUnsafeOwnedECKey()
// Before we do anything, we validate that the x963 representation has the right number of bytes.
// This is because BoringSSL will quietly accept shorter byte counts, though it will reject longer ones.
// This brings our behaviour into line with CryptoKit
let group = Curve.group
let length = bytes.withUnsafeBytes { $0.count }
guard length == (group.coordinateByteCount * 2) + 1 else {
throw CryptoKitError.incorrectParameterSize
}
self.key = try group.makeUnsafeOwnedECKey()
var (x, y) = try bytes.readx963PublicNumbers()
try self.setPublicKey(x: &x, y: &y)
}
init<Bytes: ContiguousBytes>(rawRepresentation bytes: Bytes) throws {
self.key = try Curve.group.makeUnsafeOwnedECKey()
let group = Curve.group
// Before we do anything, we validate that the raw representation has the right number of bytes.
// This is because BoringSSL will quietly accept shorter byte counts, though it will reject longer ones.
// This brings our behaviour into line with CryptoKit
let length = bytes.withUnsafeBytes { $0.count }
guard length == group.coordinateByteCount * 2 else {
throw CryptoKitError.incorrectParameterSize
}
self.key = try group.makeUnsafeOwnedECKey()
// The raw representation is identical to the x963 representation, without the leading 0x4.
var (x, y): (ArbitraryPrecisionInteger, ArbitraryPrecisionInteger) = try bytes.withUnsafeBytes { bytesPtr in
@@ -51,7 +51,6 @@ extension Curve25519.KeyAgreement {
@usableFromInline
struct OpenSSLCurve25519PrivateKeyImpl {
@usableFromInline
var key: SecureBytes
@usableFromInline
@@ -69,13 +68,19 @@ extension Curve25519.KeyAgreement {
privateKeySize = Curve25519.KeyAgreement.keySizeBytes // We always use the whole thing.
}
self.publicKey = .init(publicKey)
// BoringSSL performs an "anti-mask" of the private key. That's well-motivated, but corecrypto doesn't
// and we'd like to behave the same way. Undo the private key anti-mask.
let firstByteIndex = self.key.startIndex
let lastByteIndex = self.key.index(before: self.key.endIndex)
self.key[firstByteIndex] &= 248
self.key[lastByteIndex] &= 127
self.key[lastByteIndex] |= 64
}
init<D: ContiguousBytes>(rawRepresentation: D) throws {
let publicBytes: [UInt8] = try rawRepresentation.withUnsafeBytes { privatePointer in
guard privatePointer.count == Curve25519.KeyAgreement.keySizeBytes else {
throw CryptoKitError.incorrectKeySize
}
try OpenSSLCurve25519PrivateKeyImpl.validateX25519PrivateKeyData(rawRepresentation: privatePointer)
return Array(unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes) { publicKeyBytes, publicKeySize in
precondition(publicKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
@@ -118,6 +123,14 @@ extension Curve25519.KeyAgreement {
var rawRepresentation: Data {
return Data(self.key)
}
/// Validates whether the passed x25519 key representation is valid.
/// - Parameter rawRepresentation: The provided key representation. Expected to be a valid 32-bytes private key.
static func validateX25519PrivateKeyData(rawRepresentation: UnsafeRawBufferPointer) throws {
guard rawRepresentation.count == 32 else {
throw CryptoKitError.incorrectKeySize
}
}
}
}
#endif // (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
+1 -2
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -15,6 +15,5 @@
@_exported import CryptoKit
#else
/// The Curve25519 Elliptic Curve.
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public enum Curve25519 {}
#endif // Linux or !SwiftPM
+1 -1
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
+1 -4
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -46,14 +46,11 @@ protocol NISTECPrivateKey: ECPrivateKey where PublicKey: NISTECPublicKey {
}
/// The NIST P-256 Elliptic Curve.
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public enum P256 { }
/// The NIST P-384 Elliptic Curve.
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public enum P384 { }
/// The NIST P-521 Elliptic Curve.
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public enum P521 { }
#endif // Linux or !SwiftPM
+1 -1
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -17,7 +17,6 @@
import Foundation
/// The size of a symmetric key
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public struct SymmetricKeySize {
public let bitCount: Int
@@ -47,7 +46,6 @@ public struct SymmetricKeySize {
}
/// A symmetric key for use with software implementations of cryptographic algorithms.
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public struct SymmetricKey: ContiguousBytes {
let sb: SecureBytes
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -18,7 +18,6 @@ import Foundation
/// Performs HMAC - Keyed-Hashing for Message Authentication
/// Reference: https://tools.ietf.org/html/rfc2104
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public struct HMAC<H: HashFunction>: MACAlgorithm {
public typealias Key = SymmetricKey
public typealias MAC = HashedAuthenticationCode<H>
@@ -44,7 +43,7 @@ public struct HMAC<H: HashFunction>: MACAlgorithm {
if key.byteCount == H.blockByteCount {
K = key
} else if (key.byteCount > H.blockByteCount) {
} else if key.byteCount > H.blockByteCount {
var array = Array(repeating: UInt8(0), count: H.blockByteCount)
K = key.withUnsafeBytes { (keyBytes) in
@@ -108,7 +107,6 @@ public struct HMAC<H: HashFunction>: MACAlgorithm {
/// - authenticatedData: Authenticated Data
/// - key: The key to authenticate the data with
/// - Returns: Returns true if the MAC is valid. False otherwise.
@available(iOS 13.2, macOS 10.15, watchOS 6.1, tvOS 13.2, macCatalyst 13.2, *)
public static func isValidAuthenticationCode<C: ContiguousBytes, D: DataProtocol>(_ authenticationCode: C,
authenticating authenticatedData: D,
using key: SymmetricKey) -> Bool {
@@ -162,7 +160,6 @@ public struct HMAC<H: HashFunction>: MACAlgorithm {
}
/// A structure that contains a Message Authentication Code that was computed from a Hash Function using HMAC.
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *)
public struct HashedAuthenticationCode<H: HashFunction>: MessageAuthenticationCode {
let digest: H.Digest
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff. Show more