2 * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright 2017 Ribose Inc. All Rights Reserved.
4 * Ported from Ribose contributions from Botan.
6 * Licensed under the OpenSSL license (the "License"). You may not use
7 * this file except in compliance with the License. You can obtain a copy
8 * in the file LICENSE in the source distribution or at
9 * https://www.openssl.org/source/license.html
12 #include "internal/sm2.h"
13 #include "internal/sm2err.h"
14 #include <openssl/err.h>
15 #include <openssl/evp.h>
16 #include <openssl/bn.h>
18 #include "internal/numbers.h"
20 int sm2_compute_userid_digest(uint8_t *out,
26 const EC_GROUP *group = EC_KEY_get0_group(key);
28 EVP_MD_CTX *hash = NULL;
42 hash = EVP_MD_CTX_new();
44 if (hash == NULL || ctx == NULL) {
45 SM2err(SM2_F_SM2_COMPUTE_USERID_DIGEST, ERR_R_MALLOC_FAILURE);
58 SM2err(SM2_F_SM2_COMPUTE_USERID_DIGEST, ERR_R_MALLOC_FAILURE);
62 if (!EVP_DigestInit(hash, digest)) {
63 SM2err(SM2_F_SM2_COMPUTE_USERID_DIGEST, ERR_R_EVP_LIB);
67 /* ZA = H256(ENTLA || IDA || a || b || xG || yG || xA || yA) */
69 uid_len = strlen(user_id);
70 if (uid_len >= (UINT16_MAX / 8)) {
72 SM2err(SM2_F_SM2_COMPUTE_USERID_DIGEST, SM2_R_USER_ID_TOO_LARGE);
76 entla = (uint16_t)(8 * uid_len);
79 if (!EVP_DigestUpdate(hash, &e_byte, 1)) {
80 SM2err(SM2_F_SM2_COMPUTE_USERID_DIGEST, ERR_R_EVP_LIB);
83 e_byte = entla & 0xFF;
84 if (!EVP_DigestUpdate(hash, &e_byte, 1)
85 || !EVP_DigestUpdate(hash, user_id, uid_len)) {
86 SM2err(SM2_F_SM2_COMPUTE_USERID_DIGEST, ERR_R_EVP_LIB);
90 if (!EC_GROUP_get_curve(group, p, a, b, ctx)) {
91 SM2err(SM2_F_SM2_COMPUTE_USERID_DIGEST, ERR_R_EC_LIB);
95 p_bytes = BN_num_bytes(p);
96 buf = OPENSSL_zalloc(p_bytes);
98 SM2err(SM2_F_SM2_COMPUTE_USERID_DIGEST, ERR_R_MALLOC_FAILURE);
102 if (BN_bn2binpad(a, buf, p_bytes) < 0
103 || !EVP_DigestUpdate(hash, buf, p_bytes)
104 || BN_bn2binpad(b, buf, p_bytes) < 0
105 || !EVP_DigestUpdate(hash, buf, p_bytes)
106 || !EC_POINT_get_affine_coordinates(group,
107 EC_GROUP_get0_generator(group),
109 || BN_bn2binpad(xG, buf, p_bytes) < 0
110 || !EVP_DigestUpdate(hash, buf, p_bytes)
111 || BN_bn2binpad(yG, buf, p_bytes) < 0
112 || !EVP_DigestUpdate(hash, buf, p_bytes)
113 || !EC_POINT_get_affine_coordinates(group,
114 EC_KEY_get0_public_key(key),
116 || BN_bn2binpad(xA, buf, p_bytes) < 0
117 || !EVP_DigestUpdate(hash, buf, p_bytes)
118 || BN_bn2binpad(yA, buf, p_bytes) < 0
119 || !EVP_DigestUpdate(hash, buf, p_bytes)
120 || !EVP_DigestFinal(hash, out, NULL)) {
121 SM2err(SM2_F_SM2_COMPUTE_USERID_DIGEST, ERR_R_INTERNAL_ERROR);
130 EVP_MD_CTX_free(hash);