Use SDF as the crypto provider in SM2/3/4 CTX API

cmake .. -DENABLE_CRYPTO_SDF=ON
This commit is contained in:
Zhi Guan
2024-05-08 17:04:45 +08:00
parent 2000655392
commit 3d491c9e14
8 changed files with 2286 additions and 5 deletions

View File

@@ -538,6 +538,26 @@ if (ENABLE_SKF)
endif()
option(ENABLE_CRYPTO_SDF "Enable SDF as default crypto implementation" OFF)
if (ENABLE_CRYPTO_SDF)
message(STATUS "ENABLE_CRYPTO_SDF is ON")
add_definitions(-DENABLE_CRYPTO_SDF)
list(FIND src src/sm3_digest.c sm3_digest_index)
list(REMOVE_AT src ${sm3_digest_index})
list(INSERT src ${sm3_digest_index} src/sdf/sdf_sm3.c)
list(FIND src src/sm4_cbc.c index)
list(REMOVE_AT src ${index})
list(INSERT src ${index} src/sdf/sdf_sm4_cbc.c)
list(FIND src src/sm2_sign.c index)
list(REMOVE_AT src ${index})
list(INSERT src ${index} src/sdf/sdf_sm2_sign.c)
list(FIND src src/sm2_enc.c index)
list(REMOVE_AT src ${index})
list(INSERT src ${index} src/sdf/sdf_sm2_enc.c)
endif()
option(ENABLE_SDF "Enable SDF module" OFF)
if (ENABLE_SDF)

View File

@@ -34,6 +34,27 @@ typedef struct {
int index;
} SDF_KEY;
typedef struct {
void *hSession;
} SDF_SM3_CTX;
typedef struct {
void *hSession;
void *hKey;
} SDF_SM4_KEY;
typedef struct {
uint32_t index;
uint8_t passlen;
unsigned char pass[26 + 1];
} SDF_ENC_PRIVATE_KEY;
typedef struct {
uint32_t index;
uint8_t passlen;
unsigned char pass[26 + 1];
} SDF_PRIVATE_KEY;
int sdf_load_library(const char *so_path, const char *vendor);
int sdf_open_device(SDF_DEVICE *dev);

View File

@@ -75,7 +75,6 @@ typedef struct {
union {
SM3_CTX sm3_ctx;
SM3_HMAC_CTX hmac_ctx;
void *handle;
};
int state;
} SM3_DIGEST_CTX;

View File

@@ -51,10 +51,7 @@ void sm4_ctr32_encrypt(const SM4_KEY *key, uint8_t ctr[16], const uint8_t *in, s
typedef struct {
union {
SM4_KEY sm4_key;
void *handle;
};
SM4_KEY sm4_key;
uint8_t iv[SM4_BLOCK_SIZE];
uint8_t block[SM4_BLOCK_SIZE];
size_t block_nbytes;

893
src/sdf/sdf_sm2_enc.c Normal file
View File

@@ -0,0 +1,893 @@
/*
* Copyright 2014-2024 The GmSSL Project. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <gmssl/sdf.h>
#include <gmssl/sm2.h>
#include <gmssl/sm3.h>
#include <gmssl/mem.h>
#include <gmssl/asn1.h>
#include <gmssl/error.h>
#include "sdf.h"
extern void *globalDeviceHandle;
static const uint8_t zeros[ECCref_MAX_LEN - 32] = {0};
int sm2_do_encrypt(const SM2_KEY *key, const uint8_t *in, size_t inlen, SM2_CIPHERTEXT *out)
{
void *hSession = NULL;
SM2_POINT point;
ECCrefPublicKey eccPublicKey;
ECCCipher eccCipher;
int ret;
ret = SDF_OpenSession(globalDeviceHandle, &hSession);
if (ret != SDR_OK) {
error_print();
return -1;
}
if (inlen > SM2_MAX_PLAINTEXT_SIZE) {
error_print();
return -1;
}
// SM2_KEY to ECCrefPublicKey
sm2_z256_point_to_bytes(&key->public_key, (uint8_t *)&point);
eccPublicKey.bits = 256;
memset(eccPublicKey.x, 0, sizeof(zeros));
memcpy(eccPublicKey.x + sizeof(zeros), point.x, 32);
memset(eccPublicKey.y, 0, sizeof(zeros));
memcpy(eccPublicKey.y + sizeof(zeros), point.y, 32);
// encrypt
ret = SDF_ExternalEncrypt_ECC(hSession, SGD_SM2_3, &eccPublicKey, (unsigned char *)in, (unsigned int)inlen, &eccCipher);
if (ret != SDR_OK) {
error_print();
return -1;
}
// ECCCipher to SM2_CIPHERTEXT
if (memcmp(eccCipher.x, zeros, sizeof(zeros)) != 0
|| memcmp(eccCipher.y, zeros, sizeof(zeros)) != 0) {
error_print();
return -1;
}
memcpy(out->point.x, eccCipher.x + sizeof(zeros), 32);
memcpy(out->point.y, eccCipher.y + sizeof(zeros), 32);
memcpy(out->hash, eccCipher.M, 32);
memcpy(out->ciphertext, eccCipher.C, eccCipher.L);
out->ciphertext_size = eccCipher.L;
ret = SDF_CloseSession(hSession);
if (ret != SDR_OK) {
error_print();
return -1;
}
return 1;
}
int sdf_load_sm2_enc_key(SM2_KEY *key, unsigned int uiISKIndex, const char *pass)
{
SDF_PRIVATE_KEY *sk = (SDF_PRIVATE_KEY *)&key->private_key;
void *hSession = NULL;
ECCrefPublicKey eccPublicKey;
SM2_POINT point;
int ret;
ret = SDF_OpenSession(globalDeviceHandle, &hSession);
if (ret != SDR_OK) {
error_print();
return -1;
}
ret = SDF_GetPrivateKeyAccessRight(hSession, uiISKIndex, (unsigned char *)pass, (unsigned int)strlen(pass));
if (ret != SDR_OK) {
error_print();
return -1;
}
ret = SDF_ExportEncPublicKey_ECC(hSession, uiISKIndex, &eccPublicKey);
if (ret != SDR_OK) {
error_print();
return -1;
}
// check bits and endian of ECCrefPublicKey
if (eccPublicKey.bits != 256) {
error_print();
return -1;
}
if (memcmp(eccPublicKey.x, zeros, sizeof(zeros)) != 0
|| memcmp(eccPublicKey.y, zeros, sizeof(zeros)) != 0) {
error_print();
return -1;
}
// set SM2_KEY.public_key
memcpy(point.x, eccPublicKey.x + sizeof(zeros), 32);
memcpy(point.y, eccPublicKey.y + sizeof(zeros), 32);
if (sm2_z256_point_from_bytes(&key->public_key, (uint8_t *)&point) != 1) {
error_print();
return -1;
}
// save index and pass in SM2_KEY.private_key
sk->index = uiISKIndex;
if (strlen(pass) > 26) {
error_print();
return -1;
}
memset(sk->pass, 0, 27);
memcpy(sk->pass, pass, strlen(pass));
return 1;
}
int sm2_do_decrypt(const SM2_KEY *key, const SM2_CIPHERTEXT *in, uint8_t *out, size_t *outlen)
{
SDF_PRIVATE_KEY *sk = (SDF_PRIVATE_KEY *)&key->private_key;
void *hSession = NULL;
ECCCipher eccCipher;
unsigned int uiLength;
int ret;
ret = SDF_OpenSession(globalDeviceHandle, &hSession);
if (ret != SDR_OK) {
error_print();
return -1;
}
ret = SDF_GetPrivateKeyAccessRight(hSession, sk->index, sk->pass, sk->passlen);
if (ret != SDR_OK) {
error_print();
return -1;
}
// SM2_CIPHERTEXT to ECCCipher
memset(eccCipher.x, 0, sizeof(zeros));
memcpy(eccCipher.x + sizeof(zeros), in->point.x, 32);
memset(eccCipher.y, 0, sizeof(zeros));
memcpy(eccCipher.y + sizeof(zeros), in->point.y, 32);
memcpy(eccCipher.M, in->hash, 32);
memcpy(eccCipher.C, in->ciphertext, in->ciphertext_size);
eccCipher.L = (unsigned int)in->ciphertext_size;
// decrypt
ret = SDF_InternalDecrypt_ECC(hSession, sk->index, SGD_SM2_3, &eccCipher, out, &uiLength);
if (ret != SDR_OK) {
error_print();
return -1;
}
SDF_CloseSession(hSession);
*outlen = uiLength;
return 1;
}
// copy from src/sm2_enc.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <gmssl/sm2.h>
#include <gmssl/sm3.h>
#include <gmssl/mem.h>
#include <gmssl/asn1.h>
#include <gmssl/error.h>
#include <gmssl/endian.h>
static int all_zero(const uint8_t *buf, size_t len)
{
size_t i;
for (i = 0; i < len; i++) {
if (buf[i]) {
return 0;
}
}
return 1;
}
int sm2_kdf(const uint8_t *in, size_t inlen, size_t outlen, uint8_t *out)
{
SM3_CTX ctx;
uint8_t counter_be[4];
uint8_t dgst[SM3_DIGEST_SIZE];
uint32_t counter = 1;
size_t len;
while (outlen) {
PUTU32(counter_be, counter);
counter++;
sm3_init(&ctx);
sm3_update(&ctx, in, inlen);
sm3_update(&ctx, counter_be, sizeof(counter_be));
sm3_finish(&ctx, dgst);
len = outlen < SM3_DIGEST_SIZE ? outlen : SM3_DIGEST_SIZE;
memcpy(out, dgst, len);
out += len;
outlen -= len;
}
memset(&ctx, 0, sizeof(SM3_CTX));
memset(dgst, 0, sizeof(dgst));
return 1;
}
// use Montgomery's Trick to inverse Z coordinates on multiple (x1, y1) = [k]G
int sm2_encrypt_pre_compute(SM2_ENC_PRE_COMP pre_comp[SM2_ENC_PRE_COMP_NUM])
{
SM2_Z256_POINT P[SM2_ENC_PRE_COMP_NUM];
sm2_z256_t f[SM2_ENC_PRE_COMP_NUM];
sm2_z256_t g[SM2_ENC_PRE_COMP_NUM];
int i;
for (i = 0; i < SM2_ENC_PRE_COMP_NUM; i++) {
// rand k in [1, n - 1]
do {
if (sm2_z256_rand_range(pre_comp[i].k, sm2_z256_order()) != 1) {
error_print();
return -1;
}
} while (sm2_z256_is_zero(pre_comp[i].k));
// (x1, y1) = kG
sm2_z256_point_mul_generator(&P[i], pre_comp[i].k);
}
// f[0] = Z[0]
// f[1] = Z[0] * Z[1]
// ...
// f[31] = Z[0] * Z[1] * ... * Z[31]
sm2_z256_copy(f[0], P[0].Z);
for (i = 1; i < SM2_ENC_PRE_COMP_NUM; i++) {
sm2_z256_modp_mont_mul(f[i], f[i - 1], P[i].Z);
}
// f[31]^-1 = (Z[0] * ... * Z[31])^-1
sm2_z256_modp_mont_inv(f[SM2_ENC_PRE_COMP_NUM - 1], f[SM2_ENC_PRE_COMP_NUM - 1]);
// g[31] = Z[31]
// g[30] = Z[30] * Z[31]
// ...
// g[1] = Z[1] * Z[2] * ... * Z[31]
//
sm2_z256_copy(g[SM2_ENC_PRE_COMP_NUM - 1], P[SM2_ENC_PRE_COMP_NUM - 1].Z);
for (i = SM2_ENC_PRE_COMP_NUM - 2; i >= 1; i--) {
sm2_z256_modp_mont_mul(g[i], g[i + 1], P[i].Z);
}
// Z[0]^-1 = g[1] * f[31]^-1
// Z[1]^-1 = g[2] * f[0] * f[31]^-1
// Z[2]^-1 = g[3] * f[1] * f[31]^-1
// ...
// Z[30]^-1 = g[31] * f[29] * f[31]^-1
// Z[31]^-1 = f[30] * f[31]^-1
sm2_z256_modp_mont_mul(P[0].Z, g[1], f[SM2_ENC_PRE_COMP_NUM - 1]);
for (i = 1; i < SM2_ENC_PRE_COMP_NUM - 1; i++) {
sm2_z256_modp_mont_mul(P[i].Z, g[i + 1], f[i - 1]);
sm2_z256_modp_mont_mul(P[i].Z, P[i].Z, f[SM2_ENC_PRE_COMP_NUM - 1]);
}
sm2_z256_modp_mont_mul(P[SM2_ENC_PRE_COMP_NUM - 1].Z,
f[SM2_ENC_PRE_COMP_NUM - 2], f[SM2_ENC_PRE_COMP_NUM - 1]);
// y[i] = Y[i] * Z[i]^-3 (mod n)
// x[i] = X[i] * Z[i]^-2 (mod n)
for (i = 0; i < SM2_ENC_PRE_COMP_NUM; i++) {
sm2_z256_modp_mont_mul(P[i].Y, P[i].Y, P[i].Z);
sm2_z256_modp_mont_sqr(P[i].Z, P[i].Z);
sm2_z256_modp_mont_mul(P[i].Y, P[i].Y, P[i].Z);
sm2_z256_modp_mont_mul(P[i].X, P[i].X, P[i].Z);
sm2_z256_modp_from_mont(P[i].X, P[i].X);
sm2_z256_modp_from_mont(P[i].Y, P[i].Y);
sm2_z256_to_bytes(P[i].X, pre_comp[i].C1.x);
sm2_z256_to_bytes(P[i].Y, pre_comp[i].C1.y);
}
return 1;
}
int sm2_do_encrypt_ex(const SM2_KEY *key, const SM2_ENC_PRE_COMP *pre_comp,
const uint8_t *in, size_t inlen, SM2_CIPHERTEXT *out)
{
SM2_Z256_POINT kP;
uint8_t x2y2[64];
SM3_CTX sm3_ctx;
// output C1
out->point = pre_comp->C1;
// k * P = (x2, y2)
sm2_z256_point_mul(&kP, pre_comp->k, &key->public_key);
sm2_z256_point_to_bytes(&kP, x2y2);
// t = KDF(x2 || y2, inlen)
sm2_kdf(x2y2, 64, inlen, out->ciphertext);
// if t is all zero, return 0, caller should change pre_comp and retry
if (all_zero(out->ciphertext, inlen)) {
return 0;
}
// output C2 = M xor t
gmssl_memxor(out->ciphertext, out->ciphertext, in, inlen);
out->ciphertext_size = (uint32_t)inlen;
// output C3 = Hash(x2 || m || y2)
sm3_init(&sm3_ctx);
sm3_update(&sm3_ctx, x2y2, 32);
sm3_update(&sm3_ctx, in, inlen);
sm3_update(&sm3_ctx, x2y2 + 32, 32);
sm3_finish(&sm3_ctx, out->hash);
gmssl_secure_clear(&kP, sizeof(SM2_Z256_POINT));
gmssl_secure_clear(x2y2, sizeof(x2y2));
return 1;
}
// key->public_key will not be point_at_infinity when decoded from_bytes/octets/der
/*
int sm2_do_encrypt(const SM2_KEY *key, const uint8_t *in, size_t inlen, SM2_CIPHERTEXT *out)
{
sm2_z256_t k;
SM2_Z256_POINT C1;
SM2_Z256_POINT kP;
uint8_t x2y2[64];
SM3_CTX sm3_ctx;
if (!(SM2_MIN_PLAINTEXT_SIZE <= inlen && inlen <= SM2_MAX_PLAINTEXT_SIZE)) {
error_print();
return -1;
}
retry:
// rand k in [1, n - 1]
do {
if (sm2_z256_rand_range(k, sm2_z256_order()) != 1) {
error_print();
return -1;
}
} while (sm2_z256_is_zero(k));
// output C1 = k * G = (x1, y1)
sm2_z256_point_mul_generator(&C1, k);
sm2_z256_point_to_bytes(&C1, (uint8_t *)&out->point);
// k * P = (x2, y2)
sm2_z256_point_mul(&kP, k, &key->public_key);
sm2_z256_point_to_bytes(&kP, x2y2);
// t = KDF(x2 || y2, inlen)
sm2_kdf(x2y2, 64, inlen, out->ciphertext);
// if t is all zero, retry
if (all_zero(out->ciphertext, inlen)) {
goto retry;
}
// output C2 = M xor t
gmssl_memxor(out->ciphertext, out->ciphertext, in, inlen);
out->ciphertext_size = (uint32_t)inlen;
// output C3 = Hash(x2 || m || y2)
sm3_init(&sm3_ctx);
sm3_update(&sm3_ctx, x2y2, 32);
sm3_update(&sm3_ctx, in, inlen);
sm3_update(&sm3_ctx, x2y2 + 32, 32);
sm3_finish(&sm3_ctx, out->hash);
gmssl_secure_clear(k, sizeof(k));
gmssl_secure_clear(&kP, sizeof(SM2_Z256_POINT));
gmssl_secure_clear(x2y2, sizeof(x2y2));
return 1;
}
*/
int sm2_do_encrypt_fixlen(const SM2_KEY *key, const uint8_t *in, size_t inlen, int point_size, SM2_CIPHERTEXT *out)
{
unsigned int trys = 200;
sm2_z256_t k;
SM2_Z256_POINT C1;
SM2_Z256_POINT kP;
uint8_t x2y2[64];
SM3_CTX sm3_ctx;
if (!(SM2_MIN_PLAINTEXT_SIZE <= inlen && inlen <= SM2_MAX_PLAINTEXT_SIZE)) {
error_print();
return -1;
}
switch (point_size) {
case SM2_ciphertext_compact_point_size:
case SM2_ciphertext_typical_point_size:
case SM2_ciphertext_max_point_size:
break;
default:
error_print();
return -1;
}
retry:
// rand k in [1, n - 1]
do {
if (sm2_z256_rand_range(k, sm2_z256_order()) != 1) {
error_print();
return -1;
}
} while (sm2_z256_is_zero(k));
// output C1 = k * G = (x1, y1)
sm2_z256_point_mul_generator(&C1, k);
sm2_z256_point_to_bytes(&C1, (uint8_t *)&out->point);
// check fixlen
if (trys) {
size_t len = 0;
asn1_integer_to_der(out->point.x, 32, NULL, &len);
asn1_integer_to_der(out->point.y, 32, NULL, &len);
if (len != point_size) {
trys--;
goto retry;
}
} else {
gmssl_secure_clear(k, sizeof(k));
error_print();
return -1;
}
// k * P = (x2, y2)
sm2_z256_point_mul(&kP, k, &key->public_key);
sm2_z256_point_to_bytes(&kP, x2y2);
// t = KDF(x2 || y2, inlen)
sm2_kdf(x2y2, 64, inlen, out->ciphertext);
// if t is all zero, retry
if (all_zero(out->ciphertext, inlen)) {
goto retry;
}
// output C2 = M xor t
gmssl_memxor(out->ciphertext, out->ciphertext, in, inlen);
out->ciphertext_size = (uint32_t)inlen;
// output C3 = Hash(x2 || m || y2)
sm3_init(&sm3_ctx);
sm3_update(&sm3_ctx, x2y2, 32);
sm3_update(&sm3_ctx, in, inlen);
sm3_update(&sm3_ctx, x2y2 + 32, 32);
sm3_finish(&sm3_ctx, out->hash);
gmssl_secure_clear(k, sizeof(k));
gmssl_secure_clear(&kP, sizeof(SM2_Z256_POINT));
gmssl_secure_clear(x2y2, sizeof(x2y2));
return 1;
}
/*
int sm2_do_decrypt(const SM2_KEY *key, const SM2_CIPHERTEXT *in, uint8_t *out, size_t *outlen)
{
int ret = -1;
SM2_Z256_POINT C1;
uint8_t x2y2[64];
SM3_CTX sm3_ctx;
uint8_t hash[32];
// check C1 is on sm2 curve
if (sm2_z256_point_from_bytes(&C1, (uint8_t *)&in->point) != 1) {
error_print();
return -1;
}
// d * C1 = (x2, y2)
sm2_z256_point_mul(&C1, key->private_key, &C1);
// t = KDF(x2 || y2, klen) and check t is not all zeros
sm2_z256_point_to_bytes(&C1, x2y2);
sm2_kdf(x2y2, 64, in->ciphertext_size, out);
if (all_zero(out, in->ciphertext_size)) {
error_print();
goto end;
}
// M = C2 xor t
gmssl_memxor(out, out, in->ciphertext, in->ciphertext_size);
*outlen = in->ciphertext_size;
// u = Hash(x2 || M || y2)
sm3_init(&sm3_ctx);
sm3_update(&sm3_ctx, x2y2, 32);
sm3_update(&sm3_ctx, out, in->ciphertext_size);
sm3_update(&sm3_ctx, x2y2 + 32, 32);
sm3_finish(&sm3_ctx, hash);
// check if u == C3
if (memcmp(in->hash, hash, sizeof(hash)) != 0) {
error_print();
goto end;
}
ret = 1;
end:
gmssl_secure_clear(&C1, sizeof(SM2_Z256_POINT));
gmssl_secure_clear(x2y2, sizeof(x2y2));
return ret;
}
*/
int sm2_ciphertext_to_der(const SM2_CIPHERTEXT *C, uint8_t **out, size_t *outlen)
{
size_t len = 0;
if (!C) {
return 0;
}
if (asn1_integer_to_der(C->point.x, 32, NULL, &len) != 1
|| asn1_integer_to_der(C->point.y, 32, NULL, &len) != 1
|| asn1_octet_string_to_der(C->hash, 32, NULL, &len) != 1
|| asn1_octet_string_to_der(C->ciphertext, C->ciphertext_size, NULL, &len) != 1
|| asn1_sequence_header_to_der(len, out, outlen) != 1
|| asn1_integer_to_der(C->point.x, 32, out, outlen) != 1
|| asn1_integer_to_der(C->point.y, 32, out, outlen) != 1
|| asn1_octet_string_to_der(C->hash, 32, out, outlen) != 1
|| asn1_octet_string_to_der(C->ciphertext, C->ciphertext_size, out, outlen) != 1) {
error_print();
return -1;
}
return 1;
}
int sm2_ciphertext_from_der(SM2_CIPHERTEXT *C, const uint8_t **in, size_t *inlen)
{
int ret;
const uint8_t *d;
size_t dlen;
const uint8_t *x;
const uint8_t *y;
const uint8_t *hash;
const uint8_t *c;
size_t xlen, ylen, hashlen, clen;
if ((ret = asn1_sequence_from_der(&d, &dlen, in, inlen)) != 1) {
if (ret < 0) error_print();
return ret;
}
if (asn1_integer_from_der(&x, &xlen, &d, &dlen) != 1
|| asn1_length_le(xlen, 32) != 1) {
error_print();
return -1;
}
if (asn1_integer_from_der(&y, &ylen, &d, &dlen) != 1
|| asn1_length_le(ylen, 32) != 1) {
error_print();
return -1;
}
if (asn1_octet_string_from_der(&hash, &hashlen, &d, &dlen) != 1
|| asn1_check(hashlen == 32) != 1) {
error_print();
return -1;
}
if (asn1_octet_string_from_der(&c, &clen, &d, &dlen) != 1
// || asn1_length_is_zero(clen) == 1
|| asn1_length_le(clen, SM2_MAX_PLAINTEXT_SIZE) != 1) {
error_print();
return -1;
}
if (asn1_length_is_zero(dlen) != 1) {
error_print();
return -1;
}
memset(C, 0, sizeof(SM2_CIPHERTEXT));
memcpy(C->point.x + 32 - xlen, x, xlen);
memcpy(C->point.y + 32 - ylen, y, ylen);
memcpy(C->hash, hash, hashlen);
memcpy(C->ciphertext, c, clen);
C->ciphertext_size = (uint8_t)clen;
return 1;
}
int sm2_ciphertext_print(FILE *fp, int fmt, int ind, const char *label, const uint8_t *a, size_t alen)
{
uint8_t buf[512] = {0};
SM2_CIPHERTEXT *c = (SM2_CIPHERTEXT *)buf;
if (sm2_ciphertext_from_der(c, &a, &alen) != 1
|| asn1_length_is_zero(alen) != 1) {
error_print();
return -1;
}
format_print(fp, fmt, ind, "%s\n", label);
ind += 4;
format_bytes(fp, fmt, ind, "XCoordinate", c->point.x, 32);
format_bytes(fp, fmt, ind, "YCoordinate", c->point.y, 32);
format_bytes(fp, fmt, ind, "HASH", c->hash, 32);
format_bytes(fp, fmt, ind, "CipherText", c->ciphertext, c->ciphertext_size);
return 1;
}
int sm2_encrypt(const SM2_KEY *key, const uint8_t *in, size_t inlen, uint8_t *out, size_t *outlen)
{
SM2_CIPHERTEXT C;
if (!key || !in || !out || !outlen) {
error_print();
return -1;
}
if (!inlen) {
error_print();
return -1;
}
if (sm2_do_encrypt(key, in, inlen, &C) != 1) {
error_print();
return -1;
}
*outlen = 0;
if (sm2_ciphertext_to_der(&C, &out, outlen) != 1) {
error_print();
return -1;
}
return 1;
}
int sm2_encrypt_fixlen(const SM2_KEY *key, const uint8_t *in, size_t inlen, int point_size, uint8_t *out, size_t *outlen)
{
SM2_CIPHERTEXT C;
if (!key || !in || !out || !outlen) {
error_print();
return -1;
}
if (!inlen) {
error_print();
return -1;
}
if (sm2_do_encrypt_fixlen(key, in, inlen, point_size, &C) != 1) {
error_print();
return -1;
}
*outlen = 0;
if (sm2_ciphertext_to_der(&C, &out, outlen) != 1) {
error_print();
return -1;
}
return 1;
}
int sm2_decrypt(const SM2_KEY *key, const uint8_t *in, size_t inlen, uint8_t *out, size_t *outlen)
{
SM2_CIPHERTEXT C;
if (!key || !in || !out || !outlen) {
error_print();
return -1;
}
if (sm2_ciphertext_from_der(&C, &in, &inlen) != 1
|| asn1_length_is_zero(inlen) != 1) {
error_print();
return -1;
}
if (sm2_do_decrypt(key, &C, out, outlen) != 1) {
error_print();
return -1;
}
return 1;
}
int sm2_encrypt_init(SM2_ENC_CTX *ctx)
{
if (!ctx) {
error_print();
return -1;
}
#define ENABLE_SM2_ENC_PRE_COMPUTE 1
#if ENABLE_SM2_ENC_PRE_COMPUTE
if (sm2_encrypt_pre_compute(ctx->pre_comp) != 1) {
error_print();
return -1;
}
ctx->pre_comp_num = SM2_ENC_PRE_COMP_NUM;
#endif
ctx->buf_size = 0;
return 1;
}
int sm2_encrypt_update(SM2_ENC_CTX *ctx, const uint8_t *in, size_t inlen)
{
if (!ctx) {
error_print();
return -1;
}
if (ctx->buf_size > SM2_MAX_PLAINTEXT_SIZE) {
error_print();
return -1;
}
if (in) {
if (inlen > SM2_MAX_PLAINTEXT_SIZE - ctx->buf_size) {
error_print();
return -1;
}
memcpy(ctx->buf + ctx->buf_size, in, inlen);
ctx->buf_size += inlen;
}
return 1;
}
int sm2_encrypt_finish(SM2_ENC_CTX *ctx, const SM2_KEY *public_key, uint8_t *out, size_t *outlen)
{
SM2_CIPHERTEXT ciphertext;
if (!ctx || !public_key || !outlen) {
error_print();
return -1;
}
if (ctx->buf_size > SM2_MAX_PLAINTEXT_SIZE) {
error_print();
return -1;
}
if (ctx->buf_size == 0) {
error_print();
return -1;
}
if (!out) {
*outlen = SM2_MAX_CIPHERTEXT_SIZE;
return 1;
}
#if ENABLE_SM2_ENC_PRE_COMPUTE
if (ctx->pre_comp_num == 0) {
if (sm2_encrypt_pre_compute(ctx->pre_comp) != 1) {
error_print();
return -1;
}
ctx->pre_comp_num = SM2_ENC_PRE_COMP_NUM;
}
ctx->pre_comp_num--;
if (sm2_do_encrypt_ex(public_key, &ctx->pre_comp[ctx->pre_comp_num], ctx->buf, ctx->buf_size, &ciphertext) != 1) {
error_print();
return -1;
}
*outlen = 0;
if (sm2_ciphertext_to_der(&ciphertext, &out, outlen) != 1) {
error_print();
return -1;
}
#else
if (sm2_encrypt(public_key, ctx->buf, ctx->buf_size, out, outlen) != 1) {
error_print();
return -1;
}
#endif
return 1;
}
int sm2_encrypt_reset(SM2_ENC_CTX *ctx)
{
if (!ctx) {
error_print();
return -1;
}
ctx->buf_size = 0;
return 1;
}
int sm2_decrypt_init(SM2_DEC_CTX *ctx)
{
if (!ctx) {
error_print();
return -1;
}
ctx->buf_size = 0;
return 1;
}
int sm2_decrypt_update(SM2_DEC_CTX *ctx, const uint8_t *in, size_t inlen)
{
if (!ctx) {
error_print();
return -1;
}
if (ctx->buf_size > SM2_MAX_CIPHERTEXT_SIZE) {
error_print();
return -1;
}
if (in) {
if (inlen > SM2_MAX_CIPHERTEXT_SIZE - ctx->buf_size) {
error_print();
return -1;
}
memcpy(ctx->buf + ctx->buf_size, in, inlen);
ctx->buf_size += inlen;
}
return 1;
}
int sm2_decrypt_finish(SM2_DEC_CTX *ctx, const SM2_KEY *key, uint8_t *out, size_t *outlen)
{
if (!ctx || !key || !outlen) {
error_print();
return -1;
}
if (ctx->buf_size > SM2_MAX_CIPHERTEXT_SIZE) {
error_print();
return -1;
}
if (ctx->buf_size < SM2_MIN_CIPHERTEXT_SIZE) {
error_print();
return -1;
}
if (!out) {
*outlen = SM2_MAX_PLAINTEXT_SIZE;
return 1;
}
if (sm2_decrypt(key, ctx->buf, ctx->buf_size, out, outlen) != 1) {
error_print();
return -1;
}
return 1;
}
int sm2_decrypt_reset(SM2_DEC_CTX *ctx)
{
if (!ctx) {
error_print();
return -1;
}
ctx->buf_size = 0;
return 1;
}

824
src/sdf/sdf_sm2_sign.c Normal file
View File

@@ -0,0 +1,824 @@
/*
* Copyright 2014-2024 The GmSSL Project. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <gmssl/sdf.h>
#include <gmssl/sm2.h>
#include <gmssl/sm3.h>
#include <gmssl/mem.h>
#include <gmssl/asn1.h>
#include <gmssl/error.h>
#include "sdf.h"
extern void *globalDeviceHandle;
static const uint8_t zeros[ECCref_MAX_LEN - 32] = {0};
// hSession is from HashInit/Update/Final, also means the uiISKIndex key has been opened with password
int sdf_sm2_do_sign(void *hSession, unsigned int uiISKIndex, const uint8_t dgst[32], SM2_SIGNATURE *sig)
{
ECCSignature eccSignature;
int ret;
ret = SDF_InternalSign_ECC(hSession, uiISKIndex, (unsigned char *)dgst, 32, &eccSignature);
if (ret != SDR_OK) {
error_print();
return -1;
}
// ECCSignature to SM2_SIGNATURE
if (memcmp(eccSignature.r, zeros, sizeof(zeros)) != 0
|| memcmp(eccSignature.s, zeros, sizeof(zeros)) != 0) {
error_print();
return -1;
}
memcpy(sig->r, eccSignature.r + sizeof(zeros), 32);
memcpy(sig->s, eccSignature.s + sizeof(zeros), 32);
return 1;
}
int sdf_sm2_do_verify(void *hSession, const SM2_KEY *key, const uint8_t dgst[32], const SM2_SIGNATURE *sig)
{
SM2_POINT point;
ECCrefPublicKey eccPublicKey;
ECCSignature eccSignature;
int ret;
// SM2_KEY to ECCrefPublicKey
sm2_z256_point_to_bytes(&key->public_key, (uint8_t *)&point);
eccPublicKey.bits = 256;
memset(eccPublicKey.x, 0, sizeof(zeros));
memcpy(eccPublicKey.x + sizeof(zeros), point.x, 32);
memset(eccPublicKey.y, 0, sizeof(zeros));
memcpy(eccPublicKey.y + sizeof(zeros), point.y, 32);
// SM2_SIGNATURE to ECCSignature
memset(eccSignature.r, 0, sizeof(zeros));
memcpy(eccSignature.r + sizeof(zeros), sig->r, 32);
memset(eccSignature.s, 0, sizeof(zeros));
memcpy(eccSignature.s + sizeof(zeros), sig->s, 32);
ret = SDF_ExternalVerify_ECC(hSession, SGD_SM2_1, &eccPublicKey, (unsigned char *)dgst, 32, &eccSignature);
if (ret != SDR_OK) {
error_print();
return -1;
}
return 1;
}
int sdf_load_sm2_sign_key(SM2_KEY *key, unsigned int uiISKIndex, const char *pass)
{
void *hSession = NULL;
ECCrefPublicKey eccPublicKey;
SM2_POINT point;
SDF_PRIVATE_KEY *sk = (SDF_PRIVATE_KEY *)&key->private_key;
int ret;
ret = SDF_OpenSession(globalDeviceHandle, &hSession);
if (ret != SDR_OK) {
error_print();
return -1;
}
ret = SDF_GetPrivateKeyAccessRight(hSession, uiISKIndex, (unsigned char *)pass, (unsigned int)strlen(pass));
if (ret != SDR_OK) {
error_print();
return -1;
}
ret = SDF_ExportSignPublicKey_ECC(hSession, uiISKIndex, &eccPublicKey);
if (ret != SDR_OK) {
error_print();
return -1;
}
// check bits and endian of ECCrefPublicKey
if (eccPublicKey.bits != 256) {
error_print();
return -1;
}
if (memcmp(eccPublicKey.x, zeros, sizeof(zeros)) != 0
|| memcmp(eccPublicKey.y, zeros, sizeof(zeros)) != 0) {
error_print();
return -1;
}
// set SM2_KEY.public_key
memcpy(point.x, eccPublicKey.x + sizeof(zeros), 32);
memcpy(point.y, eccPublicKey.y + sizeof(zeros), 32);
if (sm2_z256_point_from_bytes(&key->public_key, (uint8_t *)&point) != 1) {
error_print();
return -1;
}
// save index and pass in SM2_KEY.private_key
sk->index = uiISKIndex;
if (strlen(pass) > 26) {
error_print();
return -1;
}
memset(sk->pass, 0, 27);
memcpy(sk->pass, pass, strlen(pass));
return 1;
}
int sm2_sign_init(SM2_SIGN_CTX *ctx, const SM2_KEY *key, const char *id, size_t idlen)
{
SDF_SM3_CTX *sdf_sm3_ctx = (SDF_SM3_CTX *)&ctx->sm3_ctx;
SDF_PRIVATE_KEY *sk = (SDF_PRIVATE_KEY *)ctx->key.private_key;
void *hSession = NULL;
ECCrefPublicKey eccPublicKey;
int ret;
ret = SDF_OpenSession(globalDeviceHandle, &hSession);
if (ret != SDR_OK) {
error_print();
return -1;
}
// check and save sign key
ret = SDF_GetPrivateKeyAccessRight(hSession, sk->index, sk->pass, sk->passlen);
if (ret != SDR_OK) {
error_print();
return -1;
}
ctx->key = *key;
// hash_init with Z
ret = SDF_ExportSignPublicKey_ECC(hSession, sk->index, &eccPublicKey);
if (ret != SDR_OK) {
error_print();
return -1;
}
ret = SDF_HashInit(hSession, SGD_SM3, &eccPublicKey, (unsigned char *)id, (unsigned int)idlen);
if (ret != SDR_OK) {
error_print();
return -1;
}
// save session
sdf_sm3_ctx->hSession = hSession;
return 1;
}
int sm2_sign_update(SM2_SIGN_CTX *ctx, const uint8_t *data, size_t datalen)
{
SDF_SM3_CTX *sdf_sm3_ctx = (SDF_SM3_CTX *)&ctx->sm3_ctx;
int ret;
ret = SDF_HashUpdate(sdf_sm3_ctx->hSession, (unsigned char *)data, (unsigned int)datalen);
if (ret != SDR_OK) {
error_print();
return -1;
}
return 1;
}
int sm2_sign_finish(SM2_SIGN_CTX *ctx, uint8_t *sig, size_t *siglen)
{
SDF_SM3_CTX *sdf_sm3_ctx = (SDF_SM3_CTX *)&ctx->sm3_ctx;
SDF_PRIVATE_KEY *sk = (SDF_PRIVATE_KEY *)ctx->key.private_key;
uint8_t dgst[32];
unsigned int uiLength;
SM2_SIGNATURE signature;
int ret;
// get hSession from ctx
ret = SDF_HashFinal(sdf_sm3_ctx->hSession, dgst, &uiLength);
if (ret != SDR_OK) {
error_print();
return -1;
}
// get uiISKIndex from ctx
if (sdf_sm2_do_sign(sdf_sm3_ctx->hSession, sk->index, dgst, &signature) != 1) {
error_print();
return -1;
}
*siglen = 0;
if (sm2_signature_to_der(&signature, &sig, siglen) != 1) {
error_print();
return -1;
}
// CloseSession
SDF_CloseSession(sdf_sm3_ctx->hSession);
// TODO: add sm2_sign_ctx_cleanup() to resue the hSession
return 1;
}
int sm2_sign_finish_fixlen(SM2_SIGN_CTX *ctx, size_t siglen, uint8_t *sig)
{
error_print();
return -1;
}
// TODO: how to re-use hSession?
int sm2_sign_reset(SM2_SIGN_CTX *ctx)
{
error_print();
return -1;
}
int sm2_verify_init(SM2_VERIFY_CTX *ctx, const SM2_KEY *key, const char *id, size_t idlen)
{
SDF_SM3_CTX *sdf_sm3_ctx = (SDF_SM3_CTX *)&ctx->sm3_ctx;
void *hSession = NULL;
SM2_POINT point;
ECCrefPublicKey eccPublicKey;
int ret;
ret = SDF_OpenSession(globalDeviceHandle, &hSession);
if (ret != SDR_OK) {
error_print();
return -1;
}
sm2_z256_point_to_bytes(&key->public_key, (uint8_t *)&point);
eccPublicKey.bits = 256;
memset(eccPublicKey.x, 0, sizeof(zeros));
memcpy(eccPublicKey.x + sizeof(zeros), point.x, 32);
memset(eccPublicKey.y, 0, sizeof(zeros));
memcpy(eccPublicKey.y + sizeof(zeros), point.y, 32);
ret = SDF_HashInit(hSession, SGD_SM3, &eccPublicKey, (unsigned char *)id, (unsigned int)idlen);
if (ret != SDR_OK) {
SDF_CloseSession(hSession);
error_print();
return -1;
}
sdf_sm3_ctx->hSession = hSession;
return 1;
}
int sm2_verify_update(SM2_VERIFY_CTX *ctx, const uint8_t *data, size_t datalen)
{
SDF_SM3_CTX *sdf_sm3_ctx = (SDF_SM3_CTX *)&ctx->sm3_ctx;
int ret;
ret = SDF_HashUpdate(sdf_sm3_ctx->hSession, (unsigned char *)data, (unsigned int)datalen);
if (ret != SDR_OK) {
error_print();
return -1;
}
return 1;
}
int sm2_verify_finish(SM2_VERIFY_CTX *ctx, const uint8_t *sigbuf, size_t siglen)
{
SDF_SM3_CTX *sdf_sm3_ctx = (SDF_SM3_CTX *)&ctx->sm3_ctx;
uint8_t dgst[32];
unsigned int uiLength;
SM2_SIGNATURE sig;
int ret;
ret = SDF_HashFinal(sdf_sm3_ctx->hSession, dgst, &uiLength);
if (ret != SDR_OK) {
error_print();
return -1;
}
if (sm2_signature_from_der(&sig, &sigbuf, &siglen) != 1
|| asn1_length_is_zero(siglen) != 1) {
error_print();
return -1;
}
if (sdf_sm2_do_verify(sdf_sm3_ctx->hSession, &ctx->key, dgst, &sig) != 1) {
error_print();
return -1;
}
return 1;
}
int sm2_verify_reset(SM2_VERIFY_CTX *ctx)
{
error_print();
return -1;
}
// The following code copy from src/sm2_sign.c
int sm2_do_sign(const SM2_KEY *key, const uint8_t dgst[32], SM2_SIGNATURE *sig)
{
SM2_Z256_POINT P;
sm2_z256_t d_inv;
sm2_z256_t e;
sm2_z256_t k;
sm2_z256_t x;
sm2_z256_t t;
sm2_z256_t r;
sm2_z256_t s;
// compute (d + 1)^-1 (mod n)
sm2_z256_modn_add(d_inv, key->private_key, sm2_z256_one());
if (sm2_z256_is_zero(d_inv)) {
error_print();
return -1;
}
sm2_z256_modn_inv(d_inv, d_inv);
// e = H(M)
sm2_z256_from_bytes(e, dgst);
retry:
// rand k in [1, n - 1]
do {
if (sm2_z256_rand_range(k, sm2_z256_order()) != 1) {
error_print();
return -1;
}
} while (sm2_z256_is_zero(k));
// (x, y) = kG
sm2_z256_point_mul_generator(&P, k);
sm2_z256_point_get_xy(&P, x, NULL);
// r = e + x (mod n)
if (sm2_z256_cmp(e, sm2_z256_order()) >= 0) {
sm2_z256_sub(e, e, sm2_z256_order());
}
if (sm2_z256_cmp(x, sm2_z256_order()) >= 0) {
sm2_z256_sub(x, x, sm2_z256_order());
}
sm2_z256_modn_add(r, e, x);
// if r == 0 or r + k == n re-generate k
sm2_z256_add(t, r, k);
if (sm2_z256_is_zero(r) || sm2_z256_cmp(t, sm2_z256_order()) == 0) {
goto retry;
}
// s = ((1 + d)^-1 * (k - r * d)) mod n
sm2_z256_modn_mul(t, r, key->private_key);
sm2_z256_modn_sub(k, k, t);
sm2_z256_modn_mul(s, d_inv, k);
// check s != 0
if (sm2_z256_is_zero(s)) {
goto retry;
}
sm2_z256_to_bytes(r, sig->r);
sm2_z256_to_bytes(s, sig->s);
gmssl_secure_clear(d_inv, sizeof(d_inv));
gmssl_secure_clear(k, sizeof(k));
gmssl_secure_clear(t, sizeof(t));
return 1;
}
// d' = (d + 1)^-1 (mod n)
int sm2_fast_sign_compute_key(const SM2_KEY *key, sm2_z256_t fast_private)
{
if (sm2_z256_cmp(key->private_key, sm2_z256_order_minus_one()) >= 0) {
error_print();
return -1;
}
sm2_z256_modn_add(fast_private, key->private_key, sm2_z256_one());
sm2_z256_modn_inv(fast_private, fast_private);
return 1;
}
// use Montgomery's Trick to inverse Z coordinates on multiple (x1, y1) = [k]G
int sm2_fast_sign_pre_compute(SM2_SIGN_PRE_COMP pre_comp[32])
{
SM2_Z256_POINT P[32];
sm2_z256_t f[32];
sm2_z256_t g[32];
int i;
for (i = 0; i < 32; i++) {
// rand k in [1, n - 1]
do {
if (sm2_z256_rand_range(pre_comp[i].k, sm2_z256_order()) != 1) {
error_print();
return -1;
}
} while (sm2_z256_is_zero(pre_comp[i].k));
// (x1, y1) = kG
sm2_z256_point_mul_generator(&P[i], pre_comp[i].k);
}
// f[0] = Z[0]
// f[1] = Z[0] * Z[1]
// ...
// f[31] = Z[0] * Z[1] * ... * Z[31]
sm2_z256_copy(f[0], P[0].Z);
for (i = 1; i < 32; i++) {
sm2_z256_modp_mont_mul(f[i], f[i - 1], P[i].Z);
}
// f[31]^-1 = (Z[0] * ... * Z[31])^-1
sm2_z256_modp_mont_inv(f[31], f[31]);
// g[31] = Z[31]
// g[30] = Z[30] * Z[31]
// ...
// g[1] = Z[1] * Z[2] * ... * Z[31]
//
sm2_z256_copy(g[31], P[31].Z);
for (i = 30; i >= 1; i--) {
sm2_z256_modp_mont_mul(g[i], g[i + 1], P[i].Z);
}
// Z[0]^-1 = g[1] * f[31]^-1
// Z[1]^-1 = g[2] * f[0] * f[31]^-1
// Z[2]^-1 = g[3] * f[1] * f[31]^-1
// ...
// Z[30]^-1 = g[31] * f[29] * f[31]^-1
// Z[31]^-1 = f[30] * f[31]^-1
sm2_z256_modp_mont_mul(P[0].Z, g[1], f[31]);
for (i = 1; i <= 30; i++) {
sm2_z256_modp_mont_mul(P[i].Z, g[i + 1], f[i - 1]);
sm2_z256_modp_mont_mul(P[i].Z, P[i].Z, f[31]);
}
sm2_z256_modp_mont_mul(P[31].Z, f[30], f[31]);
// x[i] = X[i] * Z[i]^-2 (mod n)
for (i = 0; i < 32; i++) {
sm2_z256_modp_mont_sqr(P[i].Z, P[i].Z);
sm2_z256_modp_mont_mul(pre_comp[i].x1_modn, P[i].X, P[i].Z);
sm2_z256_modp_from_mont(pre_comp[i].x1_modn, pre_comp[i].x1_modn);
if (sm2_z256_cmp(pre_comp[i].x1_modn, sm2_z256_order()) >= 0) {
sm2_z256_sub(pre_comp[i].x1_modn, pre_comp[i].x1_modn, sm2_z256_order());
}
}
return 1;
}
// s = (k - r * d)/(1 + d)
// = -r + (k + r)*(1 + d)^-1
// = -r + (k + r) * d'
int sm2_fast_sign(const sm2_z256_t fast_private, SM2_SIGN_PRE_COMP *pre_comp,
const uint8_t dgst[32], SM2_SIGNATURE *sig)
{
SM2_Z256_POINT R;
sm2_z256_t e;
sm2_z256_t r;
sm2_z256_t s;
// e = H(M)
sm2_z256_from_bytes(e, dgst);
if (sm2_z256_cmp(e, sm2_z256_order()) >= 0) {
sm2_z256_sub(e, e, sm2_z256_order());
}
// r = e + x1 (mod n)
sm2_z256_modn_add(r, e, pre_comp->x1_modn);
// s = (k + r) * d' - r
sm2_z256_modn_add(s, pre_comp->k, r);
sm2_z256_modn_mul(s, s, fast_private);
sm2_z256_modn_sub(s, s, r);
sm2_z256_to_bytes(r, sig->r);
sm2_z256_to_bytes(s, sig->s);
return 1;
}
int sm2_fast_verify(const SM2_Z256_POINT point_table[16], const uint8_t dgst[32], const SM2_SIGNATURE *sig)
{
SM2_Z256_POINT R;
SM2_Z256_POINT T;
sm2_z256_t r;
sm2_z256_t s;
sm2_z256_t e;
sm2_z256_t x;
sm2_z256_t t;
// check r, s in [1, n-1]
sm2_z256_from_bytes(r, sig->r);
if (sm2_z256_is_zero(r) == 1) {
error_print();
return -1;
}
if (sm2_z256_cmp(r, sm2_z256_order()) >= 0) {
error_print();
return -1;
}
sm2_z256_from_bytes(s, sig->s);
if (sm2_z256_is_zero(s) == 1) {
error_print();
return -1;
}
if (sm2_z256_cmp(s, sm2_z256_order()) >= 0) {
error_print();
return -1;
}
// t = r + s (mod n), check t != 0
sm2_z256_modn_add(t, r, s);
if (sm2_z256_is_zero(t)) {
error_print();
return -1;
}
// Q(x,y) = s * G + t * P
sm2_z256_point_mul_generator(&R, s);
sm2_z256_point_mul_ex(&T, t, point_table);
sm2_z256_point_add(&R, &R, &T);
sm2_z256_point_get_xy(&R, x, NULL);
// e = H(M)
sm2_z256_from_bytes(e, dgst);
if (sm2_z256_cmp(e, sm2_z256_order()) >= 0) {
sm2_z256_sub(e, e, sm2_z256_order());
}
// r' = e + x (mod n)
if (sm2_z256_cmp(x, sm2_z256_order()) >= 0) {
sm2_z256_sub(x, x, sm2_z256_order());
}
sm2_z256_modn_add(e, e, x);
// check if r == r'
if (sm2_z256_cmp(e, r) != 0) {
error_print();
return -1;
}
return 1;
}
int sm2_do_verify(const SM2_KEY *key, const uint8_t dgst[32], const SM2_SIGNATURE *sig)
{
SM2_Z256_POINT R;
SM2_Z256_POINT T;
sm2_z256_t r;
sm2_z256_t s;
sm2_z256_t e;
sm2_z256_t x;
sm2_z256_t t;
// check r, s in [1, n-1]
sm2_z256_from_bytes(r, sig->r);
if (sm2_z256_is_zero(r) == 1) {
error_print();
return -1;
}
if (sm2_z256_cmp(r, sm2_z256_order()) >= 0) {
error_print();
return -1;
}
sm2_z256_from_bytes(s, sig->s);
if (sm2_z256_is_zero(s) == 1) {
error_print();
return -1;
}
if (sm2_z256_cmp(s, sm2_z256_order()) >= 0) {
error_print();
return -1;
}
// t = r + s (mod n), check t != 0
sm2_z256_modn_add(t, r, s);
if (sm2_z256_is_zero(t)) {
error_print();
return -1;
}
// Q(x,y) = s * G + t * P
sm2_z256_point_mul_generator(&R, s);
sm2_z256_point_mul(&T, t, &key->public_key);
sm2_z256_point_add(&R, &R, &T);
sm2_z256_point_get_xy(&R, x, NULL);
// e = H(M)
sm2_z256_from_bytes(e, dgst);
if (sm2_z256_cmp(e, sm2_z256_order()) >= 0) {
sm2_z256_sub(e, e, sm2_z256_order());
}
// r' = e + x (mod n)
if (sm2_z256_cmp(x, sm2_z256_order()) >= 0) {
sm2_z256_sub(x, x, sm2_z256_order());
}
sm2_z256_modn_add(e, e, x);
// check if r == r'
if (sm2_z256_cmp(e, r) != 0) {
error_print();
return -1;
}
return 1;
}
int sm2_signature_to_der(const SM2_SIGNATURE *sig, uint8_t **out, size_t *outlen)
{
size_t len = 0;
if (!sig) {
return 0;
}
if (asn1_integer_to_der(sig->r, 32, NULL, &len) != 1
|| asn1_integer_to_der(sig->s, 32, NULL, &len) != 1
|| asn1_sequence_header_to_der(len, out, outlen) != 1
|| asn1_integer_to_der(sig->r, 32, out, outlen) != 1
|| asn1_integer_to_der(sig->s, 32, out, outlen) != 1) {
error_print();
return -1;
}
return 1;
}
int sm2_signature_from_der(SM2_SIGNATURE *sig, const uint8_t **in, size_t *inlen)
{
int ret;
const uint8_t *d;
size_t dlen;
const uint8_t *r;
size_t rlen;
const uint8_t *s;
size_t slen;
if ((ret = asn1_sequence_from_der(&d, &dlen, in, inlen)) != 1) {
if (ret < 0) error_print();
return ret;
}
if (asn1_integer_from_der(&r, &rlen, &d, &dlen) != 1
|| asn1_integer_from_der(&s, &slen, &d, &dlen) != 1
|| asn1_length_le(rlen, 32) != 1
|| asn1_length_le(slen, 32) != 1
|| asn1_length_is_zero(dlen) != 1) {
error_print();
return -1;
}
memset(sig, 0, sizeof(*sig));
memcpy(sig->r + 32 - rlen, r, rlen);
memcpy(sig->s + 32 - slen, s, slen);
return 1;
}
int sm2_signature_print(FILE *fp, int fmt, int ind, const char *label, const uint8_t *a, size_t alen)
{
SM2_SIGNATURE sig;
format_print(fp, fmt, ind, "%s\n", label);
ind += 4;
if (sm2_signature_from_der(&sig, &a, &alen) != 1
|| asn1_length_is_zero(alen) != 1) {
error_print();
return -1;
}
format_bytes(fp, fmt, ind, "r", sig.r, 32);
format_bytes(fp, fmt, ind, "s", sig.s, 32);
return 1;
}
int sm2_sign(const SM2_KEY *key, const uint8_t dgst[32], uint8_t *sigbuf, size_t *siglen)
{
SM2_SIGNATURE sig;
if (!key || !dgst || !sigbuf || !siglen) {
error_print();
return -1;
}
if (sm2_do_sign(key, dgst, &sig) != 1) {
error_print();
return -1;
}
*siglen = 0;
if (sm2_signature_to_der(&sig, &sigbuf, siglen) != 1) {
error_print();
return -1;
}
return 1;
}
int sm2_sign_fixlen(const SM2_KEY *key, const uint8_t dgst[32], size_t siglen, uint8_t *sig)
{
unsigned int trys = 200; // 200 trys is engouh
uint8_t buf[SM2_MAX_SIGNATURE_SIZE];
size_t len;
switch (siglen) {
case SM2_signature_compact_size:
case SM2_signature_typical_size:
case SM2_signature_max_size:
break;
default:
error_print();
return -1;
}
while (trys--) {
if (sm2_sign(key, dgst, buf, &len) != 1) {
error_print();
return -1;
}
if (len == siglen) {
memcpy(sig, buf, len);
return 1;
}
}
// might caused by bad randomness
error_print();
return -1;
}
int sm2_verify(const SM2_KEY *key, const uint8_t dgst[32], const uint8_t *sigbuf, size_t siglen)
{
SM2_SIGNATURE sig;
if (!key || !dgst || !sigbuf || !siglen) {
error_print();
return -1;
}
if (sm2_signature_from_der(&sig, &sigbuf, &siglen) != 1
|| asn1_length_is_zero(siglen) != 1) {
error_print();
return -1;
}
if (sm2_do_verify(key, dgst, &sig) != 1) {
error_print();
return -1;
}
return 1;
}
int sm2_compute_z(uint8_t z[32], const SM2_Z256_POINT *pub, const char *id, size_t idlen)
{
SM3_CTX ctx;
uint8_t zin[18 + 32 * 6] = {
0x00, 0x80,
0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,
0xFF,0xFF,0xFF,0xFE,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFC,
0x28,0xE9,0xFA,0x9E,0x9D,0x9F,0x5E,0x34,0x4D,0x5A,0x9E,0x4B,0xCF,0x65,0x09,0xA7,
0xF3,0x97,0x89,0xF5,0x15,0xAB,0x8F,0x92,0xDD,0xBC,0xBD,0x41,0x4D,0x94,0x0E,0x93,
0x32,0xC4,0xAE,0x2C,0x1F,0x19,0x81,0x19,0x5F,0x99,0x04,0x46,0x6A,0x39,0xC9,0x94,
0x8F,0xE3,0x0B,0xBF,0xF2,0x66,0x0B,0xE1,0x71,0x5A,0x45,0x89,0x33,0x4C,0x74,0xC7,
0xBC,0x37,0x36,0xA2,0xF4,0xF6,0x77,0x9C,0x59,0xBD,0xCE,0xE3,0x6B,0x69,0x21,0x53,
0xD0,0xA9,0x87,0x7C,0xC6,0x2A,0x47,0x40,0x02,0xDF,0x32,0xE5,0x21,0x39,0xF0,0xA0,
};
if (!z || !pub || !id) {
error_print();
return -1;
}
sm2_z256_point_to_bytes(pub, &zin[18 + 32 * 4]);
sm3_init(&ctx);
if (strcmp(id, SM2_DEFAULT_ID) == 0) {
sm3_update(&ctx, zin, sizeof(zin));
} else {
uint8_t idbits[2];
idbits[0] = (uint8_t)(idlen >> 5);
idbits[1] = (uint8_t)(idlen << 3);
sm3_update(&ctx, idbits, 2);
sm3_update(&ctx, (uint8_t *)id, idlen);
sm3_update(&ctx, zin + 18, 32 * 6);
}
sm3_finish(&ctx, z);
return 1;
}

107
src/sdf/sdf_sm3.c Executable file
View File

@@ -0,0 +1,107 @@
/*
* Copyright 2014-2024 The GmSSL Project. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <gmssl/sdf.h>
#include <gmssl/sm2.h>
#include <gmssl/error.h>
#include "sdf.h"
#include "sdf_ext.h"
/*
* TODO:
* 1. SM3-HMAC
*/
void *globalDeviceHandle = NULL;
int sm3_digest_init(SM3_DIGEST_CTX *ctx, const uint8_t *key, size_t keylen)
{
SDF_SM3_CTX *sdf_sm3_ctx = (SDF_SM3_CTX *)&ctx->sm3_ctx;
void *hSession = NULL;
int ret;
if (globalDeviceHandle == NULL) {
if ((ret = SDF_OpenDevice(&globalDeviceHandle)) != SDR_OK) {
error_print_msg("SDFerror: 0x%08X\n", ret);
return -1;
}
if (globalDeviceHandle == NULL) {
error_print();
return -1;
}
}
if ((ret = SDF_OpenSession(globalDeviceHandle, &hSession)) != SDR_OK) {
error_print_msg("SDFerror: 0x%08X\n", ret);
return -1;
}
if ((ret = SDF_HashInit(hSession, SGD_SM3, NULL, NULL, 0)) != SDR_OK) {
error_print_msg("SDFerror: 0x%08X\n", ret);
return -1;
}
sdf_sm3_ctx->hSession = hSession;
return 1;
}
int sm3_digest_update(SM3_DIGEST_CTX *ctx, const uint8_t *data, size_t datalen)
{
SDF_SM3_CTX *sdf_sm3_ctx = (SDF_SM3_CTX *)&ctx->sm3_ctx;
int ret;
if ((ret = SDF_HashUpdate(sdf_sm3_ctx->hSession, (uint8_t *)data, (unsigned int)datalen)) != SDR_OK) {
error_print_msg("SDFerror: 0x%08X\n", ret);
return -1;
}
return 1;
}
int sm3_digest_finish(SM3_DIGEST_CTX *ctx, uint8_t dgst[SM3_DIGEST_SIZE])
{
SDF_SM3_CTX *sdf_sm3_ctx = (SDF_SM3_CTX *)&ctx->sm3_ctx;
unsigned int dgstlen;
int ret;
if ((ret = SDF_HashFinal(sdf_sm3_ctx->hSession, dgst, &dgstlen)) != SDR_OK) {
error_print_msg("SDFerror: 0x%08X\n", ret);
return -1;
}
return 1;
}
int sm3_digest_reset(SM3_DIGEST_CTX *ctx)
{
SDF_SM3_CTX *sdf_sm3_ctx = (SDF_SM3_CTX *)&ctx->sm3_ctx;
int ret;
if ((ret = SDF_HashInit(sdf_sm3_ctx->hSession, SGD_SM3, NULL, NULL, 0)) != SDR_OK) {
error_print_msg("SDFerror: 0x%08X\n", ret);
return -1;
}
return 1;
}
void sm3_digest_cleanup(SM3_DIGEST_CTX *ctx)
{
SDF_SM3_CTX *sdf_sm3_ctx = (SDF_SM3_CTX *)&ctx->sm3_ctx;
int ret;
if ((ret = SDF_CloseSession(sdf_sm3_ctx->hSession)) != SDR_OK) {
error_print_msg("SDFerror: 0x%08X\n", ret);
}
memset(ctx, 0, sizeof(*ctx));
}

420
src/sdf/sdf_sm4_cbc.c Normal file
View File

@@ -0,0 +1,420 @@
/*
* Copyright 2014-2024 The GmSSL Project. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
#include <gmssl/sdf.h>
#include <gmssl/sm4.h>
#include <gmssl/mem.h>
#include <gmssl/error.h>
#include "sdf.h"
#include "../sgd.h"
extern void *globalDeviceHandle;
static int sdf_sm4_cbc_encrypt_blocks(SDF_SM4_KEY *key,
const uint8_t iv[16], const uint8_t *in, size_t inlen, uint8_t *out)
{
unsigned int outlen;
int ret;
if ((ret = SDF_Encrypt(key->hSession, key->hKey, SGD_SM4_CBC,
(unsigned char *)iv, (unsigned char *)in, (unsigned int)inlen, out, &outlen)) != SDR_OK) {
error_print();
return -1;
}
return 1;
}
static int sdf_sm4_cbc_decrypt_blocks(SDF_SM4_KEY *key,
const uint8_t iv[16], const uint8_t *in, size_t inlen, uint8_t *out)
{
unsigned int outlen;
int ret;
if ((ret = SDF_Decrypt(key->hSession, key->hKey, SGD_SM4_CBC,
(unsigned char *)iv, (unsigned char *)in, (unsigned int)inlen, out, &outlen)) != SDR_OK) {
error_print();
return -1;
}
return 1;
}
static int sdf_sm4_cbc_padding_encrypt(SDF_SM4_KEY *key,
const uint8_t iv[16], const uint8_t *in, size_t inlen,
uint8_t *out, size_t *outlen)
{
uint8_t block[16];
size_t rem = inlen % 16;
int padding = 16 - inlen % 16;
if (in) {
memcpy(block, in + inlen - rem, rem);
}
memset(block + rem, padding, padding);
if (inlen/16) {
if (sdf_sm4_cbc_encrypt_blocks(key, iv, in, inlen/16, out) != 1) {
error_print();
return -1;
}
out += inlen - rem;
iv = out - 16;
}
if (sdf_sm4_cbc_encrypt_blocks(key, iv, block, 1, out) != 1) {
error_print();
return -1;
}
*outlen = inlen - rem + 16;
return 1;
}
static int sdf_sm4_cbc_padding_decrypt(SDF_SM4_KEY *key,
const uint8_t iv[16], const uint8_t *in, size_t inlen,
uint8_t *out, size_t *outlen)
{
uint8_t block[16];
size_t len = sizeof(block);
int padding;
if (inlen == 0) {
error_puts("warning: input lenght = 0");
return 0;
}
if (inlen%16 != 0 || inlen < 16) {
error_puts("invalid cbc ciphertext length");
return -1;
}
if (inlen > 16) {
if (sdf_sm4_cbc_decrypt_blocks(key, iv, in, inlen/16 - 1, out) != 1) {
error_print();
return -1;
}
iv = in + inlen - 32;
}
if (sdf_sm4_cbc_decrypt_blocks(key, iv, in + inlen - 16, 1, block) != 1) {
error_print();
return -1;
}
padding = block[15];
if (padding < 1 || padding > 16) {
error_print();
return -1;
}
len -= padding;
memcpy(out + inlen - 16, block, len);
*outlen = inlen - padding;
return 1;
}
int sm4_cbc_encrypt_init(SM4_CBC_CTX *ctx,
const uint8_t key[SM4_BLOCK_SIZE], const uint8_t iv[SM4_BLOCK_SIZE])
{
SDF_SM4_KEY *sdf_sm4_key = (SDF_SM4_KEY *)&ctx->sm4_key;
void *hSession = NULL;
void *hKey = NULL;
unsigned int uiIPKIndex = 1;
ECCCipher eccCipher;
int ret;
if (!ctx || !key || !iv) {
error_print();
return -1;
}
// OpenDevice
if (globalDeviceHandle == NULL) {
if ((ret = SDF_OpenDevice(&globalDeviceHandle)) != SDR_OK) {
error_print_msg("SDFerror: 0x%08X\n", ret);
return -1;
}
if (globalDeviceHandle == NULL) {
error_print();
return -1;
}
}
if ((ret = SDF_OpenSession(globalDeviceHandle, &hSession)) != SDR_OK) {
error_print_msg("SDFerror: 0x%08X\n", ret);
return -1;
}
// ImportKey
ret = SDF_InternalEncrypt_ECC(hSession, uiIPKIndex, SGD_SM2_3, (unsigned char *)key, 16, &eccCipher);
if (ret != SDR_OK) {
error_print_msg("SDF library: 0x%08X\n", ret);
return -1;
}
ret = SDF_ImportKeyWithISK_ECC(hSession, uiIPKIndex, &eccCipher, &hKey);
if (ret != SDR_OK) {
error_print_msg("SDF library: 0x%08X\n", ret);
return -1;
}
// save hSession and hKey into CTX
sdf_sm4_key->hSession = hSession;
sdf_sm4_key->hKey = hKey;
memcpy(ctx->iv, iv, SM4_BLOCK_SIZE);
memset(ctx->block, 0, SM4_BLOCK_SIZE);
ctx->block_nbytes = 0;
return 1;
}
int sm4_cbc_encrypt_update(SM4_CBC_CTX *ctx,
const uint8_t *in, size_t inlen, uint8_t *out, size_t *outlen)
{
SDF_SM4_KEY *sdf_sm4_key = (SDF_SM4_KEY *)&ctx->sm4_key;
size_t left;
size_t nblocks;
size_t len;
if (!ctx || !in || !out || !outlen) {
error_print();
return -1;
}
if (ctx->block_nbytes >= SM4_BLOCK_SIZE) {
error_print();
return -1;
}
*outlen = 0;
if (ctx->block_nbytes) {
left = SM4_BLOCK_SIZE - ctx->block_nbytes;
if (inlen < left) {
memcpy(ctx->block + ctx->block_nbytes, in, inlen);
ctx->block_nbytes += inlen;
return 1;
}
memcpy(ctx->block + ctx->block_nbytes, in, left);
if (sdf_sm4_cbc_encrypt_blocks(sdf_sm4_key, ctx->iv, ctx->block, 1, out) != 1) {
error_print();
return -1;
}
memcpy(ctx->iv, out, SM4_BLOCK_SIZE);
in += left;
inlen -= left;
out += SM4_BLOCK_SIZE;
*outlen += SM4_BLOCK_SIZE;
}
if (inlen >= SM4_BLOCK_SIZE) {
nblocks = inlen / SM4_BLOCK_SIZE;
len = nblocks * SM4_BLOCK_SIZE;
if (sdf_sm4_cbc_encrypt_blocks(sdf_sm4_key, ctx->iv, in, nblocks, out) != 1) {
error_print();
return -1;
}
memcpy(ctx->iv, out + len - SM4_BLOCK_SIZE, SM4_BLOCK_SIZE);
in += len;
inlen -= len;
out += len;
*outlen += len;
}
if (inlen) {
memcpy(ctx->block, in, inlen);
}
ctx->block_nbytes = inlen;
return 1;
}
int sm4_cbc_encrypt_finish(SM4_CBC_CTX *ctx, uint8_t *out, size_t *outlen)
{
SDF_SM4_KEY *sdf_sm4_key = (SDF_SM4_KEY *)&ctx->sm4_key;
if (!ctx || !out || !outlen) {
error_print();
return -1;
}
if (ctx->block_nbytes >= SM4_BLOCK_SIZE) {
error_print();
return -1;
}
if (sdf_sm4_cbc_padding_encrypt(sdf_sm4_key, ctx->iv, ctx->block, ctx->block_nbytes, out, outlen) != 1) {
error_print();
return -1;
}
SDF_CloseSession(sdf_sm4_key->hSession);
return 1;
}
// for SDF, encrypt/decrypt_init no difference
int sm4_cbc_decrypt_init(SM4_CBC_CTX *ctx,
const uint8_t key[SM4_BLOCK_SIZE], const uint8_t iv[SM4_BLOCK_SIZE])
{
if (sm4_cbc_encrypt_init(ctx, key, iv) != 1) {
error_print();
return -1;
}
return 1;
}
int sm4_cbc_decrypt_update(SM4_CBC_CTX *ctx,
const uint8_t *in, size_t inlen, uint8_t *out, size_t *outlen)
{
SDF_SM4_KEY *sdf_sm4_key = (SDF_SM4_KEY *)&ctx->sm4_key;
size_t left, len, nblocks;
if (!ctx || !in || !out || !outlen) {
error_print();
return -1;
}
if (ctx->block_nbytes > SM4_BLOCK_SIZE) {
error_print();
return -1;
}
*outlen = 0;
if (ctx->block_nbytes) {
left = SM4_BLOCK_SIZE - ctx->block_nbytes;
if (inlen <= left) {
memcpy(ctx->block + ctx->block_nbytes, in, inlen);
ctx->block_nbytes += inlen;
return 1;
}
memcpy(ctx->block + ctx->block_nbytes, in, left);
if (sdf_sm4_cbc_decrypt_blocks(sdf_sm4_key, ctx->iv, ctx->block, 1, out) != 1) {
error_print();
return -1;
}
memcpy(ctx->iv, ctx->block, SM4_BLOCK_SIZE);
in += left;
inlen -= left;
out += SM4_BLOCK_SIZE;
*outlen += SM4_BLOCK_SIZE;
}
if (inlen > SM4_BLOCK_SIZE) {
nblocks = (inlen-1) / SM4_BLOCK_SIZE;
len = nblocks * SM4_BLOCK_SIZE;
if (sdf_sm4_cbc_decrypt_blocks(sdf_sm4_key, ctx->iv, in, nblocks, out) != 1) {
error_print();
return -1;
}
memcpy(ctx->iv, in + len - SM4_BLOCK_SIZE, SM4_BLOCK_SIZE);
in += len;
inlen -= len;
out += len;
*outlen += len;
}
memcpy(ctx->block, in, inlen);
ctx->block_nbytes = inlen;
return 1;
}
int sm4_cbc_decrypt_finish(SM4_CBC_CTX *ctx, uint8_t *out, size_t *outlen)
{
SDF_SM4_KEY *sdf_sm4_key = (SDF_SM4_KEY *)&ctx->sm4_key;
if (!ctx || !out || !outlen) {
error_print();
return -1;
}
if (ctx->block_nbytes != SM4_BLOCK_SIZE) {
error_print();
return -1;
}
if (sdf_sm4_cbc_padding_decrypt(sdf_sm4_key, ctx->iv, ctx->block, SM4_BLOCK_SIZE, out, outlen) != 1) {
error_print();
return -1;
}
SDF_CloseSession(sdf_sm4_key->hSession);
return 1;
}
// copy from src/sm4_cbc.c
int sm4_cbc_padding_encrypt(const SM4_KEY *key, const uint8_t iv[16],
const uint8_t *in, size_t inlen,
uint8_t *out, size_t *outlen)
{
uint8_t block[16];
size_t rem = inlen % 16;
int padding = 16 - inlen % 16;
if (in) {
memcpy(block, in + inlen - rem, rem);
}
memset(block + rem, padding, padding);
if (inlen/16) {
sm4_cbc_encrypt_blocks(key, iv, in, inlen/16, out);
out += inlen - rem;
iv = out - 16;
}
sm4_cbc_encrypt_blocks(key, iv, block, 1, out);
*outlen = inlen - rem + 16;
return 1;
}
int sm4_cbc_padding_decrypt(const SM4_KEY *key, const uint8_t iv[16],
const uint8_t *in, size_t inlen,
uint8_t *out, size_t *outlen)
{
uint8_t block[16];
size_t len = sizeof(block);
int padding;
if (inlen == 0) {
error_puts("warning: input lenght = 0");
return 0;
}
if (inlen%16 != 0 || inlen < 16) {
error_puts("invalid cbc ciphertext length");
return -1;
}
if (inlen > 16) {
sm4_cbc_decrypt_blocks(key, iv, in, inlen/16 - 1, out);
iv = in + inlen - 32;
}
sm4_cbc_decrypt_blocks(key, iv, in + inlen - 16, 1, block);
padding = block[15];
if (padding < 1 || padding > 16) {
error_print();
return -1;
}
len -= padding;
memcpy(out + inlen - 16, block, len);
*outlen = inlen - padding;
return 1;
}