From a57193836bab289b63c3085218ca989feea670ce Mon Sep 17 00:00:00 2001 From: Zhi Guan Date: Tue, 3 Aug 2021 17:09:35 +0800 Subject: [PATCH] add sdf and skf --- include/gmssl/aes.h | 2 +- include/gmssl/error.h | 17 +- include/gmssl/hash_drbg.h | 2 - include/gmssl/md5.h | 19 +- include/gmssl/pbkdf2.h | 14 +- include/gmssl/pkcs8.h | 4 +- include/gmssl/sha1.h | 22 +- include/gmssl/sha2.h | 44 +- include/gmssl/sm3.h | 22 +- include/gmssl/tls.h | 3 + include/gmssl/zuc.h | 65 +- sdf/Makefile | 3 + sdf/README.md | 17 + sdf/sdf.h | 503 +++++++ sdf/sdf_ext.c | 292 ++++ sdf/sdf_ext.h | 92 ++ sdf/sdf_int.h | 461 ++++++ sdf/sdf_lib.c | 1608 +++++++++++++++++++++ sdf/sdf_meth.c | 143 ++ sdf/sdf_sansec.c | 371 +++++ sdf/sdf_sansec.h | 192 +++ {tools => sdf}/sdfutil.c | 255 ++-- sdf/sgd.h | 435 ++++++ skf/sgd.h | 438 ++++++ skf/skf.h | 750 ++++++++++ skf/skf_ext.c | 606 ++++++++ skf/skf_ext.h | 129 ++ skf/skf_int.h | 618 +++++++++ skf/skf_lib.c | 2772 +++++++++++++++++++++++++++++++++++++ skf/skf_meth.c | 172 +++ skf/skf_prn.c | 373 +++++ skf/skf_wisec.c | 200 +++ skf/skf_wisec.h | 157 +++ {tools => skf}/skfutil.c | 0 src/aes.c | 10 +- src/aes_modes.c | 10 +- src/asn1.c | 27 +- src/digest.c | 2 +- src/endian.h | 16 +- src/gf128.c | 3 +- src/hash_drbg.c | 13 +- src/hex.c | 15 +- src/md5.c | 133 +- src/mem.h | 2 + src/oid.c | 7 +- src/pbkdf2.c | 4 +- src/pkcs8.c | 8 +- src/sha1.c | 145 +- src/sha256.c | 155 +-- src/sm2_algo.c | 21 +- src/sm2_asn1.c | 4 +- src/sm3.c | 328 +++-- src/sm3_hmac.c | 22 +- src/sm4_modes.c | 10 +- src/tlcp.c | 12 +- src/tls.c | 32 +- src/tls12.c | 10 +- src/tls13.c | 6 +- src/tls_trace.c | 4 +- src/x509_algor.c | 4 +- src/x509_asn1.c | 16 +- src/x509_ext.c | 4 +- src/zuc_core.c | 5 + tests/asn1test.c | 23 +- tools/certverify.c | 2 +- tools/digest.c | 1 - tools/hmac.c | 2 +- tools/sm2decrypt.c | 2 +- tools/sm2sign.c | 2 +- tools/sm3sum.c | 3 +- tools/tlcp_client.c | 1 - 71 files changed, 11100 insertions(+), 765 deletions(-) create mode 100644 sdf/Makefile create mode 100644 sdf/README.md create mode 100644 sdf/sdf.h create mode 100644 sdf/sdf_ext.c create mode 100644 sdf/sdf_ext.h create mode 100644 sdf/sdf_int.h create mode 100644 sdf/sdf_lib.c create mode 100644 sdf/sdf_meth.c create mode 100644 sdf/sdf_sansec.c create mode 100644 sdf/sdf_sansec.h rename {tools => sdf}/sdfutil.c (57%) create mode 100644 sdf/sgd.h create mode 100644 skf/sgd.h create mode 100644 skf/skf.h create mode 100644 skf/skf_ext.c create mode 100644 skf/skf_ext.h create mode 100644 skf/skf_int.h create mode 100644 skf/skf_lib.c create mode 100644 skf/skf_meth.c create mode 100644 skf/skf_prn.c create mode 100644 skf/skf_wisec.c create mode 100644 skf/skf_wisec.h rename {tools => skf}/skfutil.c (100%) diff --git a/include/gmssl/aes.h b/include/gmssl/aes.h index 161ca191..2529f927 100644 --- a/include/gmssl/aes.h +++ b/include/gmssl/aes.h @@ -76,7 +76,7 @@ extern "C" { typedef struct { uint32_t rk[4 * (AES_MAX_ROUNDS + 1)]; - int rounds; + size_t rounds; } AES_KEY; int aes_set_encrypt_key(AES_KEY *aes_key, const uint8_t *key, size_t keylen); diff --git a/include/gmssl/error.h b/include/gmssl/error.h index 9a649399..e119a48a 100644 --- a/include/gmssl/error.h +++ b/include/gmssl/error.h @@ -54,15 +54,24 @@ #include #include -#define error_print(fmt, args...) \ - fprintf(stderr, "error: %s %d: %s: " fmt "\n", __FILE__, __LINE__, __FUNCTION__, ##args) - - #ifdef __cplusplus extern "C" { #endif + +#define DEBUG 1 + +#define error_print() \ + do { if (DEBUG) fprintf(stderr, "%s:%d:%s():\n",__FILE__, __LINE__, __func__); } while (0) + +#define error_print_msg(fmt, ...) \ + do { if (DEBUG) fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, __LINE__, __func__, __VA_ARGS__); } while (0) + +#define error_puts(str) \ + do { if (DEBUG) fprintf(stderr, "%s: %d: %s: %s", __FILE__, __LINE__, __func__, str); } while (0) + + void print_der(const uint8_t *in, size_t inlen); void print_bytes(const uint8_t *in, size_t inlen); void print_nodes(const uint32_t *in, size_t inlen); diff --git a/include/gmssl/hash_drbg.h b/include/gmssl/hash_drbg.h index 81880892..c539bacc 100644 --- a/include/gmssl/hash_drbg.h +++ b/include/gmssl/hash_drbg.h @@ -109,8 +109,6 @@ int hash_drbg_generate(HASH_DRBG *drbg, const uint8_t *additional, size_t additional_len, size_t outlen, uint8_t *out); -void hash_drbg_cleanup(HASH_DRBG *drbg); - #ifdef __cplusplus } diff --git a/include/gmssl/md5.h b/include/gmssl/md5.h index bb343564..ed1a4388 100755 --- a/include/gmssl/md5.h +++ b/include/gmssl/md5.h @@ -50,32 +50,33 @@ #ifndef GMSSL_MD5_H #define GMSSL_MD5_H -#define MD5_IS_BIG_ENDIAN 0 - -#define MD5_DIGEST_SIZE 16 -#define MD5_BLOCK_SIZE 64 #include #include -#include + #ifdef __cplusplus extern "C" { #endif +#define MD5_IS_BIG_ENDIAN 0 + +#define MD5_DIGEST_SIZE 16 +#define MD5_BLOCK_SIZE 64 + + typedef struct { uint32_t state[4]; uint64_t nblocks; /* num of processed blocks */ - unsigned char block[64]; /* buffer */ - int num; /* buffered bytes in |block| */ + uint8_t block[64]; /* buffer */ + size_t num; /* buffered bytes in |block| */ } MD5_CTX; void md5_init(MD5_CTX *ctx); -void md5_update(MD5_CTX *ctx, const uint8_t* data, size_t datalen); +void md5_update(MD5_CTX *ctx, const uint8_t *data, size_t datalen); void md5_finish(MD5_CTX *ctx, uint8_t dgst[MD5_DIGEST_SIZE]); -void md5_compress(uint32_t state[4], const uint8_t block[MD5_BLOCK_SIZE]); void md5_digest(const uint8_t *data, size_t datalen, uint8_t dgst[MD5_DIGEST_SIZE]); diff --git a/include/gmssl/pbkdf2.h b/include/gmssl/pbkdf2.h index 70b07804..25564385 100644 --- a/include/gmssl/pbkdf2.h +++ b/include/gmssl/pbkdf2.h @@ -49,28 +49,26 @@ #ifndef GMSSL_PBKDF2_H #define GMSSL_PBKDF2_H - #include #include #include +#include #include +#ifdef __cplusplus +extern "C" { +#endif + #define PBKDF2_MIN_ITER 10000 #define PBKDF2_MIN_SALT_SIZE 64 #define PBKDF2_DEFAULT_SALT_SIZE 8 -#ifdef __cplusplus -extern "C" { -#endif - - int pbkdf2_genkey(const DIGEST *digest, const char *pass, size_t passlen, const uint8_t *salt, size_t saltlen, - unsigned int count, size_t outlen, uint8_t *out); - + size_t count, size_t outlen, uint8_t *out); #ifdef __cplusplus diff --git a/include/gmssl/pkcs8.h b/include/gmssl/pkcs8.h index a95fbe53..0613a13a 100644 --- a/include/gmssl/pkcs8.h +++ b/include/gmssl/pkcs8.h @@ -49,10 +49,10 @@ #ifndef GMSSL_PKCS8_H #define GMSSL_PKCS8_H - #include #include #include +#include #include #include @@ -60,6 +60,7 @@ extern "C" { #endif + // EncryptedPrivateKeyInfo int sm2_enced_private_key_info_to_der(const SM2_KEY *key, const char *pass, uint8_t **out, size_t *outlen); int sm2_enced_private_key_info_from_der(SM2_KEY *key, const uint8_t **attrs, size_t *attrslen, const char *pass, const uint8_t **in, size_t *inlen); @@ -160,7 +161,6 @@ int pkcs8_enced_private_key_info_from_der( const uint8_t **in, size_t *inlen); - #ifdef __cplusplus } #endif diff --git a/include/gmssl/sha1.h b/include/gmssl/sha1.h index b63d68ed..b0ea1aee 100755 --- a/include/gmssl/sha1.h +++ b/include/gmssl/sha1.h @@ -46,38 +46,36 @@ * OF THE POSSIBILITY OF SUCH DAMAGE. */ - #ifndef GMSSL_SHA1_H #define GMSSL_SHA1_H -#define SHA1_IS_BIG_ENDIAN 1 - -#define SHA1_DIGEST_LENGTH 20 -#define SHA1_BLOCK_SIZE 64 -#define SHA1_STATE_WORDS (SHA1_DIGEST_LENGTH/sizeof(uint32_t)) - #include #include #include - #ifdef __cplusplus extern "C" { #endif +#define SHA1_IS_BIG_ENDIAN 1 + +#define SHA1_DIGEST_SIZE 20 +#define SHA1_BLOCK_SIZE 64 +#define SHA1_STATE_WORDS (SHA1_DIGEST_SIZE/sizeof(uint32_t)) + + typedef struct { uint32_t state[SHA1_STATE_WORDS]; uint64_t nblocks; /* num of processed blocks */ uint8_t block[SHA1_BLOCK_SIZE]; /* buffer */ - int num; /* buffered bytes in |block| */ + size_t num; /* buffered bytes in |block| */ } SHA1_CTX; void sha1_init(SHA1_CTX *ctx); void sha1_update(SHA1_CTX *ctx, const uint8_t *data, size_t datalen); -void sha1_finish(SHA1_CTX *ctx, uint8_t dgst[SHA1_DIGEST_LENGTH]); -void sha1_compress(uint32_t state[SHA1_STATE_WORDS], const uint8_t block[SHA1_BLOCK_SIZE]); -void sha1_digest(const uint8_t *data, size_t datalen, uint8_t dgst[SHA1_DIGEST_LENGTH]); +void sha1_finish(SHA1_CTX *ctx, uint8_t dgst[SHA1_DIGEST_SIZE]); +void sha1_digest(const uint8_t *data, size_t datalen, uint8_t dgst[SHA1_DIGEST_SIZE]); #ifdef __cplusplus diff --git a/include/gmssl/sha2.h b/include/gmssl/sha2.h index 6f7bde92..00040c7b 100755 --- a/include/gmssl/sha2.h +++ b/include/gmssl/sha2.h @@ -50,24 +50,6 @@ #ifndef GMSSL_SHA2_H #define GMSSL_SHA2_H -#define SHA2_IS_BIG_ENDIAN 1 - -#define SHA224_DIGEST_SIZE 28 -#define SHA256_DIGEST_SIZE 32 -#define SHA384_DIGEST_SIZE 48 -#define SHA512_DIGEST_SIZE 64 - -#define SHA224_BLOCK_SIZE 64 -#define SHA256_BLOCK_SIZE 64 -#define SHA384_BLOCK_SIZE 128 -#define SHA512_BLOCK_SIZE 128 - -#define SHA224_STATE_WORDS 8 -#define SHA256_STATE_WORDS 8 -#define SHA384_STATE_WORDS 8 -#define SHA512_STATE_WORDS 8 - - #include #include #include @@ -77,6 +59,13 @@ extern "C" { #endif +#define SHA2_IS_BIG_ENDIAN 1 + + +#define SHA224_DIGEST_SIZE 28 +#define SHA224_BLOCK_SIZE 64 +#define SHA224_STATE_WORDS 8 + typedef struct { uint32_t state[SHA224_STATE_WORDS]; uint64_t nblocks; @@ -87,10 +76,14 @@ typedef struct { void sha224_init(SHA224_CTX *ctx); void sha224_update(SHA224_CTX *ctx, const unsigned char* data, size_t datalen); void sha224_finish(SHA224_CTX *ctx, unsigned char dgst[SHA224_DIGEST_SIZE]); -void sha224_compress(uint32_t dgst[8], const unsigned char block[SHA224_BLOCK_SIZE]); void sha224_digest(const unsigned char *data, size_t datalen, unsigned char dgst[SHA224_DIGEST_SIZE]); + +#define SHA256_DIGEST_SIZE 32 +#define SHA256_BLOCK_SIZE 64 +#define SHA256_STATE_WORDS 8 + typedef struct { uint32_t state[8]; uint64_t nblocks; @@ -101,10 +94,14 @@ typedef struct { void sha256_init(SHA256_CTX *ctx); void sha256_update(SHA256_CTX *ctx, const unsigned char* data, size_t datalen); void sha256_finish(SHA256_CTX *ctx, unsigned char dgst[SHA256_DIGEST_SIZE]); -void sha256_compress(uint32_t dgst[8], const unsigned char block[SHA256_BLOCK_SIZE]); void sha256_digest(const unsigned char *data, size_t datalen, unsigned char dgst[SHA256_DIGEST_SIZE]); + +#define SHA384_DIGEST_SIZE 48 +#define SHA384_BLOCK_SIZE 128 +#define SHA384_STATE_WORDS 8 + typedef struct { uint64_t state[8]; uint64_t nblocks; @@ -115,10 +112,14 @@ typedef struct { void sha384_init(SHA384_CTX *ctx); void sha384_update(SHA384_CTX *ctx, const unsigned char* data, size_t datalen); void sha384_finish(SHA384_CTX *ctx, unsigned char dgst[SHA384_DIGEST_SIZE]); -void sha384_compress(uint64_t dgst[8], const unsigned char block[SHA384_BLOCK_SIZE]); void sha384_digest(const unsigned char *data, size_t datalen, unsigned char dgst[SHA384_DIGEST_SIZE]); + +#define SHA512_DIGEST_SIZE 64 +#define SHA512_BLOCK_SIZE 128 +#define SHA512_STATE_WORDS 8 + typedef struct { uint64_t state[8]; uint64_t nblocks; @@ -129,7 +130,6 @@ typedef struct { void sha512_init(SHA512_CTX *ctx); void sha512_update(SHA512_CTX *ctx, const unsigned char* data, size_t datalen); void sha512_finish(SHA512_CTX *ctx, unsigned char dgst[SHA512_DIGEST_SIZE]); -void sha512_compress(uint64_t dgst[8], const unsigned char block[SHA512_BLOCK_SIZE]); void sha512_digest(const unsigned char *data, size_t datalen, unsigned char dgst[SHA512_DIGEST_SIZE]); diff --git a/include/gmssl/sm3.h b/include/gmssl/sm3.h index 88e2eee1..fc69010c 100755 --- a/include/gmssl/sm3.h +++ b/include/gmssl/sm3.h @@ -49,34 +49,32 @@ #ifndef GMSSL_SM3_H #define GMSSL_SM3_H -#define SM3_IS_BIG_ENDIAN 1 - -#define SM3_DIGEST_SIZE 32 -#define SM3_BLOCK_SIZE 64 -#define SM3_STATE_WORDS 8 -#define SM3_HMAC_SIZE (SM3_DIGEST_SIZE) - #include #include -#include - #ifdef __cplusplus extern "C" { #endif +#define SM3_IS_BIG_ENDIAN 1 + +#define SM3_DIGEST_SIZE 32 +#define SM3_BLOCK_SIZE 64 +#define SM3_STATE_WORDS 8 +#define SM3_HMAC_SIZE (SM3_DIGEST_SIZE) + + typedef struct { uint32_t digest[SM3_STATE_WORDS]; uint64_t nblocks; uint8_t block[SM3_BLOCK_SIZE]; - int num; + size_t num; } SM3_CTX; void sm3_init(SM3_CTX *ctx); void sm3_update(SM3_CTX *ctx, const uint8_t *data, size_t datalen); void sm3_finish(SM3_CTX *ctx, uint8_t dgst[SM3_DIGEST_SIZE]); -void sm3_compress(uint32_t dgst[SM3_STATE_WORDS], const uint8_t block[SM3_BLOCK_SIZE]); void sm3_digest(const uint8_t *data, size_t datalen, uint8_t dgst[SM3_DIGEST_SIZE]); @@ -88,12 +86,10 @@ typedef struct { void sm3_hmac_init(SM3_HMAC_CTX *ctx, const uint8_t *key, size_t keylen); void sm3_hmac_update(SM3_HMAC_CTX *ctx, const uint8_t *data, size_t datalen); void sm3_hmac_finish(SM3_HMAC_CTX *ctx, uint8_t mac[SM3_HMAC_SIZE]); -void sm3_hmac_reset(SM3_HMAC_CTX *ctx); void sm3_hmac(const uint8_t *key, size_t keylen, const uint8_t *data, size_t datalen, uint8_t mac[SM3_HMAC_SIZE]); -int sm3_hmac_finish_and_verify(SM3_HMAC_CTX *ctx, const uint8_t mac[SM3_HMAC_SIZE]); #ifdef __cplusplus } diff --git a/include/gmssl/tls.h b/include/gmssl/tls.h index 4ff5eb3a..3d3ca8ea 100644 --- a/include/gmssl/tls.h +++ b/include/gmssl/tls.h @@ -701,6 +701,9 @@ int tls13_derive_secret(const uint8_t secret[32], const char *label, const DIGES +int tls_shutdown(TLS_CONNECT *conn); + + #define tls_trace printf diff --git a/include/gmssl/zuc.h b/include/gmssl/zuc.h index aabea41e..4ed5a0b2 100755 --- a/include/gmssl/zuc.h +++ b/include/gmssl/zuc.h @@ -49,9 +49,20 @@ #ifndef GMSSL_ZUC_H #define GMSSL_ZUC_H + #include #include + +#ifdef __cplusplus +extern "C" { +#endif + + +# define ZUC_KEY_SIZE 16 +# define ZUC_IV_SIZE 16 +# define ZUC_MAC_SIZE 4 + typedef uint32_t ZUC_BIT; typedef uint32_t ZUC_UINT5; typedef uint8_t ZUC_UINT6; @@ -59,76 +70,68 @@ typedef uint32_t ZUC_UINT15; typedef uint32_t ZUC_UINT31; typedef uint32_t ZUC_UINT32; -#ifdef __cplusplus -extern "C" { -#endif - - -# define ZUC_KEY_LENGTH 16 -# define ZUC_IV_LENGTH 16 -# define ZUC_MAC_LENGTH 4 - - typedef struct ZUC_KEY_st { ZUC_UINT31 LFSR[16]; ZUC_UINT32 R1; ZUC_UINT32 R2; } ZUC_KEY; -void zuc_set_key(ZUC_KEY *key, const unsigned char user_key[16], const unsigned char iv[16]); +void zuc_set_key(ZUC_KEY *key, const uint8_t user_key[16], const uint8_t iv[16]); void zuc_generate_keystream(ZUC_KEY *key, size_t nwords, ZUC_UINT32 *words); ZUC_UINT32 zuc_generate_keyword(ZUC_KEY *key); + typedef struct ZUC_MAC_CTX_st { ZUC_UINT31 LFSR[16]; ZUC_UINT32 R1; ZUC_UINT32 R2; ZUC_UINT32 T; ZUC_UINT32 K0; - unsigned char buf[4]; - int buflen; + uint8_t buf[4]; + size_t buflen; } ZUC_MAC_CTX; -void zuc_mac_init(ZUC_MAC_CTX *ctx, const unsigned char key[16], const unsigned char iv[16]); -void zuc_mac_update(ZUC_MAC_CTX *ctx, const unsigned char *data, size_t len); -void zuc_mac_finish(ZUC_MAC_CTX *ctx, const unsigned char *data, size_t nbits, unsigned char mac[4]); +void zuc_mac_init(ZUC_MAC_CTX *ctx, const uint8_t key[16], const uint8_t iv[16]); +void zuc_mac_update(ZUC_MAC_CTX *ctx, const uint8_t *data, size_t len); +void zuc_mac_finish(ZUC_MAC_CTX *ctx, const uint8_t *data, size_t nbits, uint8_t mac[4]); void zuc_eea_encrypt(const ZUC_UINT32 *in, ZUC_UINT32 *out, size_t nbits, - const unsigned char key[16], ZUC_UINT32 count, ZUC_UINT5 bearer, + const uint8_t key[16], ZUC_UINT32 count, ZUC_UINT5 bearer, ZUC_BIT direction); ZUC_UINT32 zuc_eia_generate_mac(const ZUC_UINT32 *data, size_t nbits, - const unsigned char user_key[16], ZUC_UINT32 count, ZUC_UINT5 bearer, + const uint8_t user_key[16], ZUC_UINT32 count, ZUC_UINT5 bearer, ZUC_BIT direction); -# define ZUC256_KEY_LENGTH 32 -# define ZUC256_IV_LENGTH 23 -# define ZUC256_MAC32_LENGTH 4 -# define ZUC256_MAC64_LENGTH 8 -# define ZUC256_MAC128_LENGTH 16 -# define ZUC256_MIN_MAC_LENGTH ZUC256_MAC32_LENGTH -# define ZUC256_MAX_MAC_LENGTH ZUC256_MAC128_LENGTH + +# define ZUC256_KEY_SIZE 32 +# define ZUC256_IV_SIZE 23 +# define ZUC256_MAC32_SIZE 4 +# define ZUC256_MAC64_SIZE 8 +# define ZUC256_MAC128_SIZE 16 +# define ZUC256_MIN_MAC_SIZE ZUC256_MAC32_SIZE +# define ZUC256_MAX_MAC_SIZE ZUC256_MAC128_SIZE typedef ZUC_KEY ZUC256_KEY; -void zuc256_set_key(ZUC256_KEY *key, const unsigned char user_key[32], - const unsigned char iv[23]); +void zuc256_set_key(ZUC256_KEY *key, const uint8_t user_key[32], const uint8_t iv[23]); #define zuc256_generate_keystream(k,n,out) zuc_generate_keystream(k,n,out) #define zuc256_generate_keyword(k) zuc_generate_keyword(k) + typedef struct ZUC256_MAC_CTX_st { ZUC_UINT31 LFSR[16]; ZUC_UINT32 R1; ZUC_UINT32 R2; ZUC_UINT32 T[4]; ZUC_UINT32 K0[4]; - unsigned char buf[4]; + uint8_t buf[4]; int buflen; int macbits; } ZUC256_MAC_CTX; -void zuc256_mac_init(ZUC256_MAC_CTX *ctx, const unsigned char key[32], const unsigned char iv[23], int macbits); -void zuc256_mac_update(ZUC256_MAC_CTX *ctx, const unsigned char *data, size_t len); -void zuc256_mac_finish(ZUC256_MAC_CTX *ctx, const unsigned char *data, size_t nbits, unsigned char *mac); +void zuc256_mac_init(ZUC256_MAC_CTX *ctx, const uint8_t key[32], const uint8_t iv[23], int macbits); +void zuc256_mac_update(ZUC256_MAC_CTX *ctx, const uint8_t *data, size_t len); +void zuc256_mac_finish(ZUC256_MAC_CTX *ctx, const uint8_t *data, size_t nbits, uint8_t *mac); #ifdef __cplusplus diff --git a/sdf/Makefile b/sdf/Makefile new file mode 100644 index 00000000..5618ad3d --- /dev/null +++ b/sdf/Makefile @@ -0,0 +1,3 @@ +all: + gcc -I ../include *.c -o sdfutil + diff --git a/sdf/README.md b/sdf/README.md new file mode 100644 index 00000000..102a6f67 --- /dev/null +++ b/sdf/README.md @@ -0,0 +1,17 @@ + +# SDF + +SDF模块用于支持SDF密码卡硬件。目前这部分代码完全是从GmSSL 2.x中移植过来,并移除了对OpenSSL的依赖。 + +源文件包括: + +* `sdf.h`, `sgd.h`,这两个头文件来自于SDF的标准 +* `sdf_ext.h`,即原来的`gmsdf.h`,为SDF接口增加了一些辅助功能。实现在`sdf_ext.c`中。 +* `sdf_int.h`,`sdf_meth.c`实现了对SDF动态库函数的调用,将SDF动态库转换为一个SDF的对象(包含函数指针) +* `sdf_lib.c`,调用SDF_METHOD,实现了sdf.h的功能 +* `sdf_sansec.h/c`,针对三未信安密码卡非标准功能的支持 +* `sdfutil.c`,一个访问SDF密码卡的命令行程序 + +后续工作: + +* 在gmssl的API中融入对SDF的支持。以相对ENGINE更轻量级的方式来实现。 diff --git a/sdf/sdf.h b/sdf/sdf.h new file mode 100644 index 00000000..da699665 --- /dev/null +++ b/sdf/sdf.h @@ -0,0 +1,503 @@ +/* + * Copyright (c) 2014 - 2021 The GmSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the GmSSL Project. + * (http://gmssl.org/)" + * + * 4. The name "GmSSL Project" must not be used to endorse or promote + * products derived from this software without prior written + * permission. For written permission, please contact + * guanzhi1980@gmail.com. + * + * 5. Products derived from this software may not be called "GmSSL" + * nor may "GmSSL" appear in their names without prior written + * permission of the GmSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the GmSSL Project + * (http://gmssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * SDF API is a cryptographic API for PCI-E cards defined in standard + * GM/T 0018-2012: Interface Specifications of Cryptography Device Application + * + * Note: this header file follows the specification of GM/T 0018-2012. As we + * know, some vendors provide header files with some differences, especially + * the definations of data structures. So be sure to check the file provided by + * vendors and compare with this one. + * + * The implementations of SDF API from different vendors might have different + * behaviors on the same function. The comments in this file will show + * information and warnings on these issues. If the application developer use + * the GmSSL implementation, see `crypto/gmapi/sdf_lcl.h` for more information. + */ + +#ifndef HEADER_SDF_H +#define HEADER_SDF_H + +#include +#include "sgd.h" + + +#ifdef __cplusplus +extern "C" { +#endif + + + +#pragma pack(1) +typedef struct DeviceInfo_st { + unsigned char IssuerName[40]; + unsigned char DeviceName[16]; + unsigned char DeviceSerial[16]; /* 8-char date + + * 3-char batch num + + * 5-char serial num + */ + unsigned int DeviceVersion; + unsigned int StandardVersion; + unsigned int AsymAlgAbility[2]; /* AsymAlgAbility[0] = algors + * AsymAlgAbility[1] = modulus lens + */ + unsigned int SymAlgAbility; + unsigned int HashAlgAbility; + unsigned int BufferSize; +} DEVICEINFO; + +typedef struct RSArefPublicKey_st { + unsigned int bits; + unsigned char m[RSAref_MAX_LEN]; + unsigned char e[RSAref_MAX_LEN]; +} RSArefPublicKey; + +typedef struct RSArefPrivateKey_st { + unsigned int bits; + unsigned char m[RSAref_MAX_LEN]; + unsigned char e[RSAref_MAX_LEN]; + unsigned char d[RSAref_MAX_LEN]; + unsigned char prime[2][RSAref_MAX_PLEN]; + unsigned char pexp[2][RSAref_MAX_PLEN]; + unsigned char coef[RSAref_MAX_PLEN]; +} RSArefPrivateKey; + +typedef struct ECCrefPublicKey_st { + unsigned int bits; + unsigned char x[ECCref_MAX_LEN]; + unsigned char y[ECCref_MAX_LEN]; +} ECCrefPublicKey; + +typedef struct ECCrefPrivateKey_st { + unsigned int bits; + unsigned char K[ECCref_MAX_LEN]; +} ECCrefPrivateKey; + +typedef struct ECCCipher_st { + unsigned char x[ECCref_MAX_LEN]; + unsigned char y[ECCref_MAX_LEN]; + unsigned char M[32]; + unsigned int L; + unsigned char C[1]; +} ECCCipher; + +typedef struct ECCSignature_st { + unsigned char r[ECCref_MAX_LEN]; + unsigned char s[ECCref_MAX_LEN]; +} ECCSignature; + +typedef struct SDF_ENVELOPEDKEYBLOB { + unsigned long Version; + unsigned long ulSymmAlgID; + ECCCipher ECCCipehrBlob; + ECCrefPublicKey PubKey; + unsigned char cbEncryptedPrivKey[64]; +} EnvelopedKeyBlob, *PEnvelopedKeyBlob; +#pragma pack() + +int SDF_OpenDevice( + void **phDeviceHandle); + +int SDF_CloseDevice( + void *hDeviceHandle); + +int SDF_OpenSession( + void *hDeviceHandle, + void **phSessionHandle); + +int SDF_CloseSession( + void *hSessionHandle); + +int SDF_GetDeviceInfo( + void *hSessionHandle, + DEVICEINFO *pstDeviceInfo); + +int SDF_GenerateRandom( + void *hSessionHandle, + unsigned int uiLength, + unsigned char *pucRandom); + +int SDF_GetPrivateKeyAccessRight( + void *hSessionHandle, + unsigned int uiKeyIndex, + unsigned char *pucPassword, + unsigned int uiPwdLength); + +int SDF_ReleasePrivateKeyAccessRight( + void *hSessionHandle, + unsigned int uiKeyIndex); + +int SDF_ExportSignPublicKey_RSA( + void *hSessionHandle, + unsigned int uiKeyIndex, + RSArefPublicKey *pucPublicKey); + +int SDF_ExportEncPublicKey_RSA( + void *hSessionHandle, + unsigned int uiKeyIndex, + RSArefPublicKey *pucPublicKey); + +int SDF_GenerateKeyPair_RSA( + void *hSessionHandle, + unsigned int uiKeyBits, + RSArefPublicKey *pucPublicKey, + RSArefPrivateKey *pucPrivateKey); + +int SDF_GenerateKeyWithIPK_RSA( + void *hSessionHandle, + unsigned int uiIPKIndex, + unsigned int uiKeyBits, + unsigned char *pucKey, + unsigned int *puiKeyLength, + void **phKeyHandle); + +int SDF_GenerateKeyWithEPK_RSA( + void *hSessionHandle, + unsigned int uiKeyBits, + RSArefPublicKey *pucPublicKey, + unsigned char *pucKey, + unsigned int *puiKeyLength, + void **phKeyHandle); + +int SDF_ImportKeyWithISK_RSA( + void *hSessionHandle, + unsigned int uiISKIndex, + unsigned char *pucKey, + unsigned int uiKeyLength, + void **phKeyHandle); + +int SDF_ExchangeDigitEnvelopeBaseOnRSA( + void *hSessionHandle, + unsigned int uiKeyIndex, + RSArefPublicKey *pucPublicKey, + unsigned char *pucDEInput, + unsigned int uiDELength, + unsigned char *pucDEOutput, + unsigned int *puiDELength); + +int SDF_ExportSignPublicKey_ECC( + void *hSessionHandle, + unsigned int uiKeyIndex, + ECCrefPublicKey *pucPublicKey); + +int SDF_ExportEncPublicKey_ECC( + void *hSessionHandle, + unsigned int uiKeyIndex, + ECCrefPublicKey *pucPublicKey); + +int SDF_GenerateKeyPair_ECC( + void *hSessionHandle, + unsigned int uiAlgID, + unsigned int uiKeyBits, + ECCrefPublicKey *pucPublicKey, + ECCrefPrivateKey *pucPrivateKey); + +int SDF_GenerateKeyWithIPK_ECC( + void *hSessionHandle, + unsigned int uiIPKIndex, + unsigned int uiKeyBits, + ECCCipher *pucKey, + void **phKeyHandle); + +int SDF_GenerateKeyWithEPK_ECC( + void *hSessionHandle, + unsigned int uiKeyBits, + unsigned int uiAlgID, + ECCrefPublicKey *pucPublicKey, + ECCCipher *pucKey, + void **phKeyHandle); + +int SDF_ImportKeyWithISK_ECC( + void *hSessionHandle, + unsigned int uiISKIndex, + ECCCipher *pucKey, + void **phKeyHandle); + +int SDF_GenerateAgreementDataWithECC( + void *hSessionHandle, + unsigned int uiISKIndex, + unsigned int uiKeyBits, + unsigned char *pucSponsorID, + unsigned int uiSponsorIDLength, + ECCrefPublicKey *pucSponsorPublicKey, + ECCrefPublicKey *pucSponsorTmpPublicKey, + void **phAgreementHandle); + +int SDF_GenerateKeyWithECC( + void *hSessionHandle, + unsigned char *pucResponseID, + unsigned int uiResponseIDLength, + ECCrefPublicKey *pucResponsePublicKey, + ECCrefPublicKey *pucResponseTmpPublicKey, + void *hAgreementHandle, + void **phKeyHandle); + +int SDF_GenerateAgreementDataAndKeyWithECC( + void *hSessionHandle, + unsigned int uiISKIndex, + unsigned int uiKeyBits, + unsigned char *pucResponseID, + unsigned int uiResponseIDLength, + unsigned char *pucSponsorID, + unsigned int uiSponsorIDLength, + ECCrefPublicKey *pucSponsorPublicKey, + ECCrefPublicKey *pucSponsorTmpPublicKey, + ECCrefPublicKey *pucResponsePublicKey, + ECCrefPublicKey *pucResponseTmpPublicKey, + void **phKeyHandle); + +int SDF_ExchangeDigitEnvelopeBaseOnECC( + void *hSessionHandle, + unsigned int uiKeyIndex, + unsigned int uiAlgID, + ECCrefPublicKey *pucPublicKey, + ECCCipher *pucEncDataIn, + ECCCipher *pucEncDataOut); + +int SDF_GenerateKeyWithKEK( + void *hSessionHandle, + unsigned int uiKeyBits, + unsigned int uiAlgID, + unsigned int uiKEKIndex, + unsigned char *pucKey, + unsigned int *puiKeyLength, + void **phKeyHandle); + +int SDF_ImportKeyWithKEK( + void *hSessionHandle, + unsigned int uiAlgID, + unsigned int uiKEKIndex, + unsigned char *pucKey, + unsigned int uiKeyLength, + void **phKeyHandle); + +int SDF_DestroyKey( + void *hSessionHandle, + void *hKeyHandle); + +int SDF_ExternalPublicKeyOperation_RSA( + void *hSessionHandle, + RSArefPublicKey *pucPublicKey, + unsigned char *pucDataInput, + unsigned int uiInputLength, + unsigned char *pucDataOutput, + unsigned int *puiOutputLength); + +int SDF_InternalPublicKeyOperation_RSA( + void *hSessionHandle, + unsigned int uiKeyIndex, + unsigned char *pucDataInput, + unsigned int uiInputLength, + unsigned char *pucDataOutput, + unsigned int *puiOutputLength); + +int SDF_InternalPrivateKeyOperation_RSA( + void *hSessionHandle, + unsigned int uiKeyIndex, + unsigned char *pucDataInput, + unsigned int uiInputLength, + unsigned char *pucDataOutput, + unsigned int *puiOutputLength); + +int SDF_ExternalVerify_ECC( + void *hSessionHandle, + unsigned int uiAlgID, + ECCrefPublicKey *pucPublicKey, + unsigned char *pucDataInput, + unsigned int uiInputLength, + ECCSignature *pucSignature); + +int SDF_InternalSign_ECC( + void *hSessionHandle, + unsigned int uiISKIndex, + unsigned char *pucData, + unsigned int uiDataLength, + ECCSignature *pucSignature); + +int SDF_InternalVerify_ECC( + void *hSessionHandle, + unsigned int uiIPKIndex, + unsigned char *pucData, + unsigned int uiDataLength, + ECCSignature *pucSignature); + +int SDF_ExternalEncrypt_ECC( + void *hSessionHandle, + unsigned int uiAlgID, + ECCrefPublicKey *pucPublicKey, + unsigned char *pucData, + unsigned int uiDataLength, + ECCCipher *pucEncData); + +int SDF_InternalEncrypt_ECC( + void *hSessionHandle, + unsigned int uiIPKIndex, + unsigned int uiAlgID, + unsigned char *pucData, + unsigned int uiDataLength, + ECCCipher *pucEncData); + +int SDF_InternalDecrypt_ECC( + void *hSessionHandle, + unsigned int uiISKIndex, + unsigned int uiAlgID, + ECCCipher *pucEncData, + unsigned char *pucData, + unsigned int *uiDataLength); + +int SDF_Encrypt( + void *hSessionHandle, + void *hKeyHandle, + unsigned int uiAlgID, + unsigned char *pucIV, + unsigned char *pucData, + unsigned int uiDataLength, + unsigned char *pucEncData, + unsigned int *puiEncDataLength); + +int SDF_Decrypt( + void *hSessionHandle, + void *hKeyHandle, + unsigned int uiAlgID, + unsigned char *pucIV, + unsigned char *pucEncData, + unsigned int uiEncDataLength, + unsigned char *pucData, + unsigned int *puiDataLength); + +int SDF_CalculateMAC( + void *hSessionHandle, + void *hKeyHandle, + unsigned int uiAlgID, + unsigned char *pucIV, + unsigned char *pucData, + unsigned int uiDataLength, + unsigned char *pucMAC, + unsigned int *puiMACLength); + +int SDF_HashInit( + void *hSessionHandle, + unsigned int uiAlgID, + ECCrefPublicKey *pucPublicKey, + unsigned char *pucID, + unsigned int uiIDLength); + +int SDF_HashUpdate( + void *hSessionHandle, + unsigned char *pucData, + unsigned int uiDataLength); + +int SDF_HashFinal(void *hSessionHandle, + unsigned char *pucHash, + unsigned int *puiHashLength); + +int SDF_CreateFile( + void *hSessionHandle, + unsigned char *pucFileName, + unsigned int uiNameLen, /* max 128-byte */ + unsigned int uiFileSize); + +int SDF_ReadFile( + void *hSessionHandle, + unsigned char *pucFileName, + unsigned int uiNameLen, + unsigned int uiOffset, + unsigned int *puiReadLength, + unsigned char *pucBuffer); + +int SDF_WriteFile( + void *hSessionHandle, + unsigned char *pucFileName, + unsigned int uiNameLen, + unsigned int uiOffset, + unsigned int uiWriteLength, + unsigned char *pucBuffer); + +int SDF_DeleteFile( + void *hSessionHandle, + unsigned char *pucFileName, + unsigned int uiNameLen); + +#define SDR_OK 0x0 +#define SDR_BASE 0x01000000 +#define SDR_UNKNOWERR (SDR_BASE + 0x00000001) +#define SDR_NOTSUPPORT (SDR_BASE + 0x00000002) +#define SDR_COMMFAIL (SDR_BASE + 0x00000003) +#define SDR_HARDFAIL (SDR_BASE + 0x00000004) +#define SDR_OPENDEVICE (SDR_BASE + 0x00000005) +#define SDR_OPENSESSION (SDR_BASE + 0x00000006) +#define SDR_PARDENY (SDR_BASE + 0x00000007) +#define SDR_KEYNOTEXIST (SDR_BASE + 0x00000008) +#define SDR_ALGNOTSUPPORT (SDR_BASE + 0x00000009) +#define SDR_ALGMODNOTSUPPORT (SDR_BASE + 0x0000000A) +#define SDR_PKOPERR (SDR_BASE + 0x0000000B) +#define SDR_SKOPERR (SDR_BASE + 0x0000000C) +#define SDR_SIGNERR (SDR_BASE + 0x0000000D) +#define SDR_VERIFYERR (SDR_BASE + 0x0000000E) +#define SDR_SYMOPERR (SDR_BASE + 0x0000000F) +#define SDR_STEPERR (SDR_BASE + 0x00000010) +#define SDR_FILESIZEERR (SDR_BASE + 0x00000011) +#define SDR_FILENOEXIST (SDR_BASE + 0x00000012) +#define SDR_FILEOFSERR (SDR_BASE + 0x00000013) +#define SDR_KEYTYPEERR (SDR_BASE + 0x00000014) +#define SDR_KEYERR (SDR_BASE + 0x00000015) +#define SDR_ENCDATAERR (SDR_BASE + 0x00000016) +#define SDR_RANDERR (SDR_BASE + 0x00000017) +#define SDR_PRKRERR (SDR_BASE + 0x00000018) +#define SDR_MACERR (SDR_BASE + 0x00000019) +#define SDR_FILEEXSITS (SDR_BASE + 0x0000001A) +#define SDR_FILEWERR (SDR_BASE + 0x0000001B) +#define SDR_NOBUFFER (SDR_BASE + 0x0000001C) +#define SDR_INARGERR (SDR_BASE + 0x0000001D) +#define SDR_OUTARGERR (SDR_BASE + 0x0000001E) + + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdf/sdf_ext.c b/sdf/sdf_ext.c new file mode 100644 index 00000000..f28866a4 --- /dev/null +++ b/sdf/sdf_ext.c @@ -0,0 +1,292 @@ +/* ==================================================================== + * Copyright (c) 2016 - 2017 The GmSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the GmSSL Project. + * (http://gmssl.org/)" + * + * 4. The name "GmSSL Project" must not be used to endorse or promote + * products derived from this software without prior written + * permission. For written permission, please contact + * guanzhi1980@gmail.com. + * + * 5. Products derived from this software may not be called "GmSSL" + * nor may "GmSSL" appear in their names without prior written + * permission of the GmSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the GmSSL Project + * (http://gmssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ + +#include +#include +#include +#include +#include "sdf_int.h" +#include "sdf_sansec.h" + + + +int format_bytes(FILE *out, int indent, int format, const uint8_t *data, size_t datalen) +{ + return 0; +} + +#define SDFerr(a,b) + + +typedef struct { + ULONG id; + char *name; +} table_item_t; + +static table_item_t sdf_cipher_caps[] = { + { SGD_SM1_ECB, "sm1-ecb" }, + { SGD_SM1_CBC, "sm1-cbc" }, + { SGD_SM1_CFB, "sm1-cfb" }, + { SGD_SM1_OFB, "sm1-ofb128" }, + { SGD_SM1_MAC, "cbcmac-sm1" }, + { SGD_SSF33_ECB, "ssf33-ecb" }, + { SGD_SSF33_CBC, "ssf33-cbc" }, + { SGD_SSF33_CFB, "ssf33-cfb" }, + { SGD_SSF33_OFB, "ssf33-ofb128" }, + { SGD_SSF33_MAC, "cbcmac-ssf33" }, + { SGD_SM4_ECB, "sms4-ecb" }, + { SGD_SM4_CBC, "sms4-cbc" }, + { SGD_SM4_CFB, "sms4-cfb" }, + { SGD_SM4_OFB, "sms4-ofb128" }, + { SGD_SM4_MAC, "cbcmac-sms4" }, + { SGD_ZUC_EEA3, "zuc_128eea3" }, + { SGD_ZUC_EIA3, "zuc_128eia3" } +}; + +static table_item_t sdf_digest_caps[] = { + { SGD_SM3, "sm3" }, + { SGD_SHA1, "sha1" }, + { SGD_SHA256, "sha256" }, +}; + +static table_item_t sdf_pkey_caps[] = { + { SGD_RSA_SIGN, "rsa" }, + { SGD_RSA_ENC, "rsaEncryption" }, + { SGD_SM2_1, "sm2sign" }, + { SGD_SM2_2, "sm2exchange" }, + { SGD_SM2_3, "sm2encrypt" } +}; + +int SDF_PrintDeviceInfo(FILE *out, DEVICEINFO *pstDeviceInfo) +{ + size_t i, n; + DEVICEINFO buf; + DEVICEINFO *devInfo = &buf; + + memcpy(devInfo, pstDeviceInfo, sizeof(DEVICEINFO)); + devInfo->IssuerName[39] = 0; + devInfo->DeviceName[15] = 0; + devInfo->DeviceSerial[15] = 0; + + fprintf(out, " %-18s : %s\n", "Device Name", devInfo->DeviceName); + fprintf(out, " %-18s : %s\n", "Serial Number", devInfo->DeviceSerial); + fprintf(out, " %-18s : %s\n", "Issuer", devInfo->IssuerName); + fprintf(out, " %-18s : %u\n", "Hardware Version", devInfo->DeviceVersion); + fprintf(out, " %-18s : %u\n", "Standard Version", devInfo->StandardVersion); + fprintf(out, " %-18s : ", "Public Key Algors"); + for (i = n = 0; i < sizeof(sdf_pkey_caps)/sizeof(sdf_pkey_caps[0]); i++) { + if ((devInfo->AsymAlgAbility[0] & sdf_pkey_caps[i].id) == + sdf_pkey_caps[i].id) { + fprintf(out, "%s%s", n ? "," : "", sdf_pkey_caps[i].name); + n++; + } + } + fprintf(out, "\n"); + + fprintf(out, " %-18s : ", "Ciphers"); + for (i = n = 0; i < sizeof(sdf_cipher_caps)/sizeof(sdf_cipher_caps[0]); i++) { + if ((devInfo->SymAlgAbility & sdf_cipher_caps[i].id) == + sdf_cipher_caps[i].id) { + fprintf(out, "%s%s", n ? "," : "", sdf_cipher_caps[i].name); + n++; + } + } + fprintf(out, "\n"); + + fprintf(out, " %-18s : ", "Digests"); + for (i = n = 0; i < sizeof(sdf_digest_caps)/sizeof(sdf_digest_caps[0]); i++) { + if ((devInfo->HashAlgAbility & sdf_digest_caps[i].id) == + sdf_digest_caps[i].id) { + fprintf(out, "%s%s", n ? "," : "", sdf_digest_caps[i].name); + n++; + } + } + fprintf(out, "\n"); + fprintf(out, "\n"); + + return SDR_OK; +} + +int SDF_PrintRSAPublicKey(FILE *out, RSArefPublicKey *blob) +{ + (void)fprintf(out, "bits: %d\n", blob->bits); + (void)fprintf(out, "m:\n "); + (void)format_bytes(out, 4, 16, blob->m, sizeof(blob->m)); + (void)fprintf(out, "\n"); + (void)fprintf(out, "e:\n "); + (void)format_bytes(out, 4, 16, blob->e, sizeof(blob->e)); + (void)fprintf(out, "\n"); + return SDR_OK; +} + +int SDF_PrintRSAPrivateKey(FILE *bio, RSArefPrivateKey *blob) +{ + (void)fprintf(bio, "bits: %d", blob->bits); + (void)fprintf(bio, "\n%s:\n ", "m"); + (void)format_bytes(bio, 4, 16, blob->m, sizeof(blob->m)); + (void)fprintf(bio, "\n%s:\n ", "e"); + (void)format_bytes(bio, 4, 16, blob->e, sizeof(blob->e)); + (void)fprintf(bio, "\n%s:\n ", "d"); + (void)format_bytes(bio, 4, 16, blob->d, sizeof(blob->d)); + (void)fprintf(bio, "\n%s:\n ", "prime[0]"); + (void)format_bytes(bio, 4, 16, blob->prime[0], sizeof(blob->prime[0])); + (void)fprintf(bio, "\n%s:\n ", "prime[1]"); + (void)format_bytes(bio, 4, 16, blob->prime[1], sizeof(blob->prime[1])); + (void)fprintf(bio, "\n%s:\n ", "pexp[0]"); + (void)format_bytes(bio, 4, 16, blob->pexp[0], sizeof(blob->pexp[0])); + (void)fprintf(bio, "\n%s:\n ", "pexp[1]"); + (void)format_bytes(bio, 4, 16, blob->pexp[1], sizeof(blob->pexp[1])); + (void)fprintf(bio, "\n%s:\n ", "coef"); + (void)format_bytes(bio, 4, 16, blob->coef, sizeof(blob->coef)); + (void)fprintf(bio, "\n"); + + return SDR_OK; +} + +int SDF_PrintECCPublicKey(FILE *bio, ECCrefPublicKey *blob) +{ + (void)fprintf(bio, "bits: %d", blob->bits); + (void)fprintf(bio, "\n%s:\n ", "x"); + (void)format_bytes(bio, 4, 16, blob->x, sizeof(blob->x)); + (void)fprintf(bio, "\n%s:\n ", "y"); + (void)format_bytes(bio, 4, 16, blob->y, sizeof(blob->y)); + (void)fprintf(bio, "\n"); + + return SDR_OK; +} + +int SDF_PrintECCPrivateKey(FILE *bio, ECCrefPrivateKey *blob) +{ + (void)fprintf(bio, "bits: %d", blob->bits); + (void)fprintf(bio, "\n%s:\n ", "K"); + (void)format_bytes(bio, 4, 16, blob->K, sizeof(blob->K)); + (void)fprintf(bio, "\n"); + + return SDR_OK; +} + +int SDF_PrintECCCipher(FILE *bio, ECCCipher *blob) +{ + (void)fprintf(bio, "%s:\n ", "x"); + (void)format_bytes(bio, 4, 16, blob->x, sizeof(blob->x)); + (void)fprintf(bio, "\n%s:\n ", "y"); + (void)format_bytes(bio, 4, 16, blob->y, sizeof(blob->y)); + (void)fprintf(bio, "\n%s:\n ", "M"); + (void)format_bytes(bio, 4, 16, blob->M, sizeof(blob->M)); + (void)fprintf(bio, "\nL: %d", blob->L); + (void)fprintf(bio, "\n%s:\n ", "C"); + (void)format_bytes(bio, 4, 16, blob->C, sizeof(blob->C)); + (void)fprintf(bio, "\n"); + + return SDR_OK; +} + +int SDF_PrintECCSignature(FILE *bio, ECCSignature *blob) +{ + (void)fprintf(bio, "%s:\n ", "r"); + (void)format_bytes(bio, 4, 16, blob->r, sizeof(blob->r)); + (void)fprintf(bio, "\n%s:\n ", "s"); + (void)format_bytes(bio, 4, 16, blob->s, sizeof(blob->s)); + (void)fprintf(bio, "\n"); + + return SDR_OK; +} + +int SDF_ImportKey( + void *hSessionHandle, + unsigned char *pucKey, + unsigned int uiKeyLength, + void **phKeyHandle) +{ + (void)hSessionHandle; + (void)pucKey; + (void)uiKeyLength; + (void)phKeyHandle; + SDFerr(SDF_F_SDF_IMPORTKEY, SDF_R_NOT_IMPLEMENTED); + return SDR_NOTSUPPORT; +} + +int SDF_NewECCCipher(ECCCipher **cipher, size_t ulDataLen) +{ + ECCCipher *ecc_cipher = NULL; + size_t len; + + if (!cipher) { + SDFerr(SDF_F_SDF_NEWECCCIPHER, ERR_R_PASSED_NULL_PARAMETER); + return SDR_INARGERR; + } + + if (!ulDataLen || ulDataLen > INT_MAX) { + SDFerr(SDF_F_SDF_NEWECCCIPHER, + SDF_R_INVALID_SM2_CIPHERTEXT_LENGTH); + return SDR_INARGERR; + } + + len = sizeof(ECCCipher) - 1 + ulDataLen; + if (len < sizeof(SANSEC_ECCCipher)) { + len = sizeof(SANSEC_ECCCipher); + } + + if (!(ecc_cipher = malloc(len))) { + SDFerr(SDF_F_SDF_NEWECCCIPHER, ERR_R_MALLOC_FAILURE); + return SDR_NOBUFFER; + } + memset(ecc_cipher, 0, sizeof(*ecc_cipher)); + + ecc_cipher->L = (unsigned int)ulDataLen; + + *cipher = ecc_cipher; + return SDR_OK; +} + +int SDF_FreeECCCipher(ECCCipher *cipher) +{ + free(cipher); + return SDR_OK; +} diff --git a/sdf/sdf_ext.h b/sdf/sdf_ext.h new file mode 100644 index 00000000..ee05d3db --- /dev/null +++ b/sdf/sdf_ext.h @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2014 - 2021 The GmSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the GmSSL Project. + * (http://gmssl.org/)" + * + * 4. The name "GmSSL Project" must not be used to endorse or promote + * products derived from this software without prior written + * permission. For written permission, please contact + * guanzhi1980@gmail.com. + * + * 5. Products derived from this software may not be called "GmSSL" + * nor may "GmSSL" appear in their names without prior written + * permission of the GmSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the GmSSL Project + * (http://gmssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef GMSSL_SDF_EXT_H +#define GMSSL_SDF_EXT_H + + +#include +#include +#include "sgd.h" +#include "sdf.h" + + +#ifdef __cplusplus +extern "C" { +#endif + + +#define SDF_MIN_KEY_INDEX 1 /* defined by GM/T 0018 */ +#define SDF_MAX_KEY_INDEX 32 /* defined by GmSSL */ +#define SDF_MIN_PASSWORD_LENGTH 8 /* defined by GM/T 0018 */ +#define SDF_MAX_PASSWORD_LENGTH 255 /* defined by GmSSL */ +#define SDF_MAX_FILE_SIZE (256 * 1024) + + + +int SDF_LoadLibrary(char *so_path, char *vendor); +int SDF_UnloadLibrary(void); +int SDF_ImportKey(void *hSessionHandle, unsigned char *pucKey, + unsigned int uiKeyLength, void **phKeyHandle); + +int SDF_PrintDeviceInfo(FILE *out, DEVICEINFO *devInfo); +int SDF_PrintRSAPublicKey(FILE *out, RSArefPublicKey *ref); +int SDF_PrintRSAPrivateKey(FILE *out, RSArefPrivateKey *ref); +int SDF_PrintECCPublicKey(FILE *out, ECCrefPublicKey *ref); +int SDF_PrintECCPrivateKey(FILE *out, ECCrefPrivateKey *ref); +int SDF_NewECCCipher(ECCCipher **cipher, size_t ulDataLen); +int SDF_FreeECCCipher(ECCCipher *cipher); +int SDF_PrintECCCipher(FILE *out, ECCCipher *cipher); +int SDF_PrintECCSignature(FILE *out, ECCSignature *sig); +int SDF_GetErrorString(int err, char **str); + + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdf/sdf_int.h b/sdf/sdf_int.h new file mode 100644 index 00000000..96b5af02 --- /dev/null +++ b/sdf/sdf_int.h @@ -0,0 +1,461 @@ +/* + * Copyright (c) 2014 - 2021 The GmSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the GmSSL Project. + * (http://gmssl.org/)" + * + * 4. The name "GmSSL Project" must not be used to endorse or promote + * products derived from this software without prior written + * permission. For written permission, please contact + * guanzhi1980@gmail.com. + * + * 5. Products derived from this software may not be called "GmSSL" + * nor may "GmSSL" appear in their names without prior written + * permission of the GmSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the GmSSL Project + * (http://gmssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HEADER_SDF_METH_H +#define HEADER_SDF_METH_H + + +#include + + +typedef int (*SDF_OpenDevice_FuncPtr)( + void **phDeviceHandle); + +typedef int (*SDF_CloseDevice_FuncPtr)( + void *hDeviceHandle); + +typedef int (*SDF_OpenSession_FuncPtr)( + void *hDeviceHandle, + void **phSessionHandle); + +typedef int (*SDF_CloseSession_FuncPtr)( + void *hSessionHandle); + +typedef int (*SDF_GetDeviceInfo_FuncPtr)( + void *hSessionHandle, + DEVICEINFO *pstDeviceInfo); + +typedef int (*SDF_GenerateRandom_FuncPtr)( + void *hSessionHandle, + unsigned int uiLength, + unsigned char *pucRandom); + +typedef int (*SDF_GetPrivateKeyAccessRight_FuncPtr)( + void *hSessionHandle, + unsigned int uiKeyIndex, + unsigned char *pucPassword, + unsigned int uiPwdLength); + +typedef int (*SDF_ReleasePrivateKeyAccessRight_FuncPtr)( + void *hSessionHandle, + unsigned int uiKeyIndex); + +typedef int (*SDF_ExportSignPublicKey_RSA_FuncPtr)( + void *hSessionHandle, + unsigned int uiKeyIndex, + RSArefPublicKey *pucPublicKey); + +typedef int (*SDF_ExportEncPublicKey_RSA_FuncPtr)( + void *hSessionHandle, + unsigned int uiKeyIndex, + RSArefPublicKey *pucPublicKey); + +typedef int (*SDF_GenerateKeyPair_RSA_FuncPtr)( + void *hSessionHandle, + unsigned int uiKeyBits, + RSArefPublicKey *pucPublicKey, + RSArefPrivateKey *pucPrivateKey); + +typedef int (*SDF_GenerateKeyWithIPK_RSA_FuncPtr)( + void *hSessionHandle, + unsigned int uiIPKIndex, + unsigned int uiKeyBits, + unsigned char *pucKey, + unsigned int *puiKeyLength, + void **phKeyHandle); + +typedef int (*SDF_GenerateKeyWithEPK_RSA_FuncPtr)( + void *hSessionHandle, + unsigned int uiKeyBits, + RSArefPublicKey *pucPublicKey, + unsigned char *pucKey, + unsigned int *puiKeyLength, + void **phKeyHandle); + +typedef int (*SDF_ImportKeyWithISK_RSA_FuncPtr)( + void *hSessionHandle, + unsigned int uiISKIndex, + unsigned char *pucKey, + unsigned int uiKeyLength, + void **phKeyHandle); + +typedef int (*SDF_ExchangeDigitEnvelopeBaseOnRSA_FuncPtr)( + void *hSessionHandle, + unsigned int uiKeyIndex, + RSArefPublicKey *pucPublicKey, + unsigned char *pucDEInput, + unsigned int uiDELength, + unsigned char *pucDEOutput, + unsigned int *puiDELength); + +typedef int (*SDF_ExportSignPublicKey_ECC_FuncPtr)( + void *hSessionHandle, + unsigned int uiKeyIndex, + ECCrefPublicKey *pucPublicKey); + +typedef int (*SDF_ExportEncPublicKey_ECC_FuncPtr)( + void *hSessionHandle, + unsigned int uiKeyIndex, + ECCrefPublicKey *pucPublicKey); + +typedef int (*SDF_GenerateKeyPair_ECC_FuncPtr)( + void *hSessionHandle, + unsigned int uiAlgID, + unsigned int uiKeyBits, + ECCrefPublicKey *pucPublicKey, + ECCrefPrivateKey *pucPrivateKey); + +typedef int (*SDF_GenerateKeyWithIPK_ECC_FuncPtr)( + void *hSessionHandle, + unsigned int uiIPKIndex, + unsigned int uiKeyBits, + ECCCipher *pucKey, + void **phKeyHandle); + +typedef int (*SDF_GenerateKeyWithEPK_ECC_FuncPtr)( + void *hSessionHandle, + unsigned int uiKeyBits, + unsigned int uiAlgID, + ECCrefPublicKey *pucPublicKey, + ECCCipher *pucKey, + void **phKeyHandle); + +typedef int (*SDF_ImportKeyWithISK_ECC_FuncPtr)( + void *hSessionHandle, + unsigned int uiISKIndex, + ECCCipher *pucKey, + void **phKeyHandle); + +typedef int (*SDF_GenerateAgreementDataWithECC_FuncPtr)( + void *hSessionHandle, + unsigned int uiISKIndex, + unsigned int uiKeyBits, + unsigned char *pucSponsorID, + unsigned int uiSponsorIDLength, + ECCrefPublicKey *pucSponsorPublicKey, + ECCrefPublicKey *pucSponsorTmpPublicKey, + void **phAgreementHandle); + +typedef int (*SDF_GenerateKeyWithECC_FuncPtr)( + void *hSessionHandle, + unsigned char *pucResponseID, + unsigned int uiResponseIDLength, + ECCrefPublicKey *pucResponsePublicKey, + ECCrefPublicKey *pucResponseTmpPublicKey, + void *hAgreementHandle, + void **phKeyHandle); + +typedef int (*SDF_GenerateAgreementDataAndKeyWithECC_FuncPtr)( + void *hSessionHandle, + unsigned int uiISKIndex, + unsigned int uiKeyBits, + unsigned char *pucResponseID, + unsigned int uiResponseIDLength, + unsigned char *pucSponsorID, + unsigned int uiSponsorIDLength, + ECCrefPublicKey *pucSponsorPublicKey, + ECCrefPublicKey *pucSponsorTmpPublicKey, + ECCrefPublicKey *pucResponsePublicKey, + ECCrefPublicKey *pucResponseTmpPublicKey, + void **phKeyHandle); + +typedef int (*SDF_ExchangeDigitEnvelopeBaseOnECC_FuncPtr)( + void *hSessionHandle, + unsigned int uiKeyIndex, + unsigned int uiAlgID, + ECCrefPublicKey *pucPublicKey, + ECCCipher *pucEncDataIn, + ECCCipher *pucEncDataOut); + +typedef int (*SDF_GenerateKeyWithKEK_FuncPtr)( + void *hSessionHandle, + unsigned int uiKeyBits, + unsigned int uiAlgID, + unsigned int uiKEKIndex, + unsigned char *pucKey, + unsigned int *puiKeyLength, + void **phKeyHandle); + +typedef int (*SDF_ImportKeyWithKEK_FuncPtr)( + void *hSessionHandle, + unsigned int uiAlgID, + unsigned int uiKEKIndex, + unsigned char *pucKey, + unsigned int uiKeyLength, + void **phKeyHandle); + +typedef int (*SDF_DestroyKey_FuncPtr)( + void *hSessionHandle, + void *hKeyHandle); + +typedef int (*SDF_ExternalPublicKeyOperation_RSA_FuncPtr)( + void *hSessionHandle, + RSArefPublicKey *pucPublicKey, + unsigned char *pucDataInput, + unsigned int uiInputLength, + unsigned char *pucDataOutput, + unsigned int *puiOutputLength); + +typedef int (*SDF_InternalPublicKeyOperation_RSA_FuncPtr)( + void *hSessionHandle, + unsigned int uiKeyIndex, + unsigned char *pucDataInput, + unsigned int uiInputLength, + unsigned char *pucDataOutput, + unsigned int *puiOutputLength); + +typedef int (*SDF_InternalPrivateKeyOperation_RSA_FuncPtr)( + void *hSessionHandle, + unsigned int uiKeyIndex, + unsigned char *pucDataInput, + unsigned int uiInputLength, + unsigned char *pucDataOutput, + unsigned int *puiOutputLength); + +typedef int (*SDF_ExternalVerify_ECC_FuncPtr)( + void *hSessionHandle, + unsigned int uiAlgID, + ECCrefPublicKey *pucPublicKey, + unsigned char *pucDataInput, + unsigned int uiInputLength, + ECCSignature *pucSignature); + +typedef int (*SDF_InternalSign_ECC_FuncPtr)( + void *hSessionHandle, + unsigned int uiISKIndex, + unsigned char *pucData, + unsigned int uiDataLength, + ECCSignature *pucSignature); + +typedef int (*SDF_InternalVerify_ECC_FuncPtr)( + void *hSessionHandle, + unsigned int uiIPKIndex, + unsigned char *pucData, + unsigned int uiDataLength, + ECCSignature *pucSignature); + +typedef int (*SDF_ExternalEncrypt_ECC_FuncPtr)( + void *hSessionHandle, + unsigned int uiAlgID, + ECCrefPublicKey *pucPublicKey, + unsigned char *pucData, + unsigned int uiDataLength, + ECCCipher *pucEncData); + +typedef int (*SDF_ExternalDecrypt_ECC_FuncPtr)( + void *hSessionHandle, + unsigned int uiAlgID, + ECCrefPrivateKey *pucPrivateKey, + ECCCipher *pucEncData, + unsigned char *pucData, + unsigned int *puiDataLength); + +typedef int (*SDF_InternalEncrypt_ECC_FuncPtr)( + void *hSessionHandle, + unsigned int uiIPKIndex, + unsigned int uiAlgID, + unsigned char *pucData, + unsigned int uiDataLength, + ECCCipher *pucEncData); + +typedef int (*SDF_InternalDecrypt_ECC_FuncPtr)( + void *hSessionHandle, + unsigned int uiISKIndex, + unsigned int uiAlgID, + ECCCipher *pucEncData, + unsigned char *pucData, + unsigned int *puiDataLength); + +typedef int (*SDF_Encrypt_FuncPtr)( + void *hSessionHandle, + void *hKeyHandle, + unsigned int uiAlgID, + unsigned char *pucIV, + unsigned char *pucData, + unsigned int uiDataLength, + unsigned char *pucEncData, + unsigned int *puiEncDataLength); + +typedef int (*SDF_Decrypt_FuncPtr)( + void *hSessionHandle, + void *hKeyHandle, + unsigned int uiAlgID, + unsigned char *pucIV, + unsigned char *pucEncData, + unsigned int uiEncDataLength, + unsigned char *pucData, + unsigned int *puiDataLength); + +typedef int (*SDF_CalculateMAC_FuncPtr)( + void *hSessionHandle, + void *hKeyHandle, + unsigned int uiAlgID, + unsigned char *pucIV, + unsigned char *pucData, + unsigned int uiDataLength, + unsigned char *pucMAC, + unsigned int *puiMACLength); + +typedef int (*SDF_HashInit_FuncPtr)( + void *hSessionHandle, + unsigned int uiAlgID, + ECCrefPublicKey *pucPublicKey, + unsigned char *pucID, + unsigned int uiIDLength); + +typedef int (*SDF_HashUpdate_FuncPtr)( + void *hSessionHandle, + unsigned char *pucData, + unsigned int uiDataLength); + +typedef int (*SDF_HashFinal_FuncPtr)(void *hSessionHandle, + unsigned char *pucHash, + unsigned int *puiHashLength); + +typedef int (*SDF_CreateObject_FuncPtr)( + void *hSessionHandle, + unsigned char *pucFileName, + unsigned int uiNameLen, + unsigned int uiFileSize); + +typedef int (*SDF_ReadObject_FuncPtr)( + void *hSessionHandle, + unsigned char *pucFileName, + unsigned int uiNameLen, + unsigned int uiOffset, + unsigned int *puiReadLength, + unsigned char *pucBuffer); + +typedef int (*SDF_WriteObject_FuncPtr)( + void *hSessionHandle, + unsigned char *pucFileName, + unsigned int uiNameLen, + unsigned int uiOffset, + unsigned int uiWriteLength, + unsigned char *pucBuffer); + +typedef int (*SDF_DeleteObject_FuncPtr)( + void *hSessionHandle, + unsigned char *pucFileName, + unsigned int uiNameLen); + +typedef struct sdf_method_st { + char *name; + void *dso; + SDF_OpenDevice_FuncPtr OpenDevice; + SDF_CloseDevice_FuncPtr CloseDevice; + SDF_OpenSession_FuncPtr OpenSession; + SDF_CloseSession_FuncPtr CloseSession; + SDF_GetDeviceInfo_FuncPtr GetDeviceInfo; + SDF_GenerateRandom_FuncPtr GenerateRandom; + SDF_GetPrivateKeyAccessRight_FuncPtr GetPrivateKeyAccessRight; + SDF_ReleasePrivateKeyAccessRight_FuncPtr ReleasePrivateKeyAccessRight; + SDF_ExportSignPublicKey_RSA_FuncPtr ExportSignPublicKey_RSA; + SDF_ExportEncPublicKey_RSA_FuncPtr ExportEncPublicKey_RSA; + SDF_GenerateKeyPair_RSA_FuncPtr GenerateKeyPair_RSA; + SDF_GenerateKeyWithIPK_RSA_FuncPtr GenerateKeyWithIPK_RSA; + SDF_GenerateKeyWithEPK_RSA_FuncPtr GenerateKeyWithEPK_RSA; + SDF_ImportKeyWithISK_RSA_FuncPtr ImportKeyWithISK_RSA; + SDF_ExchangeDigitEnvelopeBaseOnRSA_FuncPtr ExchangeDigitEnvelopeBaseOnRSA; + SDF_ExportSignPublicKey_ECC_FuncPtr ExportSignPublicKey_ECC; + SDF_ExportEncPublicKey_ECC_FuncPtr ExportEncPublicKey_ECC; + SDF_GenerateKeyPair_ECC_FuncPtr GenerateKeyPair_ECC; + SDF_GenerateKeyWithIPK_ECC_FuncPtr GenerateKeyWithIPK_ECC; + SDF_GenerateKeyWithEPK_ECC_FuncPtr GenerateKeyWithEPK_ECC; + SDF_ImportKeyWithISK_ECC_FuncPtr ImportKeyWithISK_ECC; + SDF_GenerateAgreementDataWithECC_FuncPtr GenerateAgreementDataWithECC; + SDF_GenerateKeyWithECC_FuncPtr GenerateKeyWithECC; + SDF_GenerateAgreementDataAndKeyWithECC_FuncPtr GenerateAgreementDataAndKeyWithECC; + SDF_ExchangeDigitEnvelopeBaseOnECC_FuncPtr ExchangeDigitEnvelopeBaseOnECC; + SDF_GenerateKeyWithKEK_FuncPtr GenerateKeyWithKEK; + SDF_ImportKeyWithKEK_FuncPtr ImportKeyWithKEK; + SDF_DestroyKey_FuncPtr DestroyKey; + SDF_ExternalPublicKeyOperation_RSA_FuncPtr ExternalPublicKeyOperation_RSA; + SDF_InternalPublicKeyOperation_RSA_FuncPtr InternalPublicKeyOperation_RSA; + SDF_InternalPrivateKeyOperation_RSA_FuncPtr InternalPrivateKeyOperation_RSA; + SDF_ExternalVerify_ECC_FuncPtr ExternalVerify_ECC; + SDF_InternalSign_ECC_FuncPtr InternalSign_ECC; + SDF_InternalVerify_ECC_FuncPtr InternalVerify_ECC; + SDF_ExternalEncrypt_ECC_FuncPtr ExternalEncrypt_ECC; + SDF_ExternalDecrypt_ECC_FuncPtr ExternalDecrypt_ECC; + SDF_InternalEncrypt_ECC_FuncPtr InternalEncrypt_ECC; + SDF_InternalDecrypt_ECC_FuncPtr InternalDecrypt_ECC; + SDF_Encrypt_FuncPtr Encrypt; + SDF_Decrypt_FuncPtr Decrypt; + SDF_CalculateMAC_FuncPtr CalculateMAC; + SDF_HashInit_FuncPtr HashInit; + SDF_HashUpdate_FuncPtr HashUpdate; + SDF_HashFinal_FuncPtr HashFinal; + SDF_CreateObject_FuncPtr CreateObject; + SDF_ReadObject_FuncPtr ReadObject; + SDF_WriteObject_FuncPtr WriteObject; + SDF_DeleteObject_FuncPtr DeleteObject; +} SDF_METHOD; + +SDF_METHOD *SDF_METHOD_load_library(const char *so_path); +void SDF_METHOD_free(SDF_METHOD *meth); + + +typedef struct sdf_vendor_st { + char *name; + unsigned int (*cipher_vendor2std)(unsigned int vendor_id); + unsigned int (*cipher_std2vendor)(unsigned int std_id); + unsigned int (*cipher_cap)(unsigned int vendor_cap); + unsigned int (*digest_vendor2std)(unsigned int vendor_id); + unsigned int (*digest_std2vendor)(unsigned int std_id); + unsigned int (*digest_cap)(unsigned int vendor_cap); + unsigned int (*pkey_vendor2std)(unsigned int vendor_id); + unsigned int (*pkey_std2vendor)(unsigned int std_id); + unsigned int (*pkey_cap)(unsigned int vendor_cap); + int (*encode_ecccipher)(const ECCCipher *a, void *buf); + int (*decode_ecccipher)(ECCCipher *a, const void *buf); + unsigned long (*get_error_reason)(int err); +} SDF_VENDOR; + + +#endif diff --git a/sdf/sdf_lib.c b/sdf/sdf_lib.c new file mode 100644 index 00000000..588185d1 --- /dev/null +++ b/sdf/sdf_lib.c @@ -0,0 +1,1608 @@ +/* ==================================================================== + * Copyright (c) 2016 - 2017 The GmSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the GmSSL Project. + * (http://gmssl.org/)" + * + * 4. The name "GmSSL Project" must not be used to endorse or promote + * products derived from this software without prior written + * permission. For written permission, please contact + * guanzhi1980@gmail.com. + * + * 5. Products derived from this software may not be called "GmSSL" + * nor may "GmSSL" appear in their names without prior written + * permission of the GmSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the GmSSL Project + * (http://gmssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ + +#include +#include "sdf_ext.h" +#include "sdf_int.h" + +SDF_METHOD *sdf_method = NULL; +SDF_VENDOR *sdf_vendor = NULL; +extern SDF_VENDOR sdf_sansec; + +#define SDFerr(a,b) + + + +int SDF_LoadLibrary(char *so_path, char *vendor) +{ + if (sdf_method) { + SDF_METHOD_free(sdf_method); + sdf_method = NULL; + } + + if (!(sdf_method = SDF_METHOD_load_library(so_path))) { + SDFerr(SDF_F_SDF_LOADLIBRARY, SDF_R_LOAD_LIBRARY_FAILURE); + return SDR_BASE; + } + + if (vendor) { + if (strcmp(vendor, sdf_sansec.name) == 0) { + sdf_vendor = &sdf_sansec; + } + } + + return SDR_OK; +} + +int SDF_UnloadLibrary(void) +{ + SDF_METHOD_free(sdf_method); + sdf_method = NULL; + sdf_vendor = NULL; + return SDR_OK; +} + +/* +static SDF_ERR_REASON sdf_errors[] = { + { SDR_OK, SDF_R_SUCCESS }, + { SDR_BASE, SDF_R_ERROR }, + { SDR_UNKNOWERR, SDF_R_UNNOWN_ERROR }, + { SDR_NOTSUPPORT, SDF_R_OPERATION_NOT_SUPPORTED }, + { SDR_COMMFAIL, SDF_R_COMMUNICATION_FAILURE }, + { SDR_HARDFAIL, SDF_R_HARDWARE_ERROR }, + { SDR_OPENDEVICE, SDF_R_OPEN_DEVICE_FAILURE }, + { SDR_OPENSESSION, SDF_R_OPEN_SESSION_FAILURE }, + { SDR_PARDENY, SDF_R_NO_PRIVATE_KEY_ACCESS_RIGHT }, + { SDR_KEYNOTEXIST, SDF_R_KEY_NOT_EXIST }, + { SDR_ALGNOTSUPPORT, SDF_R_ALGORITHM_NOT_SUPPORTED }, + { SDR_ALGMODNOTSUPPORT, SDF_R_ALGORITHM_MODE_NOT_SUPPORTED }, + { SDR_PKOPERR, SDF_R_PUBLIC_KEY_OPERATION_FAILURE }, + { SDR_SKOPERR, SDF_R_PRIVATE_KEY_OPERATION_FAILURE }, + { SDR_SIGNERR, SDF_R_SIGNING_FAILURE }, + { SDR_VERIFYERR, SDF_R_VERIFICATION_FAILURE }, + { SDR_SYMOPERR, SDF_R_SYMMETRIC_OPERATION_FAILURE }, + { SDR_STEPERR, SDF_R_MULTI_STEP_OPERATION_ERROR }, + { SDR_FILESIZEERR, SDF_R_INVALID_FILE_SIZE }, + { SDR_FILENOEXIST, SDF_R_FILE_NOT_EXIST }, + { SDR_FILEOFSERR, SDF_R_INVALID_FILE_OFFSET }, + { SDR_KEYTYPEERR, SDF_R_INVALID_KEY_TYPE }, + { SDR_KEYERR, SDF_R_INVALID_KEY }, + { SDR_ENCDATAERR, SDF_R_ENCRYPT_DATA_ERROR }, + { SDR_RANDERR, SDF_R_RANDOM_GENERATION_ERROR }, + { SDR_PRKRERR, SDF_R_PRKERR }, + { SDR_MACERR, SDF_R_MAC_ERROR }, + { SDR_FILEEXSITS, SDF_R_FILE_ALREADY_EXIST }, + { SDR_FILEWERR, SDF_R_WRITE_FILE_FAILURE }, + { SDR_NOBUFFER, SDF_R_BUFFER_TOO_SMALL }, + { SDR_INARGERR, SDF_R_INVALID_INPUT_ARGUMENT }, + { SDR_OUTARGERR, SDF_R_INVALID_OUTPUT_ARGUMENT }, +}; + +static unsigned long sdf_get_error_reason(int err) +{ + size_t i; + for (i = 0; i < sizeof(sdf_errors)/sizeof(sdf_errors[0]); i++) { + if (err == sdf_errors[i].err) { + return sdf_errors[i].reason; + } + } + if (sdf_vendor) { + return sdf_vendor->get_error_reason(err); + } + return 0; +} + + +int SDF_GetErrorString(int err, char **str) +{ + unsigned long reason; + + if ((reason = sdf_get_error_reason(err)) != 0) { + *str = (char*)ERR_reason_error_string(reason); + } else { + *str = "(unknown)"; + } + + return SDR_OK; +} +*/ + +int SDF_OpenDevice( + void **phDeviceHandle) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->OpenDevice) { + SDFerr(SDF_F_SDF_OPENDEVICE, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->OpenDevice( + phDeviceHandle)) != SDR_OK) { + SDFerr(SDF_F_SDF_OPENDEVICE, sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_CloseDevice( + void *hDeviceHandle) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->CloseDevice) { + SDFerr(SDF_F_SDF_CLOSEDEVICE, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->CloseDevice( + hDeviceHandle)) != SDR_OK) { + SDFerr(SDF_F_SDF_CLOSEDEVICE, sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_OpenSession( + void *hDeviceHandle, + void **phSessionHandle) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->OpenSession) { + SDFerr(SDF_F_SDF_OPENSESSION, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->OpenSession( + hDeviceHandle, + phSessionHandle)) != SDR_OK) { + SDFerr(SDF_F_SDF_OPENSESSION, sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_CloseSession( + void *hSessionHandle) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->CloseSession) { + SDFerr(SDF_F_SDF_CLOSESESSION, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->CloseSession( + hSessionHandle)) != SDR_OK) { + SDFerr(SDF_F_SDF_CLOSESESSION, sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_GetDeviceInfo( + void *hSessionHandle, + DEVICEINFO *pstDeviceInfo) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->GetDeviceInfo) { + SDFerr(SDF_F_SDF_GETDEVICEINFO, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->GetDeviceInfo( + hSessionHandle, + pstDeviceInfo)) != SDR_OK) { + SDFerr(SDF_F_SDF_GETDEVICEINFO, sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_GenerateRandom( + void *hSessionHandle, + unsigned int uiLength, + unsigned char *pucRandom) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->GenerateRandom) { + SDFerr(SDF_F_SDF_GENERATERANDOM, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->GenerateRandom( + hSessionHandle, + uiLength, + pucRandom)) != SDR_OK) { + SDFerr(SDF_F_SDF_GENERATERANDOM, sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_GetPrivateKeyAccessRight( + void *hSessionHandle, + unsigned int uiKeyIndex, + unsigned char *pucPassword, + unsigned int uiPwdLength) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->GetPrivateKeyAccessRight) { + SDFerr(SDF_F_SDF_GETPRIVATEKEYACCESSRIGHT, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->GetPrivateKeyAccessRight( + hSessionHandle, + uiKeyIndex, + pucPassword, + uiPwdLength)) != SDR_OK) { + SDFerr(SDF_F_SDF_GETPRIVATEKEYACCESSRIGHT, sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_ReleasePrivateKeyAccessRight( + void *hSessionHandle, + unsigned int uiKeyIndex) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->ReleasePrivateKeyAccessRight) { + SDFerr(SDF_F_SDF_RELEASEPRIVATEKEYACCESSRIGHT, + SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->ReleasePrivateKeyAccessRight( + hSessionHandle, + uiKeyIndex)) != SDR_OK) { + SDFerr(SDF_F_SDF_RELEASEPRIVATEKEYACCESSRIGHT, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_ExportSignPublicKey_RSA( + void *hSessionHandle, + unsigned int uiKeyIndex, + RSArefPublicKey *pucPublicKey) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->ExportSignPublicKey_RSA) { + SDFerr(SDF_F_SDF_EXPORTSIGNPUBLICKEY_RSA, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->ExportSignPublicKey_RSA( + hSessionHandle, + uiKeyIndex, + pucPublicKey)) != SDR_OK) { + SDFerr(SDF_F_SDF_EXPORTSIGNPUBLICKEY_RSA, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_ExportEncPublicKey_RSA( + void *hSessionHandle, + unsigned int uiKeyIndex, + RSArefPublicKey *pucPublicKey) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->ExportEncPublicKey_RSA) { + SDFerr(SDF_F_SDF_EXPORTENCPUBLICKEY_RSA, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->ExportEncPublicKey_RSA( + hSessionHandle, + uiKeyIndex, + pucPublicKey)) != SDR_OK) { + SDFerr(SDF_F_SDF_EXPORTENCPUBLICKEY_RSA, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_GenerateKeyPair_RSA( + void *hSessionHandle, + unsigned int uiKeyBits, + RSArefPublicKey *pucPublicKey, + RSArefPrivateKey *pucPrivateKey) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->GenerateKeyPair_RSA) { + SDFerr(SDF_F_SDF_GENERATEKEYPAIR_RSA, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->GenerateKeyPair_RSA( + hSessionHandle, + uiKeyBits, + pucPublicKey, + pucPrivateKey)) != SDR_OK) { + SDFerr(SDF_F_SDF_GENERATEKEYPAIR_RSA, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_GenerateKeyWithIPK_RSA( + void *hSessionHandle, + unsigned int uiIPKIndex, + unsigned int uiKeyBits, + unsigned char *pucKey, + unsigned int *puiKeyLength, + void **phKeyHandle) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->GenerateKeyWithIPK_RSA) { + SDFerr(SDF_F_SDF_GENERATEKEYWITHIPK_RSA, + SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->GenerateKeyWithIPK_RSA( + hSessionHandle, + uiIPKIndex, + uiKeyBits, + pucKey, + puiKeyLength, + phKeyHandle)) != SDR_OK) { + SDFerr(SDF_F_SDF_GENERATEKEYWITHIPK_RSA, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_GenerateKeyWithEPK_RSA( + void *hSessionHandle, + unsigned int uiKeyBits, + RSArefPublicKey *pucPublicKey, + unsigned char *pucKey, + unsigned int *puiKeyLength, + void **phKeyHandle) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->GenerateKeyWithEPK_RSA) { + SDFerr(SDF_F_SDF_GENERATEKEYWITHEPK_RSA, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->GenerateKeyWithEPK_RSA( + hSessionHandle, + uiKeyBits, + pucPublicKey, + pucKey, + puiKeyLength, + phKeyHandle)) != SDR_OK) { + SDFerr(SDF_F_SDF_GENERATEKEYWITHEPK_RSA, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_ImportKeyWithISK_RSA( + void *hSessionHandle, + unsigned int uiISKIndex, + unsigned char *pucKey, + unsigned int uiKeyLength, + void **phKeyHandle) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->ImportKeyWithISK_RSA) { + SDFerr(SDF_F_SDF_IMPORTKEYWITHISK_RSA, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->ImportKeyWithISK_RSA( + hSessionHandle, + uiISKIndex, + pucKey, + uiKeyLength, + phKeyHandle)) != SDR_OK) { + SDFerr(SDF_F_SDF_IMPORTKEYWITHISK_RSA, sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_ExchangeDigitEnvelopeBaseOnRSA( + void *hSessionHandle, + unsigned int uiKeyIndex, + RSArefPublicKey *pucPublicKey, + unsigned char *pucDEInput, + unsigned int uiDELength, + unsigned char *pucDEOutput, + unsigned int *puiDELength) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->ExchangeDigitEnvelopeBaseOnRSA) { + SDFerr(SDF_F_SDF_EXCHANGEDIGITENVELOPEBASEONRSA, + SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->ExchangeDigitEnvelopeBaseOnRSA( + hSessionHandle, + uiKeyIndex, + pucPublicKey, + pucDEInput, + uiDELength, + pucDEOutput, + puiDELength)) != SDR_OK) { + SDFerr(SDF_F_SDF_EXCHANGEDIGITENVELOPEBASEONRSA, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_ExportSignPublicKey_ECC( + void *hSessionHandle, + unsigned int uiKeyIndex, + ECCrefPublicKey *pucPublicKey) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->ExportSignPublicKey_ECC) { + SDFerr(SDF_F_SDF_EXPORTSIGNPUBLICKEY_ECC, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->ExportSignPublicKey_ECC( + hSessionHandle, + uiKeyIndex, + pucPublicKey)) != SDR_OK) { + SDFerr(SDF_F_SDF_EXPORTSIGNPUBLICKEY_ECC, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_ExportEncPublicKey_ECC( + void *hSessionHandle, + unsigned int uiKeyIndex, + ECCrefPublicKey *pucPublicKey) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->ExportEncPublicKey_ECC) { + SDFerr(SDF_F_SDF_EXPORTENCPUBLICKEY_ECC, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->ExportEncPublicKey_ECC( + hSessionHandle, + uiKeyIndex, + pucPublicKey)) != SDR_OK) { + SDFerr(SDF_F_SDF_EXPORTENCPUBLICKEY_ECC, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_GenerateKeyPair_ECC( + void *hSessionHandle, + unsigned int uiAlgID, + unsigned int uiKeyBits, + ECCrefPublicKey *pucPublicKey, + ECCrefPrivateKey *pucPrivateKey) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->GenerateKeyPair_ECC) { + SDFerr(SDF_F_SDF_GENERATEKEYPAIR_ECC, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if (sdf_vendor) { + if (!(uiAlgID = sdf_vendor->pkey_std2vendor(uiAlgID))) { + SDFerr(SDF_F_SDF_GENERATEKEYPAIR_ECC, + SDF_R_NOT_SUPPORTED_ECC_ALGOR); + return SDR_ALGNOTSUPPORT; + } + } + + if ((ret = sdf_method->GenerateKeyPair_ECC( + hSessionHandle, + uiAlgID, + uiKeyBits, + pucPublicKey, + pucPrivateKey)) != SDR_OK) { + SDFerr(SDF_F_SDF_GENERATEKEYPAIR_ECC, sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_GenerateKeyWithIPK_ECC( + void *hSessionHandle, + unsigned int uiIPKIndex, + unsigned int uiKeyBits, + ECCCipher *pucKey, + void **phKeyHandle) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->GenerateKeyWithIPK_ECC) { + SDFerr(SDF_F_SDF_GENERATEKEYWITHIPK_ECC, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->GenerateKeyWithIPK_ECC( + hSessionHandle, + uiIPKIndex, + uiKeyBits, + pucKey, + phKeyHandle)) != SDR_OK) { + SDFerr(SDF_F_SDF_GENERATEKEYWITHIPK_ECC, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_GenerateKeyWithEPK_ECC( + void *hSessionHandle, + unsigned int uiKeyBits, + unsigned int uiAlgID, + ECCrefPublicKey *pucPublicKey, + ECCCipher *pucKey, + void **phKeyHandle) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->GenerateKeyWithEPK_ECC) { + SDFerr(SDF_F_SDF_GENERATEKEYWITHEPK_ECC, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if (sdf_vendor) { + if (!(uiAlgID = sdf_vendor->cipher_std2vendor(uiAlgID))) { + SDFerr(SDF_F_SDF_GENERATEKEYWITHEPK_ECC, + SDF_R_NOT_SUPPORTED_CIPHER_ALGOR); + return SDR_ALGNOTSUPPORT; + } + } + + if ((ret = sdf_method->GenerateKeyWithEPK_ECC( + hSessionHandle, + uiKeyBits, + uiAlgID, + pucPublicKey, + pucKey, + phKeyHandle)) != SDR_OK) { + SDFerr(SDF_F_SDF_GENERATEKEYWITHEPK_ECC, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_ImportKeyWithISK_ECC( + void *hSessionHandle, + unsigned int uiISKIndex, + ECCCipher *pucKey, + void **phKeyHandle) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->ImportKeyWithISK_ECC) { + SDFerr(SDF_F_SDF_IMPORTKEYWITHISK_ECC, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->ImportKeyWithISK_ECC( + hSessionHandle, + uiISKIndex, + pucKey, + phKeyHandle)) != SDR_OK) { + SDFerr(SDF_F_SDF_IMPORTKEYWITHISK_ECC, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_GenerateAgreementDataWithECC( + void *hSessionHandle, + unsigned int uiISKIndex, + unsigned int uiKeyBits, + unsigned char *pucSponsorID, + unsigned int uiSponsorIDLength, + ECCrefPublicKey *pucSponsorPublicKey, + ECCrefPublicKey *pucSponsorTmpPublicKey, + void **phAgreementHandle) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->GenerateAgreementDataWithECC) { + SDFerr(SDF_F_SDF_GENERATEAGREEMENTDATAWITHECC, + SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->GenerateAgreementDataWithECC( + hSessionHandle, + uiISKIndex, + uiKeyBits, + pucSponsorID, + uiSponsorIDLength, + pucSponsorPublicKey, + pucSponsorTmpPublicKey, + phAgreementHandle)) != SDR_OK) { + SDFerr(SDF_F_SDF_GENERATEAGREEMENTDATAWITHECC, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_GenerateKeyWithECC( + void *hSessionHandle, + unsigned char *pucResponseID, + unsigned int uiResponseIDLength, + ECCrefPublicKey *pucResponsePublicKey, + ECCrefPublicKey *pucResponseTmpPublicKey, + void *hAgreementHandle, + void **phKeyHandle) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->GenerateKeyWithECC) { + SDFerr(SDF_F_SDF_GENERATEKEYWITHECC, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->GenerateKeyWithECC( + hSessionHandle, + pucResponseID, + uiResponseIDLength, + pucResponsePublicKey, + pucResponseTmpPublicKey, + hAgreementHandle, + phKeyHandle)) != SDR_OK) { + SDFerr(SDF_F_SDF_GENERATEKEYWITHECC, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_GenerateAgreementDataAndKeyWithECC( + void *hSessionHandle, + unsigned int uiISKIndex, + unsigned int uiKeyBits, + unsigned char *pucResponseID, + unsigned int uiResponseIDLength, + unsigned char *pucSponsorID, + unsigned int uiSponsorIDLength, + ECCrefPublicKey *pucSponsorPublicKey, + ECCrefPublicKey *pucSponsorTmpPublicKey, + ECCrefPublicKey *pucResponsePublicKey, + ECCrefPublicKey *pucResponseTmpPublicKey, + void **phKeyHandle) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->GenerateAgreementDataAndKeyWithECC) { + SDFerr(SDF_F_SDF_GENERATEAGREEMENTDATAANDKEYWITHECC, + SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->GenerateAgreementDataAndKeyWithECC( + hSessionHandle, + uiISKIndex, + uiKeyBits, + pucResponseID, + uiResponseIDLength, + pucSponsorID, + uiSponsorIDLength, + pucSponsorPublicKey, + pucSponsorTmpPublicKey, + pucResponsePublicKey, + pucResponseTmpPublicKey, + phKeyHandle)) != SDR_OK) { + SDFerr(SDF_F_SDF_GENERATEAGREEMENTDATAANDKEYWITHECC, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_ExchangeDigitEnvelopeBaseOnECC( + void *hSessionHandle, + unsigned int uiKeyIndex, + unsigned int uiAlgID, + ECCrefPublicKey *pucPublicKey, + ECCCipher *pucEncDataIn, + ECCCipher *pucEncDataOut) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->ExchangeDigitEnvelopeBaseOnECC) { + SDFerr(SDF_F_SDF_EXCHANGEDIGITENVELOPEBASEONECC, + SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if (sdf_vendor) { + if (!(uiAlgID = sdf_vendor->cipher_std2vendor(uiAlgID))) { + SDFerr(SDF_F_SDF_EXCHANGEDIGITENVELOPEBASEONECC, + SDF_R_NOT_SUPPORTED_CIPHER_ALGOR); + return SDR_ALGNOTSUPPORT; + } + } + + if ((ret = sdf_method->ExchangeDigitEnvelopeBaseOnECC( + hSessionHandle, + uiKeyIndex, + uiAlgID, + pucPublicKey, + pucEncDataIn, + pucEncDataOut)) != SDR_OK) { + SDFerr(SDF_F_SDF_EXCHANGEDIGITENVELOPEBASEONECC, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_GenerateKeyWithKEK( + void *hSessionHandle, + unsigned int uiKeyBits, + unsigned int uiAlgID, + unsigned int uiKEKIndex, + unsigned char *pucKey, + unsigned int *puiKeyLength, + void **phKeyHandle) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->GenerateKeyWithKEK) { + SDFerr(SDF_F_SDF_GENERATEKEYWITHKEK, + SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if (sdf_vendor) { + if (!(uiAlgID = sdf_vendor->cipher_std2vendor(uiAlgID))) { + SDFerr(SDF_F_SDF_GENERATEKEYWITHKEK, + SDF_R_NOT_SUPPORTED_CIPHER_ALGOR); + return SDR_ALGNOTSUPPORT; + } + } + + if ((ret = sdf_method->GenerateKeyWithKEK( + hSessionHandle, + uiKeyBits, + uiAlgID, + uiKEKIndex, + pucKey, + puiKeyLength, + phKeyHandle)) != SDR_OK) { + SDFerr(SDF_F_SDF_GENERATEKEYWITHKEK, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_ImportKeyWithKEK( + void *hSessionHandle, + unsigned int uiAlgID, + unsigned int uiKEKIndex, + unsigned char *pucKey, + unsigned int uiKeyLength, + void **phKeyHandle) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->ImportKeyWithKEK) { + SDFerr(SDF_F_SDF_IMPORTKEYWITHKEK, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if (sdf_vendor) { + if (!(uiAlgID = sdf_vendor->cipher_std2vendor(uiAlgID))) { + SDFerr(SDF_F_SDF_IMPORTKEYWITHKEK, + SDF_R_NOT_SUPPORTED_CIPHER_ALGOR); + return SDR_ALGNOTSUPPORT; + } + } + + if ((ret = sdf_method->ImportKeyWithKEK( + hSessionHandle, + uiAlgID, + uiKEKIndex, + pucKey, + uiKeyLength, + phKeyHandle)) != SDR_OK) { + SDFerr(SDF_F_SDF_IMPORTKEYWITHKEK, sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_DestroyKey( + void *hSessionHandle, + void *hKeyHandle) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->DestroyKey) { + SDFerr(SDF_F_SDF_DESTROYKEY, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->DestroyKey( + hSessionHandle, + hKeyHandle)) != SDR_OK) { + SDFerr(SDF_F_SDF_DESTROYKEY, sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_ExternalPublicKeyOperation_RSA( + void *hSessionHandle, + RSArefPublicKey *pucPublicKey, + unsigned char *pucDataInput, + unsigned int uiInputLength, + unsigned char *pucDataOutput, + unsigned int *puiOutputLength) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->ExternalPublicKeyOperation_RSA) { + SDFerr(SDF_F_SDF_EXTERNALPUBLICKEYOPERATION_RSA, + SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->ExternalPublicKeyOperation_RSA( + hSessionHandle, + pucPublicKey, + pucDataInput, + uiInputLength, + pucDataOutput, + puiOutputLength)) != SDR_OK) { + SDFerr(SDF_F_SDF_EXTERNALPUBLICKEYOPERATION_RSA, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_InternalPublicKeyOperation_RSA( + void *hSessionHandle, + unsigned int uiKeyIndex, + unsigned char *pucDataInput, + unsigned int uiInputLength, + unsigned char *pucDataOutput, + unsigned int *puiOutputLength) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->InternalPublicKeyOperation_RSA) { + SDFerr(SDF_F_SDF_INTERNALPUBLICKEYOPERATION_RSA, + SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->InternalPublicKeyOperation_RSA( + hSessionHandle, + uiKeyIndex, + pucDataInput, + uiInputLength, + pucDataOutput, + puiOutputLength)) != SDR_OK) { + SDFerr(SDF_F_SDF_INTERNALPUBLICKEYOPERATION_RSA, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_InternalPrivateKeyOperation_RSA( + void *hSessionHandle, + unsigned int uiKeyIndex, + unsigned char *pucDataInput, + unsigned int uiInputLength, + unsigned char *pucDataOutput, + unsigned int *puiOutputLength) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->InternalPrivateKeyOperation_RSA) { + SDFerr(SDF_F_SDF_INTERNALPRIVATEKEYOPERATION_RSA, + SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->InternalPrivateKeyOperation_RSA( + hSessionHandle, + uiKeyIndex, + pucDataInput, + uiInputLength, + pucDataOutput, + puiOutputLength)) != SDR_OK) { + SDFerr(SDF_F_SDF_INTERNALPRIVATEKEYOPERATION_RSA, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_ExternalVerify_ECC( + void *hSessionHandle, + unsigned int uiAlgID, + ECCrefPublicKey *pucPublicKey, + unsigned char *pucDataInput, + unsigned int uiInputLength, + ECCSignature *pucSignature) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->ExternalVerify_ECC) { + SDFerr(SDF_F_SDF_EXTERNALVERIFY_ECC, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if (sdf_vendor) { + if (!(uiAlgID = sdf_vendor->pkey_std2vendor(uiAlgID))) { + SDFerr(SDF_F_SDF_EXTERNALVERIFY_ECC, + SDF_R_NOT_SUPPORTED_PKEY_ALGOR); + return SDR_ALGNOTSUPPORT; + } + } + + if ((ret = sdf_method->ExternalVerify_ECC( + hSessionHandle, + uiAlgID, + pucPublicKey, + pucDataInput, + uiInputLength, + pucSignature)) != SDR_OK) { + SDFerr(SDF_F_SDF_EXTERNALVERIFY_ECC, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_InternalSign_ECC( + void *hSessionHandle, + unsigned int uiISKIndex, + unsigned char *pucData, + unsigned int uiDataLength, + ECCSignature *pucSignature) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->InternalSign_ECC) { + SDFerr(SDF_F_SDF_INTERNALSIGN_ECC, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->InternalSign_ECC( + hSessionHandle, + uiISKIndex, + pucData, + uiDataLength, + pucSignature)) != SDR_OK) { + SDFerr(SDF_F_SDF_INTERNALSIGN_ECC, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_InternalVerify_ECC( + void *hSessionHandle, + unsigned int uiIPKIndex, + unsigned char *pucData, + unsigned int uiDataLength, + ECCSignature *pucSignature) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->InternalVerify_ECC) { + SDFerr(SDF_F_SDF_INTERNALVERIFY_ECC, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->InternalVerify_ECC( + hSessionHandle, + uiIPKIndex, + pucData, + uiDataLength, + pucSignature)) != SDR_OK) { + SDFerr(SDF_F_SDF_INTERNALVERIFY_ECC, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_ExternalEncrypt_ECC( + void *hSessionHandle, + unsigned int uiAlgID, + ECCrefPublicKey *pucPublicKey, + unsigned char *pucData, + unsigned int uiDataLength, + ECCCipher *pucEncData) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->ExternalEncrypt_ECC) { + SDFerr(SDF_F_SDF_EXTERNALENCRYPT_ECC, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if (sdf_vendor) { + if (!(uiAlgID = sdf_vendor->pkey_std2vendor(uiAlgID))) { + SDFerr(SDF_F_SDF_EXTERNALENCRYPT_ECC, + SDF_R_NOT_SUPPORTED_PKEY_ALGOR); + return SDR_ALGNOTSUPPORT; + } + } + + if ((ret = sdf_method->ExternalEncrypt_ECC( + hSessionHandle, + uiAlgID, + pucPublicKey, + pucData, + uiDataLength, + pucEncData)) != SDR_OK) { + SDFerr(SDF_F_SDF_EXTERNALENCRYPT_ECC, + sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_InternalEncrypt_ECC( + void *hSessionHandle, + unsigned int uiIPKIndex, + unsigned int uiAlgID, + unsigned char *pucData, + unsigned int uiDataLength, + ECCCipher *pucEncData) +{ + int ret = SDR_UNKNOWERR; + ECCCipher *buf = pucEncData; + + if (!sdf_method || !sdf_method->InternalEncrypt_ECC) { + SDFerr(SDF_F_SDF_INTERNALENCRYPT_ECC, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if (pucEncData->L < uiDataLength) { + SDFerr(SDF_F_SDF_INTERNALENCRYPT_ECC, SDF_R_BUFFER_TOO_SMALL); + return SDR_NOBUFFER; + } + + if (sdf_vendor && sdf_vendor->decode_ecccipher) { + if (SDF_NewECCCipher(&buf, uiDataLength) != SDR_OK) { + SDFerr(SDF_F_SDF_INTERNALENCRYPT_ECC, ERR_R_SDF_LIB); + return SDR_UNKNOWERR; + } + } + + if (sdf_vendor && sdf_vendor->pkey_std2vendor) { + if (!(uiAlgID = sdf_vendor->pkey_std2vendor(uiAlgID))) { + SDFerr(SDF_F_SDF_INTERNALENCRYPT_ECC, + SDF_R_NOT_SUPPORTED_PKEY_ALGOR); + ret = SDR_ALGNOTSUPPORT; + goto end; + } + } + + if ((ret = sdf_method->InternalEncrypt_ECC( + hSessionHandle, + uiIPKIndex, + uiAlgID, + pucData, + uiDataLength, + buf)) != SDR_OK) { + SDFerr(SDF_F_SDF_INTERNALENCRYPT_ECC, + sdf_get_error_reason(ret)); + goto end; + } + + if (sdf_vendor && sdf_vendor->decode_ecccipher) { + if (!sdf_vendor->decode_ecccipher(pucEncData, buf)) { + SDFerr(SDF_F_SDF_INTERNALENCRYPT_ECC, ERR_R_SDF_LIB); + ret = SDR_UNKNOWERR; + goto end; + } + } + + /* + { + int i; + unsigned char *p = (unsigned char *)pucEncData; + for (i = 0; i < sizeof(ECCCipher) -1 + uiDataLength; i++) { + printf("%02x", p[i]); + } + printf("\n"); + } + */ + + ret = SDR_OK; + +end: + if (sdf_vendor && sdf_vendor->decode_ecccipher && buf) { + SDF_FreeECCCipher(buf); + } + return ret; +} + +int SDF_InternalDecrypt_ECC( + void *hSessionHandle, + unsigned int uiISKIndex, + unsigned int uiAlgID, + ECCCipher *pucEncData, + unsigned char *pucData, + unsigned int *uiDataLength) +{ + int ret = SDR_UNKNOWERR; + ECCCipher *buf = pucEncData; + + if (!sdf_method || !sdf_method->InternalDecrypt_ECC) { + SDFerr(SDF_F_SDF_INTERNALDECRYPT_ECC, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if (sdf_vendor && sdf_vendor->pkey_std2vendor) { + if (!(uiAlgID = sdf_vendor->pkey_std2vendor(uiAlgID))) { + SDFerr(SDF_F_SDF_INTERNALDECRYPT_ECC, + SDF_R_NOT_SUPPORTED_PKEY_ALGOR); + return SDR_ALGNOTSUPPORT; + } + } + + if (sdf_vendor && sdf_vendor->encode_ecccipher) { + if (SDF_NewECCCipher(&buf, pucEncData->L) != SDR_OK) { + SDFerr(SDF_F_SDF_INTERNALDECRYPT_ECC, ERR_R_SDF_LIB); + return SDR_UNKNOWERR; + } + + if (!sdf_vendor->encode_ecccipher(pucEncData, buf)) { + SDFerr(SDF_F_SDF_INTERNALDECRYPT_ECC, ERR_R_SDF_LIB); + ret = SDR_UNKNOWERR; + goto end; + } + } + + if ((ret = sdf_method->InternalDecrypt_ECC( + hSessionHandle, + uiISKIndex, + uiAlgID, + buf, + pucData, + uiDataLength)) != SDR_OK) { + SDFerr(SDF_F_SDF_INTERNALDECRYPT_ECC, + sdf_get_error_reason(ret)); + goto end; + } + +end: + if (sdf_vendor && sdf_vendor->encode_ecccipher && buf) { + SDF_FreeECCCipher(buf); + } + return ret; +} + +int SDF_Encrypt( + void *hSessionHandle, + void *hKeyHandle, + unsigned int uiAlgID, + unsigned char *pucIV, + unsigned char *pucData, + unsigned int uiDataLength, + unsigned char *pucEncData, + unsigned int *puiEncDataLength) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->Encrypt) { + SDFerr(SDF_F_SDF_ENCRYPT, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if (sdf_vendor) { + if (!(uiAlgID = sdf_vendor->cipher_std2vendor(uiAlgID))) { + SDFerr(SDF_F_SDF_ENCRYPT, + SDF_R_NOT_SUPPORTED_CIPHER_ALGOR); + return SDR_ALGNOTSUPPORT; + } + } + + if ((ret = sdf_method->Encrypt( + hSessionHandle, + hKeyHandle, + uiAlgID, + pucIV, + pucData, + uiDataLength, + pucEncData, + puiEncDataLength)) != SDR_OK) { + SDFerr(SDF_F_SDF_ENCRYPT, sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_Decrypt( + void *hSessionHandle, + void *hKeyHandle, + unsigned int uiAlgID, + unsigned char *pucIV, + unsigned char *pucEncData, + unsigned int uiEncDataLength, + unsigned char *pucData, + unsigned int *puiDataLength) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->Decrypt) { + SDFerr(SDF_F_SDF_DECRYPT, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if (sdf_vendor) { + if (!(uiAlgID = sdf_vendor->cipher_std2vendor(uiAlgID))) { + SDFerr(SDF_F_SDF_DECRYPT, SDF_R_NOT_SUPPORTED_CIPHER_ALGOR); + return SDR_ALGNOTSUPPORT; + } + } + + if ((ret = sdf_method->Decrypt( + hSessionHandle, + hKeyHandle, + uiAlgID, + pucIV, + pucEncData, + uiEncDataLength, + pucData, + puiDataLength)) != SDR_OK) { + SDFerr(SDF_F_SDF_DECRYPT, sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_CalculateMAC( + void *hSessionHandle, + void *hKeyHandle, + unsigned int uiAlgID, + unsigned char *pucIV, + unsigned char *pucData, + unsigned int uiDataLength, + unsigned char *pucMAC, + unsigned int *puiMACLength) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->CalculateMAC) { + SDFerr(SDF_F_SDF_CALCULATEMAC, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if (sdf_vendor) { + if (!(uiAlgID = sdf_vendor->cipher_std2vendor(uiAlgID))) { + SDFerr(SDF_F_SDF_CALCULATEMAC, + SDF_R_NOT_SUPPORTED_CIPHER_ALGOR); + return SDR_ALGNOTSUPPORT; + } + } + + if ((ret = sdf_method->CalculateMAC( + hSessionHandle, + hKeyHandle, + uiAlgID, + pucIV, + pucData, + uiDataLength, + pucMAC, + puiMACLength)) != SDR_OK) { + SDFerr(SDF_F_SDF_CALCULATEMAC, sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_HashInit( + void *hSessionHandle, + unsigned int uiAlgID, + ECCrefPublicKey *pucPublicKey, + unsigned char *pucID, + unsigned int uiIDLength) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->HashInit) { + SDFerr(SDF_F_SDF_HASHINIT, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if (sdf_vendor) { + if (!(uiAlgID = sdf_vendor->digest_std2vendor(uiAlgID))) { + SDFerr(SDF_F_SDF_HASHINIT, SDF_R_NOT_SUPPORTED_DIGEST_ALGOR); + return SDR_ALGNOTSUPPORT; + } + } + + if ((ret = sdf_method->HashInit( + hSessionHandle, + uiAlgID, + pucPublicKey, + pucID, + uiIDLength)) != SDR_OK) { + SDFerr(SDF_F_SDF_HASHINIT, sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_HashUpdate( + void *hSessionHandle, + unsigned char *pucData, + unsigned int uiDataLength) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->HashUpdate) { + SDFerr(SDF_F_SDF_HASHUPDATE, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->HashUpdate( + hSessionHandle, + pucData, + uiDataLength)) != SDR_OK) { + SDFerr(SDF_F_SDF_HASHUPDATE, sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_HashFinal( + void *hSessionHandle, + unsigned char *pucHash, + unsigned int *puiHashLength) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->HashFinal) { + SDFerr(SDF_F_SDF_HASHFINAL, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->HashFinal( + hSessionHandle, + pucHash, + puiHashLength)) != SDR_OK) { + SDFerr(SDF_F_SDF_HASHFINAL, sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_CreateFile( + void *hSessionHandle, + unsigned char *pucFileName, + unsigned int uiNameLen, + unsigned int uiFileSize) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->CreateObject) { + SDFerr(SDF_F_SDF_CREATEFILE, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->CreateObject( + hSessionHandle, + pucFileName, + uiNameLen, + uiFileSize)) != SDR_OK) { + SDFerr(SDF_F_SDF_CREATEFILE, sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_ReadFile( + void *hSessionHandle, + unsigned char *pucFileName, + unsigned int uiNameLen, + unsigned int uiOffset, + unsigned int *puiReadLength, + unsigned char *pucBuffer) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->ReadObject) { + SDFerr(SDF_F_SDF_READFILE, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->ReadObject( + hSessionHandle, + pucFileName, + uiNameLen, + uiOffset, + puiReadLength, + pucBuffer)) != SDR_OK) { + SDFerr(SDF_F_SDF_READFILE, sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_WriteFile( + void *hSessionHandle, + unsigned char *pucFileName, + unsigned int uiNameLen, + unsigned int uiOffset, + unsigned int uiWriteLength, + unsigned char *pucBuffer) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->WriteObject) { + SDFerr(SDF_F_SDF_WRITEFILE, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->WriteObject( + hSessionHandle, + pucFileName, + uiNameLen, + uiOffset, + uiWriteLength, + pucBuffer)) != SDR_OK) { + SDFerr(SDF_F_SDF_WRITEFILE, sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} + +int SDF_DeleteFile( + void *hSessionHandle, + unsigned char *pucFileName, + unsigned int uiNameLen) +{ + int ret = SDR_UNKNOWERR; + + if (!sdf_method || !sdf_method->DeleteObject) { + SDFerr(SDF_F_SDF_DELETEFILE, SDF_R_NOT_INITIALIZED); + return SDR_NOTSUPPORT; + } + + if ((ret = sdf_method->DeleteObject( + hSessionHandle, + pucFileName, + uiNameLen)) != SDR_OK) { + SDFerr(SDF_F_SDF_DELETEFILE, sdf_get_error_reason(ret)); + return ret; + } + + return SDR_OK; +} diff --git a/sdf/sdf_meth.c b/sdf/sdf_meth.c new file mode 100644 index 00000000..c172777c --- /dev/null +++ b/sdf/sdf_meth.c @@ -0,0 +1,143 @@ +/* ==================================================================== + * Copyright (c) 2016 The GmSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the GmSSL Project. + * (http://gmssl.org/)" + * + * 4. The name "GmSSL Project" must not be used to endorse or promote + * products derived from this software without prior written + * permission. For written permission, please contact + * guanzhi1980@gmail.com. + * + * 5. Products derived from this software may not be called "GmSSL" + * nor may "GmSSL" appear in their names without prior written + * permission of the GmSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the GmSSL Project + * (http://gmssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ + +#include +#include +#include +#include +#include "sdf_int.h" + +#define SDFerr(a,b) + +#define SDF_METHOD_BIND_FUNCTION_EX(func,name) \ + sdf->func = (SDF_##func##_FuncPtr)dlsym(sdf->dso, "SDF_"#name) + +#define SDF_METHOD_BIND_FUNCTION(func) \ + SDF_METHOD_BIND_FUNCTION_EX(func,func) + +SDF_METHOD *SDF_METHOD_load_library(const char *so_path) +{ + SDF_METHOD *ret = NULL; + SDF_METHOD *sdf = NULL; + + if (!(sdf = malloc(sizeof(*sdf)))) { + SDFerr(SDF_F_SDF_METHOD_LOAD_LIBRARY, ERR_R_MALLOC_FAILURE); + goto end; + } + memset(sdf, 0, sizeof(*sdf)); + + if (!(sdf->dso = dlopen(so_path, 0))) { + SDFerr(SDF_F_SDF_METHOD_LOAD_LIBRARY, SDF_R_DSO_LOAD_FAILURE); + goto end; + } + + SDF_METHOD_BIND_FUNCTION(OpenDevice); + SDF_METHOD_BIND_FUNCTION(CloseDevice); + SDF_METHOD_BIND_FUNCTION(OpenSession); + SDF_METHOD_BIND_FUNCTION(CloseSession); + SDF_METHOD_BIND_FUNCTION(GetDeviceInfo); + SDF_METHOD_BIND_FUNCTION(GenerateRandom); + SDF_METHOD_BIND_FUNCTION(GetPrivateKeyAccessRight); + SDF_METHOD_BIND_FUNCTION(ReleasePrivateKeyAccessRight); + SDF_METHOD_BIND_FUNCTION(ExportSignPublicKey_RSA); + SDF_METHOD_BIND_FUNCTION(ExportEncPublicKey_RSA); + SDF_METHOD_BIND_FUNCTION(GenerateKeyPair_RSA); + SDF_METHOD_BIND_FUNCTION(GenerateKeyWithIPK_RSA); + SDF_METHOD_BIND_FUNCTION(GenerateKeyWithEPK_RSA); + SDF_METHOD_BIND_FUNCTION(ImportKeyWithISK_RSA); + SDF_METHOD_BIND_FUNCTION(ExchangeDigitEnvelopeBaseOnRSA); + SDF_METHOD_BIND_FUNCTION(ExportSignPublicKey_ECC); + SDF_METHOD_BIND_FUNCTION(ExportEncPublicKey_ECC); + SDF_METHOD_BIND_FUNCTION(GenerateKeyPair_ECC); + SDF_METHOD_BIND_FUNCTION(GenerateKeyWithIPK_ECC); + SDF_METHOD_BIND_FUNCTION(GenerateKeyWithEPK_ECC); + SDF_METHOD_BIND_FUNCTION(ImportKeyWithISK_ECC); + SDF_METHOD_BIND_FUNCTION(GenerateAgreementDataWithECC); + SDF_METHOD_BIND_FUNCTION(GenerateKeyWithECC); + SDF_METHOD_BIND_FUNCTION(GenerateAgreementDataAndKeyWithECC); + SDF_METHOD_BIND_FUNCTION(ExchangeDigitEnvelopeBaseOnECC); + SDF_METHOD_BIND_FUNCTION(GenerateKeyWithKEK); + SDF_METHOD_BIND_FUNCTION(ImportKeyWithKEK); + SDF_METHOD_BIND_FUNCTION(DestroyKey); + SDF_METHOD_BIND_FUNCTION(ExternalPublicKeyOperation_RSA); + //SDF_METHOD_BIND_FUNCTION(InternalPublicKeyOperation_RSA); + SDF_METHOD_BIND_FUNCTION(InternalPrivateKeyOperation_RSA); + SDF_METHOD_BIND_FUNCTION(ExternalVerify_ECC); + SDF_METHOD_BIND_FUNCTION(InternalSign_ECC); + SDF_METHOD_BIND_FUNCTION(InternalVerify_ECC); + SDF_METHOD_BIND_FUNCTION(ExternalEncrypt_ECC); + //SDF_METHOD_BIND_FUNCTION(ExternalDecrypt_ECC); + SDF_METHOD_BIND_FUNCTION(InternalEncrypt_ECC); + SDF_METHOD_BIND_FUNCTION(InternalDecrypt_ECC); + SDF_METHOD_BIND_FUNCTION(Encrypt); + SDF_METHOD_BIND_FUNCTION(Decrypt); + SDF_METHOD_BIND_FUNCTION(CalculateMAC); + SDF_METHOD_BIND_FUNCTION(HashInit); + SDF_METHOD_BIND_FUNCTION(HashUpdate); + SDF_METHOD_BIND_FUNCTION(HashFinal); + SDF_METHOD_BIND_FUNCTION_EX(CreateObject,CreateFile); + SDF_METHOD_BIND_FUNCTION_EX(ReadObject,ReadFile); + SDF_METHOD_BIND_FUNCTION_EX(WriteObject,WriteFile); + SDF_METHOD_BIND_FUNCTION_EX(DeleteObject,DeleteFile); + + ret = sdf; + sdf = NULL; + +end: + SDF_METHOD_free(sdf); + return ret; +} + +void SDF_METHOD_free(SDF_METHOD *meth) +{ + if (meth) free(meth->dso); + free(meth); +} + + diff --git a/sdf/sdf_sansec.c b/sdf/sdf_sansec.c new file mode 100644 index 00000000..67e21e01 --- /dev/null +++ b/sdf/sdf_sansec.c @@ -0,0 +1,371 @@ +/* ==================================================================== + * Copyright (c) 2016 - 2017 The GmSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the GmSSL Project. + * (http://gmssl.org/)" + * + * 4. The name "GmSSL Project" must not be used to endorse or promote + * products derived from this software without prior written + * permission. For written permission, please contact + * guanzhi1980@gmail.com. + * + * 5. Products derived from this software may not be called "GmSSL" + * nor may "GmSSL" appear in their names without prior written + * permission of the GmSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the GmSSL Project + * (http://gmssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ + +#include +#include "sdf.h" +#include "sdf_int.h" +#include "sdf_sansec.h" + + +#define SDFerr(a,b) + +typedef struct { + unsigned int std_id; + unsigned int vendor_id; +} SDF_ALGOR_PAIR; + +static SDF_ALGOR_PAIR sansec_ciphers[] = { + { SGD_SM1, SANSEC_SM1 }, + { SGD_SM1_ECB, SANSEC_SM1_ECB }, + { SGD_SM1_CBC, SANSEC_SM1_CBC }, + { SGD_SM1_CFB, SANSEC_SM1_CFB }, + { SGD_SM1_OFB, SANSEC_SM1_OFB }, + { SGD_SM1_MAC, SANSEC_SM1_MAC }, + { SGD_SM4, SANSEC_SM4 }, + { SGD_SM4_ECB, SANSEC_SM4_ECB }, + { SGD_SM4_CBC, SANSEC_SM4_CBC }, + { SGD_SM4_CFB, SANSEC_SM4_CFB }, + { SGD_SM4_OFB, SANSEC_SM4_OFB }, + { SGD_SM4_MAC, SANSEC_SM4_MAC }, + { SGD_SSF33, SANSEC_SSF33 }, + { SGD_SSF33_ECB, SANSEC_SSF33_ECB }, + { SGD_SSF33_CBC, SANSEC_SSF33_CBC }, + { SGD_SSF33_CFB, SANSEC_SSF33_CFB }, + { SGD_SSF33_OFB, SANSEC_SSF33_OFB }, + { SGD_SSF33_MAC, SANSEC_SSF33_MAC }, + { 0, SANSEC_AES }, + { 0, SANSEC_AES_ECB }, + { 0, SANSEC_AES_CBC }, + { 0, SANSEC_AES_CFB }, + { 0, SANSEC_AES_OFB }, + { 0, SANSEC_AES_MAC }, + { 0, SANSEC_DES }, + { 0, SANSEC_DES_ECB }, + { 0, SANSEC_DES_CBC }, + { 0, SANSEC_DES_CFB }, + { 0, SANSEC_DES_OFB }, + { 0, SANSEC_DES_MAC }, + { 0, SANSEC_3DES }, + { 0, SANSEC_3DES_ECB }, + { 0, SANSEC_3DES_CBC }, + { 0, SANSEC_3DES_CFB }, + { 0, SANSEC_3DES_OFB }, + { 0, SANSEC_3DES_MAC }, +}; + +static unsigned int sansec_cipher_vendor2std(unsigned int vendor_id) +{ + size_t i; + for (i = 0; i < sizeof(sansec_ciphers)/sizeof(sansec_ciphers[0]); i++) { + if (vendor_id == sansec_ciphers[i].vendor_id) { + return sansec_ciphers[i].std_id; + } + } + return 0; +} + +static unsigned int sansec_cipher_std2vendor(unsigned int std_id) +{ + size_t i; + for (i = 0; i < sizeof(sansec_ciphers)/sizeof(sansec_ciphers[0]); i++) { + if (std_id == sansec_ciphers[i].std_id) { + return sansec_ciphers[i].vendor_id; + } + } + return 0; +} + +static unsigned int sansec_cipher_cap(unsigned int vendor_cap) +{ + unsigned int std_cap = 0; + size_t i; + + for (i = 0; i < sizeof(sansec_ciphers)/sizeof(sansec_ciphers[0]); i++) { + if (vendor_cap & sansec_ciphers[i].vendor_id) { + std_cap |= sansec_ciphers[i].std_id; + } + } + + return std_cap; +} + +static SDF_ALGOR_PAIR sansec_digests[] = { + { SGD_SM3, SANSEC_SM3 }, + { SGD_SHA1, SANSEC_SHA1 }, + { SGD_SHA256, SANSEC_SHA256 }, + { 0, SANSEC_SHA512 }, + { 0, SANSEC_SHA384 }, + { 0, SANSEC_SHA224 }, + { 0, SANSEC_MD5 }, +}; + +static unsigned int sansec_digest_vendor2std(unsigned int vendor_id) +{ + size_t i; + for (i = 0; i < sizeof(sansec_digests)/sizeof(sansec_digests[0]); i++) { + if (vendor_id == sansec_digests[i].vendor_id) { + return sansec_digests[i].std_id; + } + } + return 0; +} + +static unsigned int sansec_digest_std2vendor(unsigned int std_id) +{ + size_t i; + for (i = 0; i < sizeof(sansec_digests)/sizeof(sansec_digests[0]); i++) { + if (std_id == sansec_digests[i].std_id) { + return sansec_digests[i].vendor_id; + } + } + return 0; +} + +static unsigned int sansec_digest_cap(unsigned int vendor_cap) +{ + unsigned int std_cap = 0; + size_t i; + + for (i = 0; i < sizeof(sansec_digests)/sizeof(sansec_digests[0]); i++) { + if (vendor_cap & sansec_digests[i].vendor_id) { + std_cap |= sansec_digests[i].std_id; + } + } + + return std_cap; +} + +static SDF_ALGOR_PAIR sansec_pkeys[] = { + { SGD_RSA,SANSEC_RSA }, + { SGD_RSA_SIGN,SANSEC_RSA_SIGN }, + { SGD_RSA_ENC,SANSEC_RSA_ENC }, + { SGD_SM2,SANSEC_SM2 }, + { SGD_SM2_1,SANSEC_SM2_1 }, + { SGD_SM2_2,SANSEC_SM2_2 }, + { SGD_SM2_3,SANSEC_SM2_3 }, +}; + +static unsigned int sansec_pkey_vendor2std(unsigned int vendor_id) +{ + size_t i; + for (i = 0; i < sizeof(sansec_pkeys)/sizeof(sansec_pkeys[0]); i++) { + if (vendor_id == sansec_pkeys[i].vendor_id) { + return sansec_pkeys[i].std_id; + } + } + return 0; +} + +static unsigned int sansec_pkey_std2vendor(unsigned int std_id) +{ + size_t i; + for (i = 0; i < sizeof(sansec_pkeys)/sizeof(sansec_pkeys[0]); i++) { + if (std_id == sansec_pkeys[i].std_id) { + return sansec_pkeys[i].vendor_id; + } + } + return 0; +} + +static unsigned int sansec_pkey_cap(unsigned int vendor_cap) +{ + unsigned int std_cap = 0; + size_t i; + + for (i = 0; i < sizeof(sansec_pkeys)/sizeof(sansec_pkeys[0]); i++) { + if (vendor_cap & sansec_pkeys[i].vendor_id) { + std_cap |= sansec_pkeys[i].std_id; + } + } + + return std_cap; +} + +static int sansec_encode_ecccipher(const ECCCipher *ec, void *vendor) +{ + int ret; + SANSEC_ECCCipher *sansec = vendor; + ret = sizeof(SANSEC_ECCCipher); + + if (ec->L > sizeof(sansec->C)) { + SDFerr(SDF_F_SANSEC_ENCODE_ECCCIPHER, + SDF_R_INVALID_SANSEC_ECCCIPHER_LENGTH); + return 0; + } + + if (vendor) { + sansec->clength = ec->L; + memcpy(sansec->x, ec->x, sizeof(ec->x)); + memcpy(sansec->y, ec->y, sizeof(ec->y)); + memcpy(sansec->M, ec->M, sizeof(ec->M)); + memset(sansec->M + sizeof(ec->M), 0, sizeof(sansec->M) - sizeof(ec->M)); + memcpy(sansec->C, ec->C, ec->L); + memset(sansec->C + ec->L, 0, sizeof(sansec->C) - ec->L); + } + + return ret; +} + +static int sansec_decode_ecccipher(ECCCipher *ec, const void *vendor) +{ + int ret; + const SANSEC_ECCCipher *sansec = vendor; + ret = sizeof(ECCCipher) -1 + sansec->clength; + + if (sansec->clength > sizeof(sansec->C)) { + SDFerr(SDF_F_SANSEC_DECODE_ECCCIPHER, + SDF_R_INVALID_SANSEC_ECCCIPHER_LENGTH); + return 0; + } + + if (ec) { + memcpy(ec->x, sansec->x, sizeof(ec->x)); + memcpy(ec->y, sansec->y, sizeof(ec->y)); + memcpy(ec->M, sansec->M, sizeof(ec->M)); + ec->L = sansec->clength; + memcpy(ec->C, sansec->C, sansec->clength); + } + + return ret; +} +/* +static SDF_ERR_REASON sansec_errors[] = { + { SANSEC_BASE, SDF_R_SANSEC_BASE }, + { SANSEC_INVALID_USER, SDF_R_SANSEC_INVALID_USER }, + { SANSEC_INVALID_AUTHENCODE, SDF_R_SANSEC_INVALID_AUTHENCODE }, + { SANSEC_PROTOCOL_VERSION_ERROR, SDF_R_SANSEC_PROTOCOL_VERSION_ERROR }, + { SANSEC_INVALID_COMMAND, SDF_R_SANSEC_INVALID_COMMAND }, + { SANSEC_INVALID_PARAMETERS, SDF_R_SANSEC_INVALID_PARAMETERS }, + { SANSEC_FILE_ALREADY_EXIST, SDF_R_SANSEC_FILE_ALREADY_EXIST }, + { SANSEC_SYNC_ERROR, SDF_R_SANSEC_SYNC_ERROR }, + { SANSEC_SYNC_LOGIN_ERROR, SDF_R_SANSEC_SYNC_LOGIN_ERROR }, + { SANSEC_SOCKET_TIMEOUT, SDF_R_SANSEC_SOCKET_TIMEOUT }, + { SANSEC_CONNECT_ERROR, SDF_R_SANSEC_CONNECT_ERROR }, + { SANSEC_SET_SOCKET_OPTION_ERROR, SDF_R_SANSEC_SET_SOCKET_OPTION_ERROR }, + { SANSEC_SOCKET_SEND_ERROR, SDF_R_SANSEC_SOCKET_SEND_ERROR }, + { SANSEC_SOCKET_RECV_ERROR, SDF_R_SANSEC_SOCKET_RECV_ERROR }, + { SANSEC_SOCKET_RECV_0, SDF_R_SANSEC_SOCKET_RECV_0 }, + { SANSEC_SEM_TIMEOUT, SDF_R_SANSEC_SEM_TIMEOUT }, + { SANSEC_NO_AVAILABLE_HSM, SDF_R_SANSEC_NO_AVAILABLE_HSM }, + { SANSEC_NO_AVAILABLE_CSM, SDF_R_SANSEC_NO_AVAILABLE_CSM }, + { SANSEC_CONFIG_ERROR, SDF_R_SANSEC_CONFIG_ERROR }, + { SANSEC_CARD_BASE, SDF_R_SANSEC_CARD_BASE }, + { SANSEC_CARD_UNKNOW_ERROR, SDF_R_SANSEC_CARD_UNKNOW_ERROR }, + { SANSEC_CARD_NOT_SUPPORTED, SDF_R_SANSEC_CARD_NOT_SUPPORTED }, + { SANSEC_CARD_COMMMUCATION_FAILED, SDF_R_SANSEC_CARD_COMMMUCATION_FAILED }, + { SANSEC_CARD_HARDWARE_FAILURE, SDF_R_SANSEC_CARD_HARDWARE_FAILURE }, + { SANSEC_CARD_OPEN_DEVICE_FAILED, SDF_R_SANSEC_CARD_OPEN_DEVICE_FAILED }, + { SANSEC_CARD_OPEN_SESSION_FAILED, SDF_R_SANSEC_CARD_OPEN_SESSION_FAILED }, + { SANSEC_CARD_PRIVATE_KEY_ACCESS_DENYED, SDF_R_SANSEC_CARD_PRIVATE_KEY_ACCESS_DENYED }, + { SANSEC_CARD_KEY_NOT_EXIST, SDF_R_SANSEC_CARD_KEY_NOT_EXIST }, + { SANSEC_CARD_ALGOR_NOT_SUPPORTED, SDF_R_SANSEC_CARD_ALGOR_NOT_SUPPORTED }, + { SANSEC_CARD_ALG_MODE_NOT_SUPPORTED, SDF_R_SANSEC_CARD_ALG_MODE_NOT_SUPPORTED }, + { SANSEC_CARD_PUBLIC_KEY_OPERATION_ERROR, SDF_R_SANSEC_CARD_PUBLIC_KEY_OPERATION_ERROR }, + { SANSEC_CARD_PRIVATE_KEY_OPERATION_ERROR, SDF_R_SANSEC_CARD_PRIVATE_KEY_OPERATION_ERROR }, + { SANSEC_CARD_SIGN_ERROR, SDF_R_SANSEC_CARD_SIGN_ERROR }, + { SANSEC_CARD_VERIFY_ERROR, SDF_R_SANSEC_CARD_VERIFY_ERROR }, + { SANSEC_CARD_SYMMETRIC_ALGOR_ERROR, SDF_R_SANSEC_CARD_SYMMETRIC_ALGOR_ERROR }, + { SANSEC_CARD_STEP_ERROR, SDF_R_SANSEC_CARD_STEP_ERROR }, + { SANSEC_CARD_FILE_SIZE_ERROR, SDF_R_SANSEC_CARD_FILE_SIZE_ERROR }, + { SANSEC_CARD_FILE_NOT_EXIST, SDF_R_SANSEC_CARD_FILE_NOT_EXIST }, + { SANSEC_CARD_FILE_OFFSET_ERROR, SDF_R_SANSEC_CARD_FILE_OFFSET_ERROR }, + { SANSEC_CARD_KEY_TYPE_ERROR, SDF_R_SANSEC_CARD_KEY_TYPE_ERROR }, + { SANSEC_CARD_KEY_ERROR, SDF_R_SANSEC_CARD_KEY_ERROR }, + { SANSEC_CARD_BUFFER_TOO_SMALL, SDF_R_SANSEC_CARD_BUFFER_TOO_SMALL }, + { SANSEC_CARD_DATA_PADDING_ERROR, SDF_R_SANSEC_CARD_DATA_PADDING_ERROR }, + { SANSEC_CARD_DATA_SIZE, SDF_R_SANSEC_CARD_DATA_SIZE }, + { SANSEC_CARD_CRYPTO_NOT_INITED, SDF_R_SANSEC_CARD_CRYPTO_NOT_INITED }, + { SANSEC_CARD_MANAGEMENT_DENYED, SDF_R_SANSEC_CARD_MANAGEMENT_DENYED }, + { SANSEC_CARD_OPERATION_DENYED, SDF_R_SANSEC_CARD_OPERATION_DENYED }, + { SANSEC_CARD_DEVICE_STATUS_ERROR, SDF_R_SANSEC_CARD_DEVICE_STATUS_ERROR }, + { SANSEC_CARD_LOGIN_ERROR, SDF_R_SANSEC_CARD_LOGIN_ERROR }, + { SANSEC_CARD_USERID_ERROR, SDF_R_SANSEC_CARD_USERID_ERROR }, + { SANSEC_CARD_PARAMENT_ERROR, SDF_R_SANSEC_CARD_PARAMENT_ERROR }, + { SANSEC_CARD_MANAGEMENT_DENYED_05, SDF_R_SANSEC_CARD_MANAGEMENT_DENYED_05 }, + { SANSEC_CARD_OPERATION_DENYED_05, SDF_R_SANSEC_CARD_OPERATION_DENYED_05 }, + { SANSEC_CARD_DEVICE_STATUS_ERROR_05, SDF_R_SANSEC_CARD_DEVICE_STATUS_ERROR_05 }, + { SANSEC_CARD_LOGIN_ERROR_05, SDF_R_SANSEC_CARD_LOGIN_ERROR_05 }, + { SANSEC_CARD_USERID_ERROR_05, SDF_R_SANSEC_CARD_USERID_ERROR_05 }, + { SANSEC_CARD_PARAMENT_ERROR_05, SDF_R_SANSEC_CARD_PARAMENT_ERROR_05 }, + { SANSEC_CARD_READER_BASE, SDF_R_SANSEC_CARD_READER_BASE }, + { SANSEC_CARD_READER_PIN_ERROR, SDF_R_SANSEC_CARD_READER_PIN_ERROR }, + { SANSEC_CARD_READER_NO_CARD, SDF_R_SANSEC_CARD_READER_NO_CARD }, + { SANSEC_CARD_READER_CARD_INSERT, SDF_R_SANSEC_CARD_READER_CARD_INSERT }, + { SANSEC_CARD_READER_CARD_INSERT_TYPE, SDF_R_SANSEC_CARD_READER_CARD_INSERT_TYPE }, +}; +*/ + +static unsigned long sansec_get_error_reason(int err) +{ +/* + size_t i = 0; + for (i = 0; i < OSSL_NELEM(sansec_errors); i++) { + if (err == sansec_errors[i].err) { + return sansec_errors[i].reason; + } + } +*/ + return 0; +} + +SDF_VENDOR sdf_sansec = { + "sansec", + sansec_cipher_vendor2std, + sansec_cipher_std2vendor, + sansec_cipher_cap, + sansec_digest_vendor2std, + sansec_digest_std2vendor, + sansec_digest_cap, + sansec_pkey_vendor2std, + sansec_pkey_std2vendor, + sansec_pkey_cap, + sansec_encode_ecccipher, + sansec_decode_ecccipher, + sansec_get_error_reason, +}; diff --git a/sdf/sdf_sansec.h b/sdf/sdf_sansec.h new file mode 100644 index 00000000..b7fae475 --- /dev/null +++ b/sdf/sdf_sansec.h @@ -0,0 +1,192 @@ +/* ==================================================================== + * Copyright (c) 2016 - 2017 The GmSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the GmSSL Project. + * (http://gmssl.org/)" + * + * 4. The name "GmSSL Project" must not be used to endorse or promote + * products derived from this software without prior written + * permission. For written permission, please contact + * guanzhi1980@gmail.com. + * + * 5. Products derived from this software may not be called "GmSSL" + * nor may "GmSSL" appear in their names without prior written + * permission of the GmSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the GmSSL Project + * (http://gmssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ +#ifndef GMSSL_SDF_SANSEC_H +#define GMSSL_SDF_SANSEC_H + +#include "sgd.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define SANSEC_SM1 (SGD_SM1) +#define SANSEC_SM1_ECB (SANSEC_SM1|SGD_ECB) +#define SANSEC_SM1_CBC (SANSEC_SM1|SGD_CBC) +#define SANSEC_SM1_CFB (SANSEC_SM1|SGD_CFB) +#define SANSEC_SM1_OFB (SANSEC_SM1|SGD_OFB) +#define SANSEC_SM1_MAC (SANSEC_SM1|SGD_MAC) + +#define SANSEC_SM4 0x00002000 +#define SANSEC_SM4_ECB (SANSEC_SM4|SGD_ECB) +#define SANSEC_SM4_CBC (SANSEC_SM4|SGD_CBC) +#define SANSEC_SM4_CFB (SANSEC_SM4|SGD_CFB) +#define SANSEC_SM4_OFB (SANSEC_SM4|SGD_OFB) +#define SANSEC_SM4_MAC (SANSEC_SM4|SGD_MAC) + +#define SANSEC_SSF33 (SGD_SSF33) +#define SANSEC_SSF33_ECB (SANSEC_SSF33|SGD_ECB) +#define SANSEC_SSF33_CBC (SANSEC_SSF33|SGD_CBC) +#define SANSEC_SSF33_CFB (SANSEC_SSF33|SGD_CFB) +#define SANSEC_SSF33_OFB (SANSEC_SSF33|SGD_OFB) +#define SANSEC_SSF33_MAC (SANSEC_SSF33|SGD_MAC) + +#define SANSEC_AES 0x00000400 +#define SANSEC_AES_ECB (SANSEC_AES|SGD_ECB) +#define SANSEC_AES_CBC (SANSEC_AES|SGD_CBC) +#define SANSEC_AES_CFB (SANSEC_AES|SGD_CFB) +#define SANSEC_AES_OFB (SANSEC_AES|SGD_OFB) +#define SANSEC_AES_MAC (SANSEC_AES|SGD_MAC) + +#define SANSEC_DES 0x00004000 +#define SANSEC_DES_ECB (SANSEC_DES|SGD_ECB) +#define SANSEC_DES_CBC (SANSEC_DES|SGD_CBC) +#define SANSEC_DES_CFB (SANSEC_DES|SGD_CFB) +#define SANSEC_DES_OFB (SANSEC_DES|SGD_OFB) +#define SANSEC_DES_MAC (SANSEC_DES|SGD_MAC) + +#define SANSEC_3DES 0x00000800 +#define SANSEC_3DES_ECB (SANSEC_3DES|SGD_ECB) +#define SANSEC_3DES_CBC (SANSEC_3DES|SGD_CBC) +#define SANSEC_3DES_CFB (SANSEC_3DES|SGD_CFB) +#define SANSEC_3DES_OFB (SANSEC_3DES|SGD_OFB) +#define SANSEC_3DES_MAC (SANSEC_3DES|SGD_MAC) + +#define SANSEC_SM3 (SGD_SM3) +#define SANSEC_SHA1 (SGD_SHA1) +#define SANSEC_SHA256 (SGD_SHA256) +#define SANSEC_SHA512 0x00000008 +#define SANSEC_SHA384 0x00000010 +#define SANSEC_SHA224 0x00000020 +#define SANSEC_MD5 0x00000080 + +#define SANSEC_RSA (SGD_RSA) +#define SANSEC_RSA_SIGN (SGD_RSA_SIGN) +#define SANSEC_RSA_ENC 0x00010200 +#define SANSEC_SM2 (SGD_SM2) +#define SANSEC_SM2_1 (SGD_SM2_1) +#define SANSEC_SM2_2 (SGD_SM2_2) +#define SANSEC_SM2_3 (SGD_SM2_3) + +#define SANSEC_BASE (SDR_BASE + 0x00010000) +#define SANSEC_INVALID_USER (SANSEC_BASE + 0x00000001) +#define SANSEC_INVALID_AUTHENCODE (SANSEC_BASE + 0x00000002) +#define SANSEC_PROTOCOL_VERSION_ERROR (SANSEC_BASE + 0x00000003) +#define SANSEC_INVALID_COMMAND (SANSEC_BASE + 0x00000004) +#define SANSEC_INVALID_PARAMETERS (SANSEC_BASE + 0x00000005) +#define SANSEC_FILE_ALREADY_EXIST (SANSEC_BASE + 0x00000006) +#define SANSEC_SYNC_ERROR (SANSEC_BASE + 0x00000007) +#define SANSEC_SYNC_LOGIN_ERROR (SANSEC_BASE + 0x00000008) +#define SANSEC_SOCKET_TIMEOUT (SANSEC_BASE + 0x00000100) +#define SANSEC_CONNECT_ERROR (SANSEC_BASE + 0x00000101) +#define SANSEC_SET_SOCKET_OPTION_ERROR (SANSEC_BASE + 0x00000102) +#define SANSEC_SOCKET_SEND_ERROR (SANSEC_BASE + 0x00000104) +#define SANSEC_SOCKET_RECV_ERROR (SANSEC_BASE + 0x00000105) +#define SANSEC_SOCKET_RECV_0 (SANSEC_BASE + 0x00000106) +#define SANSEC_SEM_TIMEOUT (SANSEC_BASE + 0x00000200) +#define SANSEC_NO_AVAILABLE_HSM (SANSEC_BASE + 0x00000201) +#define SANSEC_NO_AVAILABLE_CSM (SANSEC_BASE + 0x00000202) +#define SANSEC_CONFIG_ERROR (SANSEC_BASE + 0x00000301) +#define SANSEC_CARD_BASE (SDR_BASE + 0x00020000) +#define SANSEC_CARD_UNKNOW_ERROR (SANSEC_CARD_BASE + 0x00000001) +#define SANSEC_CARD_NOT_SUPPORTED (SANSEC_CARD_BASE + 0x00000002) +#define SANSEC_CARD_COMMMUCATION_FAILED (SANSEC_CARD_BASE + 0x00000003) +#define SANSEC_CARD_HARDWARE_FAILURE (SANSEC_CARD_BASE + 0x00000004) +#define SANSEC_CARD_OPEN_DEVICE_FAILED (SANSEC_CARD_BASE + 0x00000005) +#define SANSEC_CARD_OPEN_SESSION_FAILED (SANSEC_CARD_BASE + 0x00000006) +#define SANSEC_CARD_PRIVATE_KEY_ACCESS_DENYED (SANSEC_CARD_BASE + 0x00000007) +#define SANSEC_CARD_KEY_NOT_EXIST (SANSEC_CARD_BASE + 0x00000008) +#define SANSEC_CARD_ALGOR_NOT_SUPPORTED (SANSEC_CARD_BASE + 0x00000009) +#define SANSEC_CARD_ALG_MODE_NOT_SUPPORTED (SANSEC_CARD_BASE + 0x00000010) +#define SANSEC_CARD_PUBLIC_KEY_OPERATION_ERROR (SANSEC_CARD_BASE + 0x00000011) +#define SANSEC_CARD_PRIVATE_KEY_OPERATION_ERROR (SANSEC_CARD_BASE + 0x00000012) +#define SANSEC_CARD_SIGN_ERROR (SANSEC_CARD_BASE + 0x00000013) +#define SANSEC_CARD_VERIFY_ERROR (SANSEC_CARD_BASE + 0x00000014) +#define SANSEC_CARD_SYMMETRIC_ALGOR_ERROR (SANSEC_CARD_BASE + 0x00000015) +#define SANSEC_CARD_STEP_ERROR (SANSEC_CARD_BASE + 0x00000016) +#define SANSEC_CARD_FILE_SIZE_ERROR (SANSEC_CARD_BASE + 0x00000017) +#define SANSEC_CARD_FILE_NOT_EXIST (SANSEC_CARD_BASE + 0x00000018) +#define SANSEC_CARD_FILE_OFFSET_ERROR (SANSEC_CARD_BASE + 0x00000019) +#define SANSEC_CARD_KEY_TYPE_ERROR (SANSEC_CARD_BASE + 0x00000020) +#define SANSEC_CARD_KEY_ERROR (SANSEC_CARD_BASE + 0x00000021) +#define SANSEC_CARD_BUFFER_TOO_SMALL (SANSEC_CARD_BASE + 0x00000101) +#define SANSEC_CARD_DATA_PADDING_ERROR (SANSEC_CARD_BASE + 0x00000102) +#define SANSEC_CARD_DATA_SIZE (SANSEC_CARD_BASE + 0x00000103) +#define SANSEC_CARD_CRYPTO_NOT_INITED (SANSEC_CARD_BASE + 0x00000104) +#define SANSEC_CARD_MANAGEMENT_DENYED (SANSEC_CARD_BASE + 0x00001001) +#define SANSEC_CARD_OPERATION_DENYED (SANSEC_CARD_BASE + 0x00001002) +#define SANSEC_CARD_DEVICE_STATUS_ERROR (SANSEC_CARD_BASE + 0x00001003) +#define SANSEC_CARD_LOGIN_ERROR (SANSEC_CARD_BASE + 0x00001011) +#define SANSEC_CARD_USERID_ERROR (SANSEC_CARD_BASE + 0x00001012) +#define SANSEC_CARD_PARAMENT_ERROR (SANSEC_CARD_BASE + 0x00001013) +#define SANSEC_CARD_MANAGEMENT_DENYED_05 (SANSEC_CARD_BASE + 0x00000801) +#define SANSEC_CARD_OPERATION_DENYED_05 (SANSEC_CARD_BASE + 0x00000802) +#define SANSEC_CARD_DEVICE_STATUS_ERROR_05 (SANSEC_CARD_BASE + 0x00000803) +#define SANSEC_CARD_LOGIN_ERROR_05 (SANSEC_CARD_BASE + 0x00000811) +#define SANSEC_CARD_USERID_ERROR_05 (SANSEC_CARD_BASE + 0x00000812) +#define SANSEC_CARD_PARAMENT_ERROR_05 (SANSEC_CARD_BASE + 0x00000813) +#define SANSEC_CARD_READER_BASE (SDR_BASE + 0x00030000) +#define SANSEC_CARD_READER_PIN_ERROR (SANSEC_CARD_READER_BASE + 0x000063CE) +#define SANSEC_CARD_READER_NO_CARD (SANSEC_CARD_READER_BASE + 0x0000FF01) +#define SANSEC_CARD_READER_CARD_INSERT (SANSEC_CARD_READER_BASE + 0x0000FF02) +#define SANSEC_CARD_READER_CARD_INSERT_TYPE (SANSEC_CARD_READER_BASE + 0x0000FF03) + +#pragma pack(1) +typedef struct { + unsigned int clength; + unsigned char x[ECCref_MAX_LEN]; + unsigned char y[ECCref_MAX_LEN]; + unsigned char C[136]; + unsigned char M[ECCref_MAX_LEN]; +} SANSEC_ECCCipher; +#pragma pack() + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tools/sdfutil.c b/sdf/sdfutil.c similarity index 57% rename from tools/sdfutil.c rename to sdf/sdfutil.c index 2847b7f5..248a3b48 100644 --- a/tools/sdfutil.c +++ b/sdf/sdfutil.c @@ -50,13 +50,8 @@ # include # include # include -# include -# include -# include -# include -# include -# include -# include "apps.h" +#include "sdf.h" +#include "sdf_ext.h" # define OP_NONE 0 @@ -70,129 +65,152 @@ # define OP_EXPORTOBJ 8 # define OP_DELOBJ 9 -OPTIONS sdf_options[] = { - {"help", OPT_HELP, '-', "Display this summary"}, - {"lib", OPT_LIB, 's', "Vendor's SDF dynamic library"}, - {"vendor", OPT_VENDOR, 's', "Vendor name"}, - {"printdevinfo", OPT_PRINTDEVINFO, '-', "Print device information"}, - {"printsm2sign", OPT_PRINTSM2SIGN, 's', "Print SM2 signing key with key index"}, - {"printsm2enc", OPT_PRINTSM2ENC, 's', "Print SM2 encryption key with key index"}, - {"printrsasign", OPT_PRINTRSASIGN, 's', "Print RSA signing key with key index"}, - {"printrsaenc", OPT_PRINTRSAENC, 's', "Print RSA encryption key with key index"}, - {"accesskey", OPT_ACCESSKEY, 's', "Access private key with the key index number"}, - {"pass", OPT_PASS, 's', "Passphrase source for accessing private key"}, - {"importobj", OPT_IMPORTOBJ, 's', "Import data object into device"}, - {"exportobj", OPT_EXPORTOBJ, 's', "Export data object from device"}, - {"delobj", OPT_DELOBJ, 's', "Delete data object from device"}, - {"in", OPT_IN, '<', "File to be imported from"}, - {"out", OPT_OUT, '>', "File to be exported to"}, - {NULL} -}; -int sdf_main(int argc, char **argv) +void print_usage(FILE *out, const char *prog) +{ + fprintf(out, "Usage: %s commands\n", prog); + fprintf(out, "\n"); + fprintf(out, "Commands:\n"); + fprintf(out, " -help print the usage message\n"); + fprintf(out, " -lib Vendor's SDF dynamic library\n"); + fprintf(out, " -vendor Vendor name\n"); + fprintf(out, " -printdevinfo Print device information\n"); + fprintf(out, " -printsm2sign Print SM2 signing key with key index\n"); + fprintf(out, " -printsm2enc Print SM2 encryption key with key index\n"); + fprintf(out, " -printrsasign Print RSA signing key with key index\n"); + fprintf(out, " -printrsaenc Print RSA encryption key with key index\n"); + fprintf(out, " -accesskey Access private key with the key index number\n"); + fprintf(out, " -pass Passphrase source for accessing private key\n"); + fprintf(out, " -importobj Import data object into device\n"); + fprintf(out, " -exportobj Export data object from device\n"); + fprintf(out, " -delobj Delete data object from device\n"); + fprintf(out, " -in File to be imported from\n"); + fprintf(out, " -out File to be exported to\n"); + +} + +int main(int argc, char **argv) { int ret = 1; char *infile = NULL, *outfile = NULL, *prog; char *objname = NULL, *passarg = NULL, *pass = NULL; - BIO *in = NULL, *out = NULL; + FILE *in = NULL, *out = NULL; char *lib = NULL, *vendor = NULL; - unsigned char *buf = NULL; + unsigned char buf[SDF_MAX_FILE_SIZE]; unsigned int ulen; int len, key_idx = -1; - OPTION_CHOICE o; + + int o; int op = OP_NONE; void *hDev = NULL; void *hSession = NULL; - prog = opt_init(argc, argv, sdf_options); - while ((o = opt_next()) != OPT_EOF) { - switch (o) { - case OPT_EOF: - case OPT_ERR: + argc--; + argv++; + while (argc >= 1) { + if (!strcmp(*argv, "-help")) { opthelp: - BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); + print_usage(stdout, prog); goto end; - case OPT_HELP: - opt_help(sdf_options); - ret = 0; - goto end; - case OPT_LIB: - lib = opt_arg(); - break; - case OPT_VENDOR: - vendor = opt_arg(); - break; - case OPT_PRINTDEVINFO: + + } else if (!strcmp(*argv, "-lib")) { + if (--argc < 1) goto bad; + lib = *(++argv); + + } else if (!strcmp(*argv, "-vendor")) { + if (--argc < 1) goto bad; + vendor = *(++argv); + + } else if (!strcmp(*argv, "-printdevinfo")) { if (op) goto opthelp; op = OP_PRINTDEVINFO; - break; - case OPT_PRINTSM2SIGN: + if (--argc < 1) goto bad; + key_idx = atoi(*(++argv)); + + } else if (!strcmp(*argv, "-printsm2sign")) { if (op) goto opthelp; op = OP_PRINTSM2SIGN; - key_idx = atoi(opt_arg()); - break; - case OPT_PRINTSM2ENC: + if (--argc < 1) goto bad; + key_idx = atoi(*(++argv)); + + } else if (!strcmp(*argv, "-printsm2enc")) { if (op) goto opthelp; op = OP_PRINTSM2ENC; - key_idx = atoi(opt_arg()); - break; - case OPT_PRINTRSASIGN: + if (--argc < 1) goto bad; + key_idx = atoi(*(++argv)); + + } else if (!strcmp(*argv, "-printrsasign")) { if (op) goto opthelp; op = OP_PRINTRSASIGN; - key_idx = atoi(opt_arg()); - break; - case OPT_PRINTRSAENC: + if (--argc < 1) goto bad; + key_idx = atoi(*(++argv)); + + } else if (!strcmp(*argv, "-printrsaenc")) { if (op) goto opthelp; op = OP_PRINTRSAENC; - key_idx = atoi(opt_arg()); - break; - case OPT_ACCESSKEY: - key_idx = atoi(opt_arg()); - break; - case OPT_PASS: - passarg = opt_arg(); - break; - case OPT_IMPORTOBJ: + if (--argc < 1) goto bad; + key_idx = atoi(*(++argv)); + + } else if (!strcmp(*argv, "-accesskey")) { + if (--argc < 1) goto bad; + key_idx = atoi(*(++argv)); + + } else if (!strcmp(*argv, "-pass")) { + if (--argc < 1) goto bad; + pass = *(++argv); + + } else if (!strcmp(*argv, "-importobj")) { if (op) goto opthelp; op = OP_IMPORTOBJ; - objname = opt_arg(); - break; - case OPT_EXPORTOBJ: + if (--argc < 1) goto bad; + objname = *(++argv); + + } else if (!strcmp(*argv, "-exportobj")) { if (op) goto opthelp; op = OP_EXPORTOBJ; - objname = opt_arg(); - break; - case OPT_DELOBJ: + if (--argc < 1) goto bad; + objname = *(++argv); + + } else if (!strcmp(*argv, "-delobj")) { if (op) goto opthelp; op = OP_DELOBJ; - objname = opt_arg(); - break; - case OPT_IN: - infile = opt_arg(); - break; - case OPT_OUT: - outfile = opt_arg(); + if (--argc < 1) goto bad; + objname = *(++argv); + + } else if (!strcmp(*argv, "-in")) { + if (--argc < 1) goto bad; + infile = *(++argv); + + } else if (!strcmp(*argv, "-out")) { + if (--argc < 1) goto bad; + outfile = *(++argv); + + } else { break; } + + argc--; + argv++; } - argc = opt_num_rest(); + + if (argc != 0) goto opthelp; if (!lib) { - BIO_printf(bio_err, "Option '-lib' required\n"); -x509 goto opthelp; + fprintf(stderr, "Option '-lib' required\n"); + goto opthelp; } if (SDF_LoadLibrary(lib, vendor) != SDR_OK) { - ERR_print_errors(bio_err); + //ERR_print_errors(stderr); goto end; } @@ -203,7 +221,7 @@ x509 goto opthelp; if (SDF_OpenDevice(&hDev) != SDR_OK || SDF_OpenSession(hDev, &hSession) != SDR_OK) { - ERR_print_errors(bio_err); + //ERR_print_errors(stderr); goto end; } @@ -213,7 +231,7 @@ x509 goto opthelp; case OP_PRINTSM2ENC: case OP_PRINTRSASIGN: case OP_PRINTRSAENC: - if (!(out = bio_open_default(outfile, 'w', FORMAT_TEXT))) { + if (!(out = fopen(outfile, "w"))) { goto opthelp; } break; @@ -226,7 +244,7 @@ x509 goto opthelp; case OP_PRINTRSAENC: case OP_ACCESSKEY: if (key_idx < SDF_MIN_KEY_INDEX || key_idx > SDF_MAX_KEY_INDEX) { - BIO_printf(bio_err, "Invalid key index\n"); + fprintf(stderr, "Invalid key index\n"); goto end; } break; @@ -236,7 +254,7 @@ x509 goto opthelp; DEVICEINFO devInfo; if (SDF_GetDeviceInfo(hSession, &devInfo) != SDR_OK || SDF_PrintDeviceInfo(out, &devInfo) != SDR_OK) { - ERR_print_errors(bio_err); + //ERR_print_errors(stderr); goto end; } @@ -245,20 +263,20 @@ x509 goto opthelp; if (op == OP_PRINTSM2SIGN) { if (SDF_ExportSignPublicKey_ECC(hSession, key_idx, &publicKey) != SDR_OK) { - ERR_print_errors(bio_err); + //ERR_print_errors(stderr); goto end; } - BIO_puts(out, "SM2 Signing Public Key:\n"); + fprintf(out, "SM2 Signing Public Key:\n"); } else { if (SDF_ExportEncPublicKey_ECC(hSession, key_idx, &publicKey) != SDR_OK) { - ERR_print_errors(bio_err); + //ERR_print_errors(stderr); goto end; } - BIO_puts(out, "SM2 Encryption Public Key:\n"); + fprintf(out, "SM2 Encryption Public Key:\n"); } if (SDF_PrintECCPublicKey(out, &publicKey) != SDR_OK) { - ERR_print_errors(bio_err); + //ERR_print_errors(stderr); goto end; } @@ -267,69 +285,63 @@ x509 goto opthelp; if (op == OP_PRINTRSASIGN) { if (SDF_ExportSignPublicKey_RSA(hSession, key_idx, &publicKey) != SDR_OK) { - ERR_print_errors(bio_err); + //ERR_print_errors(stderr); goto end; } - BIO_puts(out, "RSA Signing Public Key:\n"); + fprintf(out, "RSA Signing Public Key:\n"); } else { if (SDF_ExportEncPublicKey_RSA(hSession, key_idx, &publicKey) != SDR_OK) { - ERR_print_errors(bio_err); + //ERR_print_errors(stderr); goto end; } - BIO_puts(out, "RSA Encryption Public Key:\n"); + fprintf(out, "RSA Encryption Public Key:\n"); } if (SDF_PrintRSAPublicKey(out, &publicKey) != SDR_OK) { - ERR_print_errors(bio_err); + //ERR_print_errors(stderr); goto end; } } else if (op == OP_ACCESSKEY) { - if (!app_passwd(passarg, NULL, &pass, NULL)) { - BIO_printf(bio_err, "Error getting password\n"); - goto end; - } if (SDF_GetPrivateKeyAccessRight(hSession, (unsigned int)key_idx, (unsigned char *)pass, strlen(pass)) != SDR_OK) { - OPENSSL_cleanse(pass, sizeof(pass)); return 0; } (void)SDF_ReleasePrivateKeyAccessRight(hSession, (unsigned int)key_idx); - BIO_printf(bio_err, "Access private key %d success\n", key_idx); + fprintf(stderr, "Access private key %d success\n", key_idx); } else if (op == OP_IMPORTOBJ) { - if (!(in = bio_open_default(infile, 'r', FORMAT_BINARY))) { + if (!(in = fopen(infile, "r"))) { goto opthelp; } - if ((len = bio_to_mem(&buf, SDF_MAX_FILE_SIZE, in)) < 0) { - BIO_printf(bio_err, "Error reading data object content\n"); + if ((len = fread(buf, 1, SDF_MAX_FILE_SIZE, in)) < 0) { + fprintf(stderr, "Error reading data object content\n"); goto end; } if (SDF_CreateFile(hSession, (unsigned char *)objname, strlen(objname), len) != SDR_OK || SDF_WriteFile(hSession, (unsigned char *)objname, strlen(objname), 0, len, buf) != SDR_OK) { - ERR_print_errors(bio_err); + //ERR_print_errors(stderr); goto end; } - BIO_printf(bio_err, "Object '%s' (%d bytes) created\n", objname, len); + fprintf(stderr, "Object '%s' (%d bytes) created\n", objname, len); } else if (op == OP_EXPORTOBJ) { - if (!(out = bio_open_default(outfile, 'w', FORMAT_BINARY))) { + if (!(out = fopen(outfile, "w"))) { goto opthelp; } - if (!(buf = OPENSSL_zalloc(SDF_MAX_FILE_SIZE)) - || SDF_ReadFile(hSession, (unsigned char *)objname, strlen(objname), 0, &ulen, buf) != SDR_OK - || BIO_write(out, buf, ulen) != ulen) { - ERR_print_errors(bio_err); + if (SDF_ReadFile(hSession, (unsigned char *)objname, strlen(objname), 0, &ulen, buf) != SDR_OK + || fwrite(buf, 1, ulen, out) != ulen) { + //ERR_print_errors(stderr); goto end; } - BIO_printf(bio_err, "Object '%s' (%u bytes) exported\n", objname, ulen); + fprintf(stderr, "Object '%s' (%u bytes) exported\n", objname, ulen); } else if (op == OP_DELOBJ) { if (SDF_DeleteFile(hSession, (unsigned char *)objname, strlen(objname)) != SDR_OK) { - ERR_print_errors(bio_err); + //ERR_print_errors(stderr); goto end; } - BIO_printf(bio_err, "Object '%s' deleted\n", objname); + fprintf(stderr, "Object '%s' deleted\n", objname); } else { goto end; @@ -337,11 +349,14 @@ x509 goto opthelp; ret = 0; +bad: + fprintf(stderr, "%s: commands should not be used together\n", prog); + + end: - BIO_free(in); - BIO_free(out); - OPENSSL_free(buf); - OPENSSL_free(pass); + fclose(in); + fclose(out); + if (hSession) (void)SDF_CloseSession(hSession); if (hDev) (void)SDF_CloseDevice(hDev); if (lib) SDF_UnloadLibrary(); diff --git a/sdf/sgd.h b/sdf/sgd.h new file mode 100644 index 00000000..664a86d0 --- /dev/null +++ b/sdf/sgd.h @@ -0,0 +1,435 @@ +/* + * Copyright (c) 2015 - 2021 The GmSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the GmSSL Project. + * (http://gmssl.org/)" + * + * 4. The name "GmSSL Project" must not be used to endorse or promote + * products derived from this software without prior written + * permission. For written permission, please contact + * guanzhi1980@gmail.com. + * + * 5. Products derived from this software may not be called "GmSSL" + * nor may "GmSSL" appear in their names without prior written + * permission of the GmSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the GmSSL Project + * (http://gmssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + */ +/* + * this header file is based on the standard GM/T 0006-2012 + * Cryptographic Application Identifier Criterion Specification + */ + +#ifndef GMSSL_SGD_H +#define GMSSL_SGD_H + + +#include + + +/* block cipher modes */ +#define SGD_ECB 0x01 +#define SGD_CBC 0x02 +#define SGD_CFB 0x04 +#define SGD_OFB 0x08 +#define SGD_MAC 0x10 + +/* stream cipher modes */ +#define SGD_EEA3 0x01 +#define SGD_EIA3 0x02 + +/* ciphers */ +#define SGD_SM1 0x00000100 +#define SGD_SSF33 0x00000200 +#define SGD_SM4 0x00000400 +#define SGD_ZUC 0x00000800 + +/* ciphers with modes */ +#define SGD_SM1_ECB (SGD_SM1|SGD_ECB) +#define SGD_SM1_CBC (SGD_SM1|SGD_CBC) +#define SGD_SM1_CFB (SGD_SM1|SGD_CFB) +#define SGD_SM1_OFB (SGD_SM1|SGD_OFB) +#define SGD_SM1_MAC (SGD_SM1|SGD_MAC) +#define SGD_SSF33_ECB (SGD_SSF33|SGD_ECB) +#define SGD_SSF33_CBC (SGD_SSF33|SGD_CBC) +#define SGD_SSF33_CFB (SGD_SSF33|SGD_CFB) +#define SGD_SSF33_OFB (SGD_SSF33|SGD_OFB) +#define SGD_SSF33_MAC (SGD_SSF33|SGD_MAC) +#define SGD_SM4_ECB (SGD_SM4|SGD_ECB) +#define SGD_SM4_CBC (SGD_SM4|SGD_CBC) +#define SGD_SM4_CFB (SGD_SM4|SGD_CFB) +#define SGD_SM4_OFB (SGD_SM4|SGD_OFB) +#define SGD_SM4_MAC (SGD_SM4|SGD_MAC) +#define SGD_ZUC_EEA3 (SGD_ZUC|SGD_EEA3) +#define SGD_ZUC_EIA3 (SGD_ZUC|SGD_EIA3) + +/* public key usage */ +#define SGD_PK_SIGN 0x0100 +#define SGD_PK_DH 0x0200 +#define SGD_PK_ENC 0x0400 + +/* public key types */ +#define SGD_RSA 0x00010000 +#define SGD_RSA_SIGN (SGD_RSA|SGD_PK_SIGN) +#define SGD_RSA_ENC (SGD_RSA|SGD_PK_ENC) +#define SGD_SM2 0x00020000 +#define SGD_SM2_1 (SGD_SM2|SGD_PK_SIGN) +#define SGD_SM2_2 (SGD_SM2|SGD_PK_DH) +#define SGD_SM2_3 (SGD_SM2|SGD_PK_ENC) + +/* hash */ +#define SGD_SM3 0x00000001 +#define SGD_SHA1 0x00000002 +#define SGD_SHA256 0x00000004 +#define SGD_HASH_FROM 0x00000008 +#define SGD_HASH_TO 0x000000FF + +/* signatue schemes */ +#define SGD_SM3_RSA (SGD_SM3|SGD_RSA) +#define SGD_SHA1_RSA (SGD_SHA1|SGD_RSA) +#define SGD_SHA256_RSA (SGD_SHA256|SGD_RSA) +#define SGD_SM3_SM2 (SGD_SM3|SGD_SM2) +#define SGD_SIG_FROM 0x00040000 +#define SGD_SIG_TO 0x800000FF + +/* data types */ +typedef char SGD_CHAR; +typedef char SGD_INT8; +typedef int16_t SGD_INT16; +typedef int32_t SGD_INT32; +typedef int64_t SGD_INT64; +typedef unsigned char SGD_UCHAR; +typedef uint8_t SGD_UINT8; +typedef uint16_t SGD_UINT16; +typedef uint32_t SGD_UINT32; +typedef uint64_t SGD_UINT64; +typedef uint32_t SGD_RV; +typedef void * SGD_OBJ; +typedef int32_t SGD_BOOL; + +#define SGD_TRUE 0x00000001 +#define SGD_FALSE 0x00000000 + +#define SGD_KEY_INDEX 0x00000101 +#define SGD_SECRET_KEY 0x00000102 +#define SGD_PUBLIC_KEY_SIGN 0x00000103 +#define SGD_PUBLIC_KEY_ENCRYPT 0x00000104 +#define SGD_PRIVATE_KEY_SIGN 0x00000105 +#define SGD_PRIVATE_KEY_ENCRYPT 0x00000106 +#define SGD_KEY_COMPONENT 0x00000107 +#define SGD_PASSWORD 0x00000108 +#define SGD_PUBLIC_KEY_CERT 0x00000109 +#define SGD_ATTRIBUTE_CERT 0x1000010A +#define SGD_SIGNATURE_DATA 0x10000111 +#define SGD_ENVELOPE_DATA 0x10000112 +#define SGD_RANDOM_DATA 0x10000113 +#define SGD_PLAIN_DATA 0x10000114 +#define SGD_CIPHER_DATA 0x10000115 +#define SGD_DIGEST_DATA 0x10000116 +#define SGD_USER_DATA 0x10000117 + +/* certificate */ +#define SGD_CERT_VERSION 0x00000001 +#define SGD_CERT_SERIAL 0x00000002 +#define SGD_CERT_ISSUER 0x00000005 +#define SGD_CERT_VALID_TIME 0x00000006 +#define SGD_CERT_SUBJECT 0x00000007 +#define SGD_CERT_DER_PUBLIC_KEY 0x00000008 +#define SGD_CERT_DER_EXTENSIONS 0x00000009 +#define SGD_EXT_AUTHORITYKEYIDENTIFIER_INFO 0x00000011 +#define SGD_EXT_SUBJECTKEYIDENTIFIER_INFO 0x00000012 +#define SGD_EXT_KEYUSAGE_INFO 0x00000013 +#define SGD_EXT_PRIVATEKEYUSAGEPERIOD_INFO 0x00000014 +#define SGD_EXT_CERTIFICATEPOLICIES_INFO 0x00000015 +#define SGD_EXT_POLICYMAPPINGS_INFO 0x00000016 +#define SGD_EXT_BASICCONSTRAINTS_INFO 0x00000017 +#define SGD_EXT_POLICYCONSTRAINTS_INFO 0x00000018 +#define SGD_EXT_EXTKEYUSAGE_INFO 0x00000019 +#define SGD_EXT_CRLDISTRIBUTIONPOINTS_INFO 0x0000001A +#define SGD_EXT_NETSCAPE_CERT_TYPE_INFO 0x0000001B +#define SGD_EXT_SELFDEFINED_EXTENSION_INFO 0x0000001C +#define SGD_CERT_ISSUER_CN 0x00000021 +#define SGD_CERT_ISSUER_O 0x00000022 +#define SGD_CERT_ISSUER_OU 0x00000023 +#define SGD_CERT_SUBJECT_CN 0x00000031 +#define SGD_CERT_SUBJECT_O 0x00000032 +#define SGD_CERT_SUBJECT_OU 0x00000033 +#define SGD_CERT_SUBJECT_EMAIL 0x00000034 +#define SGD_CERT_NOTBEFORE_TIME 0x00000035 +#define SGD_CERT_NOTAFTER_TIME 0x00000036 + +/* timestamp info */ +#define SGD_TIME_OF_STAMP 0x00000201 +#define SGD_CN_OF_TSSIGNER 0x00000202 /* Common Name of TS Signer */ +#define SGD_ORININAL_DATA 0x00000203 +#define SGD_CERT_OF_TSSSERVER 0x00000204 +#define SGD_GERTCHAIN_OF_TSSERVER 0x00000205 +#define SGD_SOURCE_OF_TIME 0x00000206 +#define SGD_TIME_PRECISION 0x00000207 +#define SGD_RESPONSE_TYPE 0x00000208 +#define SGD_SUBJECT_COUNTRY_OF_TSSIGNER 0x00000209 +#define SGD_SUBJECT_ORGNIZATION_OF_TSSIGNER 0x0000020A +#define SGD_SUJECT_CITY_OF_TSSIGNER 0x0000020B +#define SGD_SUBJECT_EMAIL_OF_TSSIGNER 0x0000020C + +/* single sign-on */ +#define SGD_SP_ID 0x00000001 +#define SGD_SP_USER_ID 0x00000002 +#define SGD_IDP_ID 0x00000003 +#define SGD_IDP_USER_ID 0x00000004 + +/* data encoding */ +#define SGD_ENCODING_RAW 0x00000000 +#define SGD_ENCODING_DER 0x01000000 +#define SGD_ENCODING_BASE64 0x02000000 +#define SGD_ENCODING_PEM 0x03000000 +#define SGD_ENCODING_TXT 0x04000000 + +/* APIs */ +#define SGD_PROTOCOL_CSP 1 /* Microsoft CryptoAPI */ +#define SGD_PROTOCOL_PKCS11 2 /* PKCS#11 */ +#define SGD_PROTOCOL_SDS 3 /* SDF API */ +#define SGD_PROTOCOL_UKEY 4 /* SKF API */ +#define SGD_PROTOCOL_CNG 5 /* Microsoft CryptoAPI Next Gen */ +#define SGD_PROTOCOL_GCS 6 /* */ + +/* certificate validation */ +#define SGD_CRL_VERIFY 1 +#define SGD_OCSP_VEIFY 2 + +/* role */ +#define SGD_ROLE_SUPER_MANAGER 0x00000001 +#define SGD_ROLE_MANAGER 0x00000002 +#define SGD_ROLE_AUDIT_MANAGER 0x00000003 +#define SGD_ROLE_AUDITOR 0x00000004 +#define SGD_ROLE_OPERATOR 0x00000005 +#define SGD_ROLE_USER 0x00000006 + +/* user operations */ +#define SGD_OPERATION_SIGNIN 0x00000001 +#define SGD_OPERATION_SIGNOUT 0x00000002 +#define SGD_OPERATION_CREATE 0x00000003 +#define SGD_OPERATION_DELETE 0x00000004 +#define SGD_OPERATION_MODIFY 0x00000005 +#define SGD_OPERATION_CHG_PWD 0x00000006 +#define SGD_OPERATION_AUTHORIZATION 0x00000007 + +/* user operation results */ +#define SGD_OPERATION_SUCCESS 0x00000000 + +/* key types */ +#define SGD_MAIN_KEY 0x00000101 +#define SGD_DEVICE_KEYS 0x00000102 +#define SGD_USER_KEYS 0x00000103 +#define SGD_KEY 0x00000104 +#define SGD_SESSION_KEY 0x00000105 +#define SGD_PRIKEY_PASSWD 0x00000106 +#define SGD_COMPARTITION_KEY 0x00000107 + +/* key operations */ +#define SGD_KEY_GENERATION 0x00000101 +#define SGD_KEY_DISPENSE 0x00000102 +#define SGD_KEY_IMPORT 0x00000103 +#define SGD_KEY_EXPORT 0x00000104 +#define SGD_KEY_DIVISION 0x00000105 +#define SGD_KEY_COMPOSE 0x00000106 +#define SGD_KEY_RENEWAL 0x00000107 +#define SGD_KEY_BACKUP 0x00000108 +#define SGD_KEY_RESTORE 0x00000109 +#define SGD_KEY_DESTORY 0x0000010A + +/* system operations */ +#define SGD_SYSTEM_INIT 0x00000201 +#define SGD_SYSTEM_START 0x00000202 +#define SGD_SYSTEM_SHUT 0x00000203 +#define SGD_SYSTEM_RESTART 0x00000204 +#define SGD_SYSTEM_QUERY 0x00000205 +#define SGD_SYSTEM_BACKUP 0x00000206 +#define SGD_SYSTEM_RESTORE 0x00000207 + +/* device info */ +#define SGD_DEVICE_SORT 0x00000201 +#define SGD_DEVICE_TYPE 0x00000202 +#define SGD_DEVICE_NAME 0x00000203 +#define SGD_DEVICE_MANUFACTURER 0x00000204 +#define SGD_DEVICE_HARDWARE_VERSION 0x00000205 +#define SGD_DEVICE_SOFTWARE_VERSION 0x00000206 +#define SGD_DEVICE_STANDARD_VERSION 0x00000207 +#define SGD_DEVICE_SERIAL_NUMBER 0x00000208 +#define SGD_DEVICE_SUPPORT_SYMM_ALG 0x00000209 +#define SGD_DEVICE_SUPPORT_PKEY_ALG 0x0000020A +#define SGD_DEVICE_SUPPORT_HASH_ALG 0x0000020B +#define SGD_DEVICE_SUPPORT_STORAGE_SPACE 0x0000020C +#define SGD_DEVICE_SUPPORT_FREE_SPACE 0x0000020D +#define SGD_DEVICE_RUNTIME 0x0000020E +#define SGD_DEVICE_USED_TIMES 0x0000020F +#define SGD_DEVICE_LOCATION 0x00000210 +#define SGD_DEVICE_DESCRIPTION 0x00000211 +#define SGD_DEVICE_MANAGER_INFO 0x00000212 +#define SGD_DEVICE_MAX_DATA_SIZE 0x00000213 + +/* device types */ +#define SGD_DEVICE_SORT_SJ 0x02000000 /* Server */ +#define SGD_DEVICE_SORT_SK 0x03000000 /* PCI-E Card */ +#define SGD_DEVICE_SORT_SM 0x04000000 /* USB-Key and SmartCard */ + +/* device functionality */ +#define SGD_DEVICE_SORT_FE 0x00000100 /* encryption */ +#define SGD_DEVICE_SORT_FA 0x00000200 /* authentication */ +#define SGD_DEVICE_SORT_FM 0x00000300 /* key management */ + +/* device status */ +#define SGD_STATUS_INIT 0x00000201 +#define SGD_STATUS_READY 0x00000202 +#define SGD_STATUS_EXCEPTION 0x00000203 + +/* SKF */ +#ifndef WIN32 +typedef signed char INT8; +typedef signed short INT16; +typedef signed int INT32; +typedef unsigned char UINT8; +typedef unsigned short UINT16; +typedef unsigned int UINT32; +typedef long BOOL; +typedef UINT8 BYTE; +typedef UINT8 CHAR; +typedef INT16 SHORT; +typedef UINT16 USHORT; +# ifndef SGD_NATIVE_LONG +typedef INT32 LONG; +typedef UINT32 ULONG; +# else +typedef long LONG; +typedef unsigned long ULONG; +# endif +typedef UINT32 UINT; +typedef UINT16 WORD; +typedef UINT32 DWORD; +typedef UINT32 FLAGS; +typedef CHAR * LPSTR; +typedef void * HANDLE; +#else +#ifndef _WINDEF_H +typedef signed char INT8; +typedef signed short INT16; +typedef signed int INT32; +typedef unsigned char UINT8; +typedef unsigned short UINT16; +typedef unsigned int UINT32; +typedef long BOOL; +typedef UINT8 BYTE; +typedef UINT8 CHAR; +typedef INT16 SHORT; +typedef UINT16 USHORT; +# ifndef SGD_NATIVE_LONG +typedef INT32 LONG; +typedef UINT32 ULONG; +# else +typedef long LONG; +typedef unsigned long ULONG; +# endif +typedef UINT32 UINT; +typedef UINT16 WORD; +typedef UINT32 DWORD; +typedef UINT32 FLAGS; +typedef CHAR * LPSTR; +typedef void * HANDLE; +#endif +#endif + +typedef HANDLE DEVHANDLE; +typedef HANDLE HAPPLICATION; +typedef HANDLE HSESSION; +typedef HANDLE HCONTAINER; + +#ifndef FALSE +#define FALSE 0x00000000 +#endif + +#ifndef TRUE +#define TRUE 0x00000001 +#endif + +#ifdef WIN32 +#define DEVAPI __stdcall +#else +#define DEVAPI +#endif + +#ifndef ADMIN_TYPE +#define ADMIN_TYPE 0 +#endif + +#ifndef USER_TYPE +#define USER_TYPE 1 +#endif + +#define MAX_RSA_MODULUS_LEN 256 +#define MAX_RSA_EXPONENT_LEN 4 +#define ECC_MAX_XCOORDINATE_BITS_LEN 512 +#define ECC_MAX_YCOORDINATE_BITS_LEN 512 +#define ECC_MAX_MODULUS_BITS_LEN 512 + +#define MAX_IV_LEN 32 + +#define MAX_FILE_NAME_SIZE 32 +#define MAX_FILE_CONTAINER_NAME_SIZE 64 + +#define SECURE_NEVER_ACCOUNT 0x00000000 +#define SECURE_ADM_ACCOUNT 0x00000001 +#define SECURE_USER_ACCOUNT 0x00000010 +#define SECURE_ANYONE_ACCOUNT 0x000000FF + + +/* SDF */ + +#define RSAref_MAX_BITS 2048 +#define RSAref_MAX_LEN ((RSAref_MAX_BITS + 7) / 8) +#define RSAref_MAX_PBITS ((RSAref_MAX_BITS + 1) / 2) +#define RSAref_MAX_PLEN ((RSAref_MAX_PBITS + 7)/ 8) + +#ifdef SGD_MAX_ECC_BITS_256 +#define ECCref_MAX_BITS 256 +#else +#define ECCref_MAX_BITS 512 +#endif +#define ECCref_MAX_LEN ((ECCref_MAX_BITS+7) / 8) + + +/* SAF */ +#define SGD_MAX_COUNT 64 +#define SGD_MAX_NAME_SIZE 256 + + +#endif diff --git a/skf/sgd.h b/skf/sgd.h new file mode 100644 index 00000000..494aa8ca --- /dev/null +++ b/skf/sgd.h @@ -0,0 +1,438 @@ +/* ==================================================================== + * Copyright (c) 2015 - 2016 The GmSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the GmSSL Project. + * (http://gmssl.org/)" + * + * 4. The name "GmSSL Project" must not be used to endorse or promote + * products derived from this software without prior written + * permission. For written permission, please contact + * guanzhi1980@gmail.com. + * + * 5. Products derived from this software may not be called "GmSSL" + * nor may "GmSSL" appear in their names without prior written + * permission of the GmSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the GmSSL Project + * (http://gmssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ +/* + * this header file is based on the standard GM/T 0006-2012 + * Cryptographic Application Identifier Criterion Specification + */ + +#ifndef HEADER_SGD_H +#define HEADER_SGD_H + +#include +#ifndef OPENSSL_NO_GMAPI + +#include + +/* block cipher modes */ +#define SGD_ECB 0x01 +#define SGD_CBC 0x02 +#define SGD_CFB 0x04 +#define SGD_OFB 0x08 +#define SGD_MAC 0x10 + +/* stream cipher modes */ +#define SGD_EEA3 0x01 +#define SGD_EIA3 0x02 + +/* ciphers */ +#define SGD_SM1 0x00000100 +#define SGD_SSF33 0x00000200 +#define SGD_SM4 0x00000400 +#define SGD_ZUC 0x00000800 + +/* ciphers with modes */ +#define SGD_SM1_ECB (SGD_SM1|SGD_ECB) +#define SGD_SM1_CBC (SGD_SM1|SGD_CBC) +#define SGD_SM1_CFB (SGD_SM1|SGD_CFB) +#define SGD_SM1_OFB (SGD_SM1|SGD_OFB) +#define SGD_SM1_MAC (SGD_SM1|SGD_MAC) +#define SGD_SSF33_ECB (SGD_SSF33|SGD_ECB) +#define SGD_SSF33_CBC (SGD_SSF33|SGD_CBC) +#define SGD_SSF33_CFB (SGD_SSF33|SGD_CFB) +#define SGD_SSF33_OFB (SGD_SSF33|SGD_OFB) +#define SGD_SSF33_MAC (SGD_SSF33|SGD_MAC) +#define SGD_SM4_ECB (SGD_SM4|SGD_ECB) +#define SGD_SM4_CBC (SGD_SM4|SGD_CBC) +#define SGD_SM4_CFB (SGD_SM4|SGD_CFB) +#define SGD_SM4_OFB (SGD_SM4|SGD_OFB) +#define SGD_SM4_MAC (SGD_SM4|SGD_MAC) +#define SGD_ZUC_EEA3 (SGD_ZUC|SGD_EEA3) +#define SGD_ZUC_EIA3 (SGD_ZUC|SGD_EIA3) + +/* public key usage */ +#define SGD_PK_SIGN 0x0100 +#define SGD_PK_DH 0x0200 +#define SGD_PK_ENC 0x0400 + +/* public key types */ +#define SGD_RSA 0x00010000 +#define SGD_RSA_SIGN (SGD_RSA|SGD_PK_SIGN) +#define SGD_RSA_ENC (SGD_RSA|SGD_PK_ENC) +#define SGD_SM2 0x00020000 +#define SGD_SM2_1 (SGD_SM2|SGD_PK_SIGN) +#define SGD_SM2_2 (SGD_SM2|SGD_PK_DH) +#define SGD_SM2_3 (SGD_SM2|SGD_PK_ENC) + +/* hash */ +#define SGD_SM3 0x00000001 +#define SGD_SHA1 0x00000002 +#define SGD_SHA256 0x00000004 +#define SGD_HASH_FROM 0x00000008 +#define SGD_HASH_TO 0x000000FF + +/* signatue schemes */ +#define SGD_SM3_RSA (SGD_SM3|SGD_RSA) +#define SGD_SHA1_RSA (SGD_SHA1|SGD_RSA) +#define SGD_SHA256_RSA (SGD_SHA256|SGD_RSA) +#define SGD_SM3_SM2 (SGD_SM3|SGD_SM2) +#define SGD_SIG_FROM 0x00040000 +#define SGD_SIG_TO 0x800000FF + +/* data types */ +typedef char SGD_CHAR; +typedef char SGD_INT8; +typedef int16_t SGD_INT16; +typedef int32_t SGD_INT32; +typedef int64_t SGD_INT64; +typedef unsigned char SGD_UCHAR; +typedef uint8_t SGD_UINT8; +typedef uint16_t SGD_UINT16; +typedef uint32_t SGD_UINT32; +typedef uint64_t SGD_UINT64; +typedef uint32_t SGD_RV; +typedef void * SGD_OBJ; +typedef int32_t SGD_BOOL; + +#define SGD_TRUE 0x00000001 +#define SGD_FALSE 0x00000000 + +#define SGD_KEY_INDEX 0x00000101 +#define SGD_SECRET_KEY 0x00000102 +#define SGD_PUBLIC_KEY_SIGN 0x00000103 +#define SGD_PUBLIC_KEY_ENCRYPT 0x00000104 +#define SGD_PRIVATE_KEY_SIGN 0x00000105 +#define SGD_PRIVATE_KEY_ENCRYPT 0x00000106 +#define SGD_KEY_COMPONENT 0x00000107 +#define SGD_PASSWORD 0x00000108 +#define SGD_PUBLIC_KEY_CERT 0x00000109 +#define SGD_ATTRIBUTE_CERT 0x1000010A +#define SGD_SIGNATURE_DATA 0x10000111 +#define SGD_ENVELOPE_DATA 0x10000112 +#define SGD_RANDOM_DATA 0x10000113 +#define SGD_PLAIN_DATA 0x10000114 +#define SGD_CIPHER_DATA 0x10000115 +#define SGD_DIGEST_DATA 0x10000116 +#define SGD_USER_DATA 0x10000117 + +/* certificate */ +#define SGD_CERT_VERSION 0x00000001 +#define SGD_CERT_SERIAL 0x00000002 +#define SGD_CERT_ISSUER 0x00000005 +#define SGD_CERT_VALID_TIME 0x00000006 +#define SGD_CERT_SUBJECT 0x00000007 +#define SGD_CERT_DER_PUBLIC_KEY 0x00000008 +#define SGD_CERT_DER_EXTENSIONS 0x00000009 +#define SGD_EXT_AUTHORITYKEYIDENTIFIER_INFO 0x00000011 +#define SGD_EXT_SUBJECTKEYIDENTIFIER_INFO 0x00000012 +#define SGD_EXT_KEYUSAGE_INFO 0x00000013 +#define SGD_EXT_PRIVATEKEYUSAGEPERIOD_INFO 0x00000014 +#define SGD_EXT_CERTIFICATEPOLICIES_INFO 0x00000015 +#define SGD_EXT_POLICYMAPPINGS_INFO 0x00000016 +#define SGD_EXT_BASICCONSTRAINTS_INFO 0x00000017 +#define SGD_EXT_POLICYCONSTRAINTS_INFO 0x00000018 +#define SGD_EXT_EXTKEYUSAGE_INFO 0x00000019 +#define SGD_EXT_CRLDISTRIBUTIONPOINTS_INFO 0x0000001A +#define SGD_EXT_NETSCAPE_CERT_TYPE_INFO 0x0000001B +#define SGD_EXT_SELFDEFINED_EXTENSION_INFO 0x0000001C +#define SGD_CERT_ISSUER_CN 0x00000021 +#define SGD_CERT_ISSUER_O 0x00000022 +#define SGD_CERT_ISSUER_OU 0x00000023 +#define SGD_CERT_SUBJECT_CN 0x00000031 +#define SGD_CERT_SUBJECT_O 0x00000032 +#define SGD_CERT_SUBJECT_OU 0x00000033 +#define SGD_CERT_SUBJECT_EMAIL 0x00000034 +#define SGD_CERT_NOTBEFORE_TIME 0x00000035 +#define SGD_CERT_NOTAFTER_TIME 0x00000036 + +/* timestamp info */ +#define SGD_TIME_OF_STAMP 0x00000201 +#define SGD_CN_OF_TSSIGNER 0x00000202 /* Common Name of TS Signer */ +#define SGD_ORININAL_DATA 0x00000203 +#define SGD_CERT_OF_TSSSERVER 0x00000204 +#define SGD_GERTCHAIN_OF_TSSERVER 0x00000205 +#define SGD_SOURCE_OF_TIME 0x00000206 +#define SGD_TIME_PRECISION 0x00000207 +#define SGD_RESPONSE_TYPE 0x00000208 +#define SGD_SUBJECT_COUNTRY_OF_TSSIGNER 0x00000209 +#define SGD_SUBJECT_ORGNIZATION_OF_TSSIGNER 0x0000020A +#define SGD_SUJECT_CITY_OF_TSSIGNER 0x0000020B +#define SGD_SUBJECT_EMAIL_OF_TSSIGNER 0x0000020C + +/* single sign-on */ +#define SGD_SP_ID 0x00000001 +#define SGD_SP_USER_ID 0x00000002 +#define SGD_IDP_ID 0x00000003 +#define SGD_IDP_USER_ID 0x00000004 + +/* data encoding */ +#define SGD_ENCODING_RAW 0x00000000 +#define SGD_ENCODING_DER 0x01000000 +#define SGD_ENCODING_BASE64 0x02000000 +#define SGD_ENCODING_PEM 0x03000000 +#define SGD_ENCODING_TXT 0x04000000 + +/* APIs */ +#define SGD_PROTOCOL_CSP 1 /* Microsoft CryptoAPI */ +#define SGD_PROTOCOL_PKCS11 2 /* PKCS#11 */ +#define SGD_PROTOCOL_SDS 3 /* SDF API */ +#define SGD_PROTOCOL_UKEY 4 /* SKF API */ +#define SGD_PROTOCOL_CNG 5 /* Microsoft CryptoAPI Next Gen */ +#define SGD_PROTOCOL_GCS 6 /* */ + +/* certificate validation */ +#define SGD_CRL_VERIFY 1 +#define SGD_OCSP_VEIFY 2 + +/* role */ +#define SGD_ROLE_SUPER_MANAGER 0x00000001 +#define SGD_ROLE_MANAGER 0x00000002 +#define SGD_ROLE_AUDIT_MANAGER 0x00000003 +#define SGD_ROLE_AUDITOR 0x00000004 +#define SGD_ROLE_OPERATOR 0x00000005 +#define SGD_ROLE_USER 0x00000006 + +/* user operations */ +#define SGD_OPERATION_SIGNIN 0x00000001 +#define SGD_OPERATION_SIGNOUT 0x00000002 +#define SGD_OPERATION_CREATE 0x00000003 +#define SGD_OPERATION_DELETE 0x00000004 +#define SGD_OPERATION_MODIFY 0x00000005 +#define SGD_OPERATION_CHG_PWD 0x00000006 +#define SGD_OPERATION_AUTHORIZATION 0x00000007 + +/* user operation results */ +#define SGD_OPERATION_SUCCESS 0x00000000 + +/* key types */ +#define SGD_MAIN_KEY 0x00000101 +#define SGD_DEVICE_KEYS 0x00000102 +#define SGD_USER_KEYS 0x00000103 +#define SGD_KEY 0x00000104 +#define SGD_SESSION_KEY 0x00000105 +#define SGD_PRIKEY_PASSWD 0x00000106 +#define SGD_COMPARTITION_KEY 0x00000107 + +/* key operations */ +#define SGD_KEY_GENERATION 0x00000101 +#define SGD_KEY_DISPENSE 0x00000102 +#define SGD_KEY_IMPORT 0x00000103 +#define SGD_KEY_EXPORT 0x00000104 +#define SGD_KEY_DIVISION 0x00000105 +#define SGD_KEY_COMPOSE 0x00000106 +#define SGD_KEY_RENEWAL 0x00000107 +#define SGD_KEY_BACKUP 0x00000108 +#define SGD_KEY_RESTORE 0x00000109 +#define SGD_KEY_DESTORY 0x0000010A + +/* system operations */ +#define SGD_SYSTEM_INIT 0x00000201 +#define SGD_SYSTEM_START 0x00000202 +#define SGD_SYSTEM_SHUT 0x00000203 +#define SGD_SYSTEM_RESTART 0x00000204 +#define SGD_SYSTEM_QUERY 0x00000205 +#define SGD_SYSTEM_BACKUP 0x00000206 +#define SGD_SYSTEM_RESTORE 0x00000207 + +/* device info */ +#define SGD_DEVICE_SORT 0x00000201 +#define SGD_DEVICE_TYPE 0x00000202 +#define SGD_DEVICE_NAME 0x00000203 +#define SGD_DEVICE_MANUFACTURER 0x00000204 +#define SGD_DEVICE_HARDWARE_VERSION 0x00000205 +#define SGD_DEVICE_SOFTWARE_VERSION 0x00000206 +#define SGD_DEVICE_STANDARD_VERSION 0x00000207 +#define SGD_DEVICE_SERIAL_NUMBER 0x00000208 +#define SGD_DEVICE_SUPPORT_SYMM_ALG 0x00000209 +#define SGD_DEVICE_SUPPORT_PKEY_ALG 0x0000020A +#define SGD_DEVICE_SUPPORT_HASH_ALG 0x0000020B +#define SGD_DEVICE_SUPPORT_STORAGE_SPACE 0x0000020C +#define SGD_DEVICE_SUPPORT_FREE_SPACE 0x0000020D +#define SGD_DEVICE_RUNTIME 0x0000020E +#define SGD_DEVICE_USED_TIMES 0x0000020F +#define SGD_DEVICE_LOCATION 0x00000210 +#define SGD_DEVICE_DESCRIPTION 0x00000211 +#define SGD_DEVICE_MANAGER_INFO 0x00000212 +#define SGD_DEVICE_MAX_DATA_SIZE 0x00000213 + +/* device types */ +#define SGD_DEVICE_SORT_SJ 0x02000000 /* Server */ +#define SGD_DEVICE_SORT_SK 0x03000000 /* PCI-E Card */ +#define SGD_DEVICE_SORT_SM 0x04000000 /* USB-Key and SmartCard */ + +/* device functionality */ +#define SGD_DEVICE_SORT_FE 0x00000100 /* encryption */ +#define SGD_DEVICE_SORT_FA 0x00000200 /* authentication */ +#define SGD_DEVICE_SORT_FM 0x00000300 /* key management */ + +/* device status */ +#define SGD_STATUS_INIT 0x00000201 +#define SGD_STATUS_READY 0x00000202 +#define SGD_STATUS_EXCEPTION 0x00000203 + +/* SKF */ +#ifndef WIN32 +typedef signed char INT8; +typedef signed short INT16; +typedef signed int INT32; +typedef unsigned char UINT8; +typedef unsigned short UINT16; +typedef unsigned int UINT32; +typedef long BOOL; +typedef UINT8 BYTE; +typedef UINT8 CHAR; +typedef INT16 SHORT; +typedef UINT16 USHORT; +# ifndef SGD_NATIVE_LONG +typedef INT32 LONG; +typedef UINT32 ULONG; +# else +typedef long LONG; +typedef unsigned long ULONG; +# endif +typedef UINT32 UINT; +typedef UINT16 WORD; +typedef UINT32 DWORD; +typedef UINT32 FLAGS; +typedef CHAR * LPSTR; +typedef void * HANDLE; +#else +#ifndef _WINDEF_H +typedef signed char INT8; +typedef signed short INT16; +typedef signed int INT32; +typedef unsigned char UINT8; +typedef unsigned short UINT16; +typedef unsigned int UINT32; +typedef long BOOL; +typedef UINT8 BYTE; +typedef UINT8 CHAR; +typedef INT16 SHORT; +typedef UINT16 USHORT; +# ifndef SGD_NATIVE_LONG +typedef INT32 LONG; +typedef UINT32 ULONG; +# else +typedef long LONG; +typedef unsigned long ULONG; +# endif +typedef UINT32 UINT; +typedef UINT16 WORD; +typedef UINT32 DWORD; +typedef UINT32 FLAGS; +typedef CHAR * LPSTR; +typedef void * HANDLE; +#endif +#endif + +typedef HANDLE DEVHANDLE; +typedef HANDLE HAPPLICATION; +typedef HANDLE HSESSION; +typedef HANDLE HCONTAINER; + +#ifndef FALSE +#define FALSE 0x00000000 +#endif + +#ifndef TRUE +#define TRUE 0x00000001 +#endif + +#ifdef WIN32 +#define DEVAPI __stdcall +#else +#define DEVAPI +#endif + +#ifndef ADMIN_TYPE +#define ADMIN_TYPE 0 +#endif + +#ifndef USER_TYPE +#define USER_TYPE 1 +#endif + +#define MAX_RSA_MODULUS_LEN 256 +#define MAX_RSA_EXPONENT_LEN 4 +#define ECC_MAX_XCOORDINATE_BITS_LEN 512 +#define ECC_MAX_YCOORDINATE_BITS_LEN 512 +#define ECC_MAX_MODULUS_BITS_LEN 512 + +#define MAX_IV_LEN 32 + +#define MAX_FILE_NAME_SIZE 32 +#define MAX_FILE_CONTAINER_NAME_SIZE 64 + +#define SECURE_NEVER_ACCOUNT 0x00000000 +#define SECURE_ADM_ACCOUNT 0x00000001 +#define SECURE_USER_ACCOUNT 0x00000010 +#define SECURE_ANYONE_ACCOUNT 0x000000FF + + +/* SDF */ + +#define RSAref_MAX_BITS 2048 +#define RSAref_MAX_LEN ((RSAref_MAX_BITS + 7) / 8) +#define RSAref_MAX_PBITS ((RSAref_MAX_BITS + 1) / 2) +#define RSAref_MAX_PLEN ((RSAref_MAX_PBITS + 7)/ 8) + +#ifdef SGD_MAX_ECC_BITS_256 +#define ECCref_MAX_BITS 256 +#else +#define ECCref_MAX_BITS 512 +#endif +#define ECCref_MAX_LEN ((ECCref_MAX_BITS+7) / 8) + + +/* SAF */ +#define SGD_MAX_COUNT 64 +#define SGD_MAX_NAME_SIZE 256 + + +#endif +#endif diff --git a/skf/skf.h b/skf/skf.h new file mode 100644 index 00000000..dd949083 --- /dev/null +++ b/skf/skf.h @@ -0,0 +1,750 @@ +/* ==================================================================== + * Copyright (c) 2015 - 2016 The GmSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the GmSSL Project. + * (http://gmssl.org/)" + * + * 4. The name "GmSSL Project" must not be used to endorse or promote + * products derived from this software without prior written + * permission. For written permission, please contact + * guanzhi1980@gmail.com. + * + * 5. Products derived from this software may not be called "GmSSL" + * nor may "GmSSL" appear in their names without prior written + * permission of the GmSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the GmSSL Project + * (http://gmssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ +/* This header file is from the official specification with minor + * modification. + */ + +#ifndef HEADER_SKF_H +#define HEADER_SKF_H + +#include +#ifndef OPENSSL_NO_SKF + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#pragma pack(1) +typedef struct Struct_Version{ + BYTE major; + BYTE minor; +} VERSION; + +typedef struct Struct_DEVINFO { + VERSION Version; + CHAR Manufacturer[64]; + CHAR Issuer[64]; + CHAR Label[32]; + CHAR SerialNumber[32]; + VERSION HWVersion; + VERSION FirmwareVersion; + ULONG AlgSymCap; + ULONG AlgAsymCap; + ULONG AlgHashCap; + ULONG DevAuthAlgId; + ULONG TotalSpace; + ULONG FreeSpace; + ULONG MaxECCBufferSize; + ULONG MaxBufferSize; + BYTE Reserved[64]; +} DEVINFO, *PDEVINFO; + +typedef struct Struct_RSAPUBLICKEYBLOB { + ULONG AlgID; + ULONG BitLen; + BYTE Modulus[MAX_RSA_MODULUS_LEN]; + BYTE PublicExponent[MAX_RSA_EXPONENT_LEN]; +} RSAPUBLICKEYBLOB, *PRSAPUBLICKEYBLOB; + +typedef struct Struct_RSAPRIVATEKEYBLOB { + ULONG AlgID; + ULONG BitLen; + BYTE Modulus[MAX_RSA_MODULUS_LEN]; + BYTE PublicExponent[MAX_RSA_EXPONENT_LEN]; + BYTE PrivateExponent[MAX_RSA_MODULUS_LEN]; + BYTE Prime1[MAX_RSA_MODULUS_LEN/2]; + BYTE Prime2[MAX_RSA_MODULUS_LEN/2]; + BYTE Prime1Exponent[MAX_RSA_MODULUS_LEN/2]; + BYTE Prime2Exponent[MAX_RSA_MODULUS_LEN/2]; + BYTE Coefficient[MAX_RSA_MODULUS_LEN/2]; +} RSAPRIVATEKEYBLOB, *PRSAPRIVATEKEYBLOB; + +typedef struct Struct_ECCPUBLICKEYBLOB { + ULONG BitLen; + BYTE XCoordinate[ECC_MAX_XCOORDINATE_BITS_LEN/8]; + BYTE YCoordinate[ECC_MAX_YCOORDINATE_BITS_LEN/8]; +} ECCPUBLICKEYBLOB, *PECCPUBLICKEYBLOB; + +typedef struct Struct_ECCPRIVATEKEYBLOB { + ULONG BitLen; + BYTE PrivateKey[ECC_MAX_MODULUS_BITS_LEN/8]; +} ECCPRIVATEKEYBLOB, *PECCPRIVATEKEYBLOB; + +typedef struct Struct_ECCCIPHERBLOB { + BYTE XCoordinate[ECC_MAX_XCOORDINATE_BITS_LEN/8]; + BYTE YCoordinate[ECC_MAX_XCOORDINATE_BITS_LEN/8]; + BYTE HASH[32]; + ULONG CipherLen; + BYTE Cipher[1]; +} ECCCIPHERBLOB, *PECCCIPHERBLOB; + +typedef struct Struct_ECCSIGNATUREBLOB { + BYTE r[ECC_MAX_XCOORDINATE_BITS_LEN/8]; + BYTE s[ECC_MAX_XCOORDINATE_BITS_LEN/8]; +} ECCSIGNATUREBLOB, *PECCSIGNATUREBLOB; + +typedef struct Struct_BLOCKCIPHERPARAM { + BYTE IV[MAX_IV_LEN]; + ULONG IVLen; + ULONG PaddingType; + ULONG FeedBitLen; +} BLOCKCIPHERPARAM, *PBLOCKCIPHERPARAM; + +typedef struct SKF_ENVELOPEDKEYBLOB { + ULONG Version; + ULONG ulSymmAlgID; + ULONG ulBits; + BYTE cbEncryptedPriKey[64]; + ECCPUBLICKEYBLOB PubKey; + ECCCIPHERBLOB ECCCipherBlob; +} ENVELOPEDKEYBLOB, *PENVELOPEDKEYBLOB; + +typedef struct Struct_FILEATTRIBUTE { + CHAR FileName[MAX_FILE_NAME_SIZE]; + ULONG FileSize; + ULONG ReadRights; + ULONG WriteRights; +} FILEATTRIBUTE, *PFILEATTRIBUTE; +#pragma pack() + +/* 7.1.2 */ +ULONG DEVAPI SKF_WaitForDevEvent( + LPSTR szDevName, + ULONG *pulDevNameLen, + ULONG *pulEvent); + +/* 7.1.3 */ +ULONG DEVAPI SKF_CancelWaitForDevEvent( + void); + +/* 7.1.4 */ +ULONG DEVAPI SKF_EnumDev( + BOOL bPresent, + LPSTR szNameList, + ULONG *pulSize); + +/* 7.1.5 */ +ULONG DEVAPI SKF_ConnectDev( + LPSTR szName, + DEVHANDLE *phDev); + +/* 7.1.6 */ +ULONG DEVAPI SKF_DisConnectDev( + DEVHANDLE hDev); + +/* 7.1.7 */ +ULONG DEVAPI SKF_GetDevState( + LPSTR szDevName, + ULONG *pulDevState); + +/* 7.1.8 */ +ULONG DEVAPI SKF_SetLabel( + DEVHANDLE hDev, + LPSTR szLabel); + +/* 7.1.9 */ +ULONG DEVAPI SKF_GetDevInfo( + DEVHANDLE hDev, + DEVINFO *pDevInfo); + +/* 7.1.10 */ +ULONG DEVAPI SKF_LockDev( + DEVHANDLE hDev, + ULONG ulTimeOut); + +/* 7.1.11 */ +ULONG DEVAPI SKF_UnlockDev( + DEVHANDLE hDev); + +/* 7.1.12 */ +ULONG DEVAPI SKF_Transmit( + DEVHANDLE hDev, + BYTE *pbCommand, + ULONG ulCommandLen, + BYTE *pbData, + ULONG *pulDataLen); + +/* 7.2.2 */ +ULONG DEVAPI SKF_ChangeDevAuthKey( + DEVHANDLE hDev, + BYTE *pbKeyValue, + ULONG ulKeyLen); + +/* 7.2.3 */ +ULONG DEVAPI SKF_DevAuth( + DEVHANDLE hDev, + BYTE *pbAuthData, + ULONG ulLen); + +/* 7.2.4 */ +ULONG DEVAPI SKF_ChangePIN( + HAPPLICATION hApplication, + ULONG ulPINType, + LPSTR szOldPin, + LPSTR szNewPin, + ULONG *pulRetryCount); + +/* 7.2.5 */ +LONG DEVAPI SKF_GetPINInfo( + HAPPLICATION hApplication, + ULONG ulPINType, + ULONG *pulMaxRetryCount, + ULONG *pulRemainRetryCount, + BOOL *pbDefaultPin); + +/* 7.2.6 */ +ULONG DEVAPI SKF_VerifyPIN( + HAPPLICATION hApplication, + ULONG ulPINType, + LPSTR szPIN, + ULONG *pulRetryCount); + +/* 7.2.7 */ +ULONG DEVAPI SKF_UnblockPIN( + HAPPLICATION hApplication, + LPSTR szAdminPIN, + LPSTR szNewUserPIN, + ULONG *pulRetryCount); + +/* 7.2.8 */ +ULONG DEVAPI SKF_ClearSecureState( + HAPPLICATION hApplication); + +/* 7.3.2 */ +ULONG DEVAPI SKF_CreateApplication( + DEVHANDLE hDev, + LPSTR szAppName, + LPSTR szAdminPin, + DWORD dwAdminPinRetryCount, + LPSTR szUserPin, + DWORD dwUserPinRetryCount, + DWORD dwCreateFileRights, + HAPPLICATION *phApplication); + +/* 7.3.3 */ +ULONG DEVAPI SKF_EnumApplication( + DEVHANDLE hDev, + LPSTR szAppName, + ULONG *pulSize); + +/* 7.3.4 */ +ULONG DEVAPI SKF_DeleteApplication( + DEVHANDLE hDev, + LPSTR szAppName); + +/* 7.3.5 */ +ULONG DEVAPI SKF_OpenApplication( + DEVHANDLE hDev, + LPSTR szAppName, + HAPPLICATION *phApplication); + +/* 7.3.6 */ +ULONG DEVAPI SKF_CloseApplication( + HAPPLICATION hApplication); + +/* 7.4.2 */ +ULONG DEVAPI SKF_CreateFile( + HAPPLICATION hApplication, + LPSTR szFileName, + ULONG ulFileSize, + ULONG ulReadRights, + ULONG ulWriteRights); + +/* 7.4.3 */ +ULONG DEVAPI SKF_DeleteFile( + HAPPLICATION hApplication, + LPSTR szFileName); + +/* 7.4.4 */ +ULONG DEVAPI SKF_EnumFiles( + HAPPLICATION hApplication, + LPSTR szFileList, + ULONG *pulSize); + +/* 7.4.5 */ +ULONG DEVAPI SKF_GetFileInfo( + HAPPLICATION hApplication, + LPSTR szFileName, + FILEATTRIBUTE *pFileInfo); + +/* 7.4.6 */ +ULONG DEVAPI SKF_ReadFile( + HAPPLICATION hApplication, + LPSTR szFileName, + ULONG ulOffset, + ULONG ulSize, + BYTE *pbOutData, + ULONG *pulOutLen); + +/* 7.4.7 */ +ULONG DEVAPI SKF_WriteFile( + HAPPLICATION hApplication, + LPSTR szFileName, + ULONG ulOffset, + BYTE *pbData, + ULONG ulSize); + +/* 7.5.2 */ +ULONG DEVAPI SKF_CreateContainer( + HAPPLICATION hApplication, + LPSTR szContainerName, + HCONTAINER *phContainer); + +/* 7.5.3 */ +ULONG DEVAPI SKF_DeleteContainer( + HAPPLICATION hApplication, + LPSTR szContainerName); + +/* 7.5.4 */ +ULONG DEVAPI SKF_OpenContainer( + HAPPLICATION hApplication, + LPSTR szContainerName, + HCONTAINER *phContainer); + +/* 7.5.5 */ +ULONG DEVAPI SKF_CloseContainer( + HCONTAINER hContainer); + +/* 7.5.6 */ +ULONG DEVAPI SKF_EnumContainer( + HAPPLICATION hApplication, + LPSTR szContainerName, + ULONG *pulSize); + +/* 7.5.7 */ +ULONG DEVAPI SKF_GetContainerType( + HCONTAINER hContainer, + ULONG *pulContainerType); + +/* 7.5.8 */ +ULONG DEVAPI SKF_ImportCertificate( + HCONTAINER hContainer, + BOOL bExportSignKey, + BYTE *pbCert, + ULONG ulCertLen); + +/* 7.5.9 */ +ULONG DEVAPI SKF_ExportCertificate( + HCONTAINER hContainer, + BOOL bSignFlag, + BYTE *pbCert, + ULONG *pulCertLen); + +/* 7.6.2 */ +ULONG DEVAPI SKF_GenRandom( + DEVHANDLE hDev, + BYTE *pbRandom, + ULONG ulRandomLen); + +/* 7.6.3 */ +ULONG DEVAPI SKF_GenExtRSAKey( + DEVHANDLE hDev, + ULONG ulBitsLen, + RSAPRIVATEKEYBLOB *pBlob); + +/* 7.6.4 */ +ULONG DEVAPI SKF_GenRSAKeyPair( + HCONTAINER hContainer, + ULONG ulBitsLen, + RSAPUBLICKEYBLOB *pBlob); + +/* 7.6.5 */ +ULONG DEVAPI SKF_ImportRSAKeyPair( + HCONTAINER hContainer, + ULONG ulSymAlgId, + BYTE *pbWrappedKey, + ULONG ulWrappedKeyLen, + BYTE *pbEncryptedData, + ULONG ulEncryptedDataLen); + +/* 7.6.6 */ +ULONG DEVAPI SKF_RSASignData( + HCONTAINER hContainer, + BYTE *pbData, + ULONG ulDataLen, + BYTE *pbSignature, + ULONG *pulSignLen); + +/* 7.6.7 */ +ULONG DEVAPI SKF_RSAVerify( + DEVHANDLE hDev, + RSAPUBLICKEYBLOB *pRSAPubKeyBlob, + BYTE *pbData, + ULONG ulDataLen, + BYTE *pbSignature, + ULONG ulSignLen); + +/* 7.6.8 */ +ULONG DEVAPI SKF_RSAExportSessionKey( + HCONTAINER hContainer, + ULONG ulAlgId, + RSAPUBLICKEYBLOB *pPubKey, + BYTE *pbData, + ULONG *pulDataLen, + HANDLE *phSessionKey); + +/* 7.6.9 */ +ULONG DEVAPI SKF_ExtRSAPubKeyOperation( + DEVHANDLE hDev, + RSAPUBLICKEYBLOB *pRSAPubKeyBlob, + BYTE *pbInput, + ULONG ulInputLen, + BYTE *pbOutput, + ULONG *pulOutputLen); + +/* 7.6.10 */ +ULONG DEVAPI SKF_ExtRSAPriKeyOperation( + DEVHANDLE hDev, + RSAPRIVATEKEYBLOB *pRSAPriKeyBlob, + BYTE *pbInput, + ULONG ulInputLen, + BYTE *pbOutput, + ULONG *pulOutputLen); + +/* 7.6.11 */ +ULONG DEVAPI SKF_GenECCKeyPair( + HCONTAINER hContainer, + ULONG ulAlgId, + ECCPUBLICKEYBLOB *pBlob); + +/* 7.6.12 */ +ULONG DEVAPI SKF_ImportECCKeyPair( + HCONTAINER hContainer, + ENVELOPEDKEYBLOB *pEnvelopedKeyBlob); + +/* 7.6.13 */ +ULONG DEVAPI SKF_ECCSignData( + HCONTAINER hContainer, + BYTE *pbDigest, + ULONG ulDigestLen, + ECCSIGNATUREBLOB *pSignature); + +#ifdef SKF_HAS_ECCDECRYPT +ULONG DEVAPI SKF_ECCDecrypt( + HCONTAINER hContainer, + ECCCIPHERBLOB *pCipherBlob, + BYTE *pbPlainText, + ULONG *pulPlainTextLen); +#endif + +/* 7.6.14 */ +ULONG DEVAPI SKF_ECCVerify( + DEVHANDLE hDev, + ECCPUBLICKEYBLOB *pECCPubKeyBlob, + BYTE *pbData, + ULONG ulDataLen, + ECCSIGNATUREBLOB *pSignature); + +/* 7.6.15 */ +ULONG DEVAPI SKF_ECCExportSessionKey( + HCONTAINER hContainer, + ULONG ulAlgId, + ECCPUBLICKEYBLOB *pPubKey, + ECCCIPHERBLOB *pData, + HANDLE *phSessionKey); + +/* 7.6.16 */ +ULONG DEVAPI SKF_ExtECCEncrypt( + DEVHANDLE hDev, + ECCPUBLICKEYBLOB *pECCPubKeyBlob, + BYTE *pbPlainText, + ULONG ulPlainTextLen, + ECCCIPHERBLOB *pCipherText); + +/* 7.6.17 */ +ULONG DEVAPI SKF_ExtECCDecrypt( + DEVHANDLE hDev, + ECCPRIVATEKEYBLOB *pECCPriKeyBlob, + ECCCIPHERBLOB *pCipherText, + BYTE *pbPlainText, + ULONG *pulPlainTextLen); + +/* 7.6.18 */ +ULONG DEVAPI SKF_ExtECCSign( + DEVHANDLE hDev, + ECCPRIVATEKEYBLOB *pECCPriKeyBlob, + BYTE *pbData, + ULONG ulDataLen, + ECCSIGNATUREBLOB *pSignature); + +/* 7.6.19 */ +ULONG DEVAPI SKF_ExtECCVerify( + DEVHANDLE hDev, + ECCPUBLICKEYBLOB *pECCPubKeyBlob, + BYTE *pbData, + ULONG ulDataLen, + ECCSIGNATUREBLOB *pSignature); + +/* 7.6.20 */ +ULONG DEVAPI SKF_GenerateAgreementDataWithECC( + HCONTAINER hContainer, + ULONG ulAlgId, + ECCPUBLICKEYBLOB *pTempECCPubKeyBlob, + BYTE *pbID, + ULONG ulIDLen, + HANDLE *phAgreementHandle); + +/* 7.6.21 */ +ULONG DEVAPI SKF_GenerateAgreementDataAndKeyWithECC( + HANDLE hContainer, + ULONG ulAlgId, + ECCPUBLICKEYBLOB *pSponsorECCPubKeyBlob, + ECCPUBLICKEYBLOB *pSponsorTempECCPubKeyBlob, + ECCPUBLICKEYBLOB *pTempECCPubKeyBlob, + BYTE *pbID, + ULONG ulIDLen, + BYTE *pbSponsorID, + ULONG ulSponsorIDLen, + HANDLE *phKeyHandle); + +/* 7.6.22 */ +ULONG DEVAPI SKF_GenerateKeyWithECC( + HANDLE hAgreementHandle, + ECCPUBLICKEYBLOB *pECCPubKeyBlob, + ECCPUBLICKEYBLOB *pTempECCPubKeyBlob, + BYTE *pbID, + ULONG ulIDLen, + HANDLE *phKeyHandle); + +/* 7.6.23 */ +ULONG DEVAPI SKF_ExportPublicKey( + HCONTAINER hContainer, + BOOL bSignFlag, + BYTE *pbBlob, + ULONG *pulBlobLen); + +/* 7.6.24 */ +ULONG DEVAPI SKF_ImportSessionKey( + HCONTAINER hContainer, + ULONG ulAlgId, + BYTE *pbWrapedData, + ULONG ulWrapedLen, + HANDLE *phKey); + +/* 7.6.25 */ +ULONG DEVAPI SKF_SetSymmKey( + DEVHANDLE hDev, + BYTE *pbKey, + ULONG ulAlgID, + HANDLE *phKey); + +/* 7.6.26 */ +ULONG DEVAPI SKF_EncryptInit( + HANDLE hKey, + BLOCKCIPHERPARAM EncryptParam); + +/* 7.6.27 */ +ULONG DEVAPI SKF_Encrypt( + HANDLE hKey, + BYTE *pbData, + ULONG ulDataLen, + BYTE *pbEncryptedData, + ULONG *pulEncryptedLen); + +/* 7.6.28 */ +ULONG DEVAPI SKF_EncryptUpdate( + HANDLE hKey, + BYTE *pbData, + ULONG ulDataLen, + BYTE *pbEncryptedData, + ULONG *pulEncryptedLen); + +/* 7.6.29 */ +ULONG DEVAPI SKF_EncryptFinal( + HANDLE hKey, + BYTE *pbEncryptedData, + ULONG *pulEncryptedDataLen); + +/* 7.6.30 */ +ULONG DEVAPI SKF_DecryptInit( + HANDLE hKey, + BLOCKCIPHERPARAM DecryptParam); + +/* 7.6.31 */ +ULONG DEVAPI SKF_Decrypt( + HANDLE hKey, + BYTE *pbEncryptedData, + ULONG ulEncryptedLen, + BYTE *pbData, + ULONG *pulDataLen); + +/* 7.6.32 */ +ULONG DEVAPI SKF_DecryptUpdate( + HANDLE hKey, + BYTE *pbEncryptedData, + ULONG ulEncryptedLen, + BYTE *pbData, + ULONG *pulDataLen); + +/* 7.6.33 */ +ULONG DEVAPI SKF_DecryptFinal( + HANDLE hKey, + BYTE *pbDecryptedData, + ULONG *pulDecryptedDataLen); + +/* 7.6.34 */ +ULONG DEVAPI SKF_DigestInit( + DEVHANDLE hDev, + ULONG ulAlgID, + ECCPUBLICKEYBLOB *pPubKey, + BYTE *pbID, + ULONG ulIDLen, + HANDLE *phHash); + +/* 7.6.35 */ +ULONG DEVAPI SKF_Digest( + HANDLE hHash, + BYTE *pbData, + ULONG ulDataLen, + BYTE *pbHashData, + ULONG *pulHashLen); + +/* 7.6.36 */ +ULONG DEVAPI SKF_DigestUpdate( + HANDLE hHash, + BYTE *pbData, + ULONG ulDataLen); + +/* 7.6.37 */ +ULONG DEVAPI SKF_DigestFinal( + HANDLE hHash, + BYTE *pHashData, + ULONG *pulHashLen); + +/* 7.6.38 */ +ULONG DEVAPI SKF_MacInit( + HANDLE hKey, + BLOCKCIPHERPARAM *pMacParam, + HANDLE *phMac); + +/* 7.6.39 */ +ULONG DEVAPI SKF_Mac( + HANDLE hMac, + BYTE *pbData, + ULONG ulDataLen, + BYTE *pbMacData, + ULONG *pulMacLen); + +/* 7.6.40 */ +ULONG DEVAPI SKF_MacUpdate( + HANDLE hMac, + BYTE *pbData, + ULONG ulDataLen); + +/* 7.6.41 */ +ULONG DEVAPI SKF_MacFinal( + HANDLE hMac, + BYTE *pbMacData, + ULONG *pulMacDataLen); + +/* 7.6.42 */ +ULONG DEVAPI SKF_CloseHandle( + HANDLE hHandle); + + +#define SAR_OK 0x00000000 +#define SAR_FAIL 0x0A000001 +#define SAR_UNKNOWNERR 0x0A000002 +#define SAR_NOTSUPPORTYETERR 0x0A000003 +#define SAR_FILEERR 0x0A000004 +#define SAR_INVALIDHANDLEERR 0x0A000005 +#define SAR_INVALIDPARAMERR 0x0A000006 +#define SAR_READFILEERR 0x0A000007 +#define SAR_WRITEFILEERR 0x0A000008 +#define SAR_NAMELENERR 0x0A000009 +#define SAR_KEYUSAGEERR 0x0A00000A +#define SAR_MODULUSLENERR 0x0A00000B +#define SAR_NOTINITIALIZEERR 0x0A00000C +#define SAR_OBJERR 0x0A00000D +#define SAR_MEMORYERR 0x0A00000E +#define SAR_TIMEOUTERR 0x0A00000F +#define SAR_INDATALENERR 0x0A000010 +#define SAR_INDATAERR 0x0A000011 +#define SAR_GENRANDERR 0x0A000012 +#define SAR_HASHOBJERR 0x0A000013 +#define SAR_HASHERR 0x0A000014 +#define SAR_GENRSAKEYERR 0x0A000015 +#define SAR_RSAMODULUSLENERR 0x0A000016 +#define SAR_CSPIMPRTPUBKEYERR 0x0A000017 +#define SAR_RSAENCERR 0x0A000018 +#define SAR_RSADECERR 0x0A000019 +#define SAR_HASHNOTEQUALERR 0x0A00001A +#define SAR_KEYNOTFOUNTERR 0x0A00001B +#define SAR_CERTNOTFOUNTERR 0x0A00001C +#define SAR_NOTEXPORTERR 0x0A00001D +#define SAR_DECRYPTPADERR 0x0A00001E +#define SAR_MACLENERR 0x0A00001F +#define SAR_BUFFER_TOO_SMALL 0x0A000020 +#define SAR_KEYINFOTYPEERR 0x0A000021 +#define SAR_NOT_EVENTERR 0x0A000022 +#define SAR_DEVICE_REMOVED 0x0A000023 +#define SAR_PIN_INCORRECT 0x0A000024 +#define SAR_PIN_LOCKED 0x0A000025 +#define SAR_PIN_INVALID 0x0A000026 +#define SAR_PIN_LEN_RANGE 0x0A000027 +#define SAR_USER_ALREADY_LOGGED_IN 0x0A000028 +#define SAR_USER_PIN_NOT_INITIALIZED 0x0A000029 +#define SAR_USER_TYPE_INVALID 0x0A00002A +#define SAR_APPLICATION_NAME_INVALID 0x0A00002B +#define SAR_APPLICATION_EXISTS 0x0A00002C +#define SAR_USER_NOT_LOGGED_IN 0x0A00002D +#define SAR_APPLICATION_NOT_EXISTS 0x0A00002E +#define SAR_FILE_ALREADY_EXIST 0x0A00002F +#define SAR_NO_ROOM 0x0A000030 +#define SAR_FILE_NOT_EXIST 0x0A000031 +#define SAR_REACH_MAX_CONTAINER_COUNT 0x0A000032 + + +#ifdef __cplusplus +} +#endif +#endif +#endif diff --git a/skf/skf_ext.c b/skf/skf_ext.c new file mode 100644 index 00000000..fcf30213 --- /dev/null +++ b/skf/skf_ext.c @@ -0,0 +1,606 @@ +/* ==================================================================== + * Copyright (c) 2014 - 2019 The GmSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the GmSSL Project. + * (http://gmssl.org/)" + * + * 4. The name "GmSSL Project" must not be used to endorse or promote + * products derived from this software without prior written + * permission. For written permission, please contact + * guanzhi1980@gmail.com. + * + * 5. Products derived from this software may not be called "GmSSL" + * nor may "GmSSL" appear in their names without prior written + * permission of the GmSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the GmSSL Project + * (http://gmssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "internal/skf_int.h" +#include "../../e_os.h" + + +ULONG DEVAPI SKF_NewECCCipher(ULONG ulCipherLen, ECCCIPHERBLOB **cipherBlob) +{ + ECCCIPHERBLOB *ret = NULL; + + if (!(ret = OPENSSL_malloc(sizeof(ECCCIPHERBLOB) - 1 + ulCipherLen))) { + SKFerr(SKF_F_SKF_NEWECCCIPHER, ERR_R_MALLOC_FAILURE); + return SAR_MEMORYERR; + } + + ret->CipherLen = ulCipherLen; + *cipherBlob = ret; + return SAR_OK; +} + +ULONG DEVAPI SKF_NewEnvelopedKey(ULONG ulCipherLen, ENVELOPEDKEYBLOB **envelopedKeyBlob) +{ + ENVELOPEDKEYBLOB *ret = NULL; + + if (!(ret = OPENSSL_zalloc(sizeof(ENVELOPEDKEYBLOB) - 1 + ulCipherLen))) { + SKFerr(SKF_F_SKF_NEWENVELOPEDKEY, ERR_R_MALLOC_FAILURE); + return SAR_MEMORYERR; + } + + ret->ECCCipherBlob.CipherLen = ulCipherLen; + *envelopedKeyBlob = ret; + return SAR_OK; +} + +ULONG DEVAPI SKF_OpenDevice(LPSTR devName, BYTE authKey[16], DEVINFO *devInfo, DEVHANDLE *phDev) +{ + ULONG rv; + DEVHANDLE hDev = NULL; + HANDLE hKey = NULL; + ULONG ulTimeOut = 0xffffffff; + BYTE authRand[16] = {0}; + BYTE authData[16] = {0}; + ULONG authRandLen = SKF_AUTHRAND_LENGTH; + ULONG authDataLen = sizeof(authData); + BLOCKCIPHERPARAM encParam = {{0}, 0, 0, 0}; + + if ((rv = SKF_ConnectDev((LPSTR)devName, &hDev)) != SAR_OK + || (rv = SKF_GetDevInfo(hDev, devInfo)) != SAR_OK + || (rv = SKF_LockDev(hDev, ulTimeOut)) != SAR_OK + || (rv = SKF_GenRandom(hDev, authRand, authRandLen)) != SAR_OK + || (rv = SKF_SetSymmKey(hDev, authKey, devInfo->DevAuthAlgId, &hKey)) != SAR_OK + || (rv = SKF_EncryptInit(hKey, encParam)) != SAR_OK + || (rv = SKF_Encrypt(hKey, authRand, sizeof(authRand), authData, &authDataLen)) != SAR_OK + || (rv =SKF_DevAuth(hDev, authData, authDataLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_OPENDEVICE, ERR_R_SKF_LIB); + goto end; + } + *phDev = hDev; + hDev = NULL; + +end: + OPENSSL_cleanse(authRand, sizeof(authRand)); + OPENSSL_cleanse(authData, sizeof(authData)); + if (hKey && (rv = SKF_CloseHandle(hKey)) != SAR_OK) { + SKFerr(SKF_F_SKF_OPENDEVICE, ERR_R_SKF_LIB); + } + if (hDev && (rv = SKF_DisConnectDev(hDev)) != SAR_OK) { + SKFerr(SKF_F_SKF_OPENDEVICE, ERR_R_SKF_LIB); + } + return rv; +} + +ULONG DEVAPI SKF_CloseDevice(DEVHANDLE hDev) +{ + ULONG rv; + if ((rv = SKF_UnlockDev(hDev)) != SAR_OK) { + SKFerr(SKF_F_SKF_CLOSEDEVICE, ERR_R_SKF_LIB); + } + if ((rv = SKF_DisConnectDev(hDev)) != SAR_OK) { + SKFerr(SKF_F_SKF_CLOSEDEVICE, ERR_R_SKF_LIB); + } + return rv; +} + + +ULONG DEVAPI SKF_ImportECCPrivateKey(DEVHANDLE hDev, HCONTAINER hContainer, + EC_KEY *ec_key, ULONG symmAlgId) +{ + int ret = 0; + ULONG rv; + ULONG containerType; + ECCPRIVATEKEYBLOB eccPriKeyBlob; + BYTE symmKey[16]; + HANDLE hSymmKey = NULL; + BLOCKCIPHERPARAM encParam; + ULONG encedPriKeyLen; + SKF_PUBLICKEYBLOB signPubKeyBlob; + ULONG signPubKeyLen = sizeof(signPubKeyBlob); + ENVELOPEDKEYBLOB envelopedKeyBlob; + + /* check container type */ + if ((rv = SKF_GetContainerType(hContainer, &containerType)) != SAR_OK) { + SKFerr(SKF_F_SKF_IMPORTECCPRIVATEKEY, ERR_R_SKF_LIB); + return rv; + } + if (containerType != SKF_CONTAINER_TYPE_ECC) { + SKFerr(SKF_F_SKF_IMPORTECCPRIVATEKEY, SKF_R_CONTAINER_TYPE_NOT_MATCH); + return SAR_FAIL; + } + + /* get private key and public key */ + if (!EC_KEY_get_ECCPRIVATEKEYBLOB(ec_key, &eccPriKeyBlob) + || !EC_KEY_get_ECCPUBLICKEYBLOB(ec_key, &(envelopedKeyBlob.PubKey))) { + SKFerr(SKF_F_SKF_IMPORTECCPRIVATEKEY, ERR_R_GMAPI_LIB); + rv = SAR_FAIL; + goto end; + } + + /* set Version, ulSymmAlgID, ulBits */ + envelopedKeyBlob.Version = SKF_ENVELOPEDKEYBLOB_VERSION; + envelopedKeyBlob.ulSymmAlgID = symmAlgId; + envelopedKeyBlob.ulBits = eccPriKeyBlob.BitLen; + + /* encrypt private key with random generated symmkey */ + if (!RAND_bytes(symmKey, sizeof(symmKey))) { + SKFerr(SKF_F_SKF_IMPORTECCPRIVATEKEY, ERR_R_SKF_LIB); + rv = SAR_FAIL; + goto end; + } + if ((rv = SKF_SetSymmKey(hDev, symmKey, symmAlgId, &hSymmKey)) != SAR_OK) { + SKFerr(SKF_F_SKF_IMPORTECCPRIVATEKEY, ERR_R_SKF_LIB); + goto end; + } + encParam.IVLen = 0; + encParam.PaddingType = SKF_NO_PADDING; + if ((rv = SKF_EncryptInit(hSymmKey, encParam)) != SAR_OK) { + SKFerr(SKF_F_SKF_IMPORTECCPRIVATEKEY, ERR_R_SKF_LIB); + goto end; + } + encedPriKeyLen = sizeof(envelopedKeyBlob.cbEncryptedPriKey); + if ((rv = SKF_Encrypt(hSymmKey, + eccPriKeyBlob.PrivateKey, sizeof(eccPriKeyBlob.PrivateKey), + (BYTE *)&(envelopedKeyBlob.cbEncryptedPriKey), &encedPriKeyLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_IMPORTECCPRIVATEKEY, ERR_R_SKF_LIB); + goto end; + } + if (encedPriKeyLen != sizeof(eccPriKeyBlob.PrivateKey)) { + SKFerr(SKF_F_SKF_IMPORTECCPRIVATEKEY, ERR_R_SKF_LIB); + rv = SAR_FAIL; + goto end; + } + + /* encrypt symmKey */ + if ((rv = SKF_ExportPublicKey(hContainer, TRUE, + (BYTE *)&signPubKeyBlob, &signPubKeyLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_IMPORTECCPRIVATEKEY, ERR_R_SKF_LIB); + goto end; + } + if (signPubKeyLen != sizeof(ECCPUBLICKEYBLOB)) { + SKFerr(SKF_F_SKF_IMPORTECCPRIVATEKEY, ERR_R_SKF_LIB); + rv = SAR_FAIL; + goto end; + } + if ((rv = SKF_ExtECCEncrypt(hDev, (ECCPUBLICKEYBLOB *)&signPubKeyBlob, + symmKey, sizeof(symmKey), &(envelopedKeyBlob.ECCCipherBlob))) != SAR_OK) { + SKFerr(SKF_F_SKF_IMPORTECCPRIVATEKEY, ERR_R_SKF_LIB); + goto end; + } + + ret = 1; +end: + OPENSSL_cleanse(&eccPriKeyBlob, sizeof(eccPriKeyBlob)); + OPENSSL_cleanse(symmKey, sizeof(symmKey)); + if (hSymmKey && SKF_CloseHandle(hSymmKey) != SAR_OK) { + SKFerr(SKF_F_SKF_IMPORTECCPRIVATEKEY, ERR_R_SKF_LIB); + ret = 0; + } + return ret; +} + +ULONG DEVAPI SKF_ImportRSAPrivateKey(DEVHANDLE hDev, HCONTAINER hContainer, + RSA *rsa, ULONG symmAlgId) +{ + ULONG rv; + ULONG containerType; + RSAPRIVATEKEYBLOB rsaPriKeyBlob; + unsigned char symmKey[16]; + RSAPUBLICKEYBLOB rsaPubKeyBlob; + ULONG rsaPubKeyLen = sizeof(rsaPubKeyBlob); + BYTE wrappedKey[MAX_RSA_MODULUS_LEN]; + ULONG wrappedKeyLen = sizeof(wrappedKey); + EVP_CIPHER_CTX *cctx = NULL; + unsigned char *p; + int len; + BYTE encedPriKey[sizeof(RSAPRIVATEKEYBLOB) + 16*2]; + ULONG encedPriKeyLen = sizeof(encedPriKey); + + + if ((rv = SKF_GetContainerType(hContainer, &containerType)) != SAR_OK) { + SKFerr(SKF_F_SKF_IMPORTRSAPRIVATEKEY, ERR_R_SKF_LIB); + return rv; + } + if (containerType != SKF_CONTAINER_TYPE_RSA) { + SKFerr(SKF_F_SKF_IMPORTRSAPRIVATEKEY, ERR_R_SKF_LIB); + return SAR_FAIL; + } + + if (!RSA_get_RSAPRIVATEKEYBLOB(rsa, &rsaPriKeyBlob)) { + SKFerr(SKF_F_SKF_IMPORTRSAPRIVATEKEY, ERR_R_SKF_LIB); + goto end; + } + + /* generate symmkey */ + /* wrap symmkey with signing public key */ + if (!RAND_bytes(symmKey, sizeof(symmKey))) { + SKFerr(SKF_F_SKF_IMPORTRSAPRIVATEKEY, ERR_R_SKF_LIB); + goto end; + } + if ((rv = SKF_ExportPublicKey(hContainer, SGD_TRUE, + (BYTE *)&rsaPubKeyBlob, &rsaPubKeyLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_IMPORTRSAPRIVATEKEY, ERR_R_SKF_LIB); + goto end; + } + if (!(rsa = RSA_new_from_RSAPUBLICKEYBLOB(&rsaPubKeyBlob))) { + SKFerr(SKF_F_SKF_IMPORTRSAPRIVATEKEY, ERR_R_SKF_LIB); + goto end; + } + if ((len = RSA_public_encrypt(sizeof(symmKey), symmKey, wrappedKey, + rsa, RSA_PKCS1_PADDING)) != rsaPriKeyBlob.BitLen / 8) { + goto end; + } + wrappedKeyLen = (ULONG)len; + + /* encrypt private key with symmkey in ECB mode */ + if (!(cctx = EVP_CIPHER_CTX_new())) { + SKFerr(SKF_F_SKF_IMPORTRSAPRIVATEKEY, ERR_R_MALLOC_FAILURE); + goto end; + } + if (!EVP_EncryptInit_ex(cctx, EVP_sms4_ecb(), NULL, symmKey, NULL)) { + SKFerr(SKF_F_SKF_IMPORTRSAPRIVATEKEY, ERR_R_EVP_LIB); + goto end; + } + p = encedPriKey; + if (!EVP_EncryptUpdate(cctx, p, &len, (unsigned char *)&rsaPriKeyBlob, + sizeof(RSAPRIVATEKEYBLOB))) { + SKFerr(SKF_F_SKF_IMPORTRSAPRIVATEKEY, ERR_R_EVP_LIB); + goto end; + } + p += len; + if (!EVP_EncryptFinal_ex(cctx, p, &len)) { + SKFerr(SKF_F_SKF_IMPORTRSAPRIVATEKEY, ERR_R_EVP_LIB); + goto end; + } + p += len; + encedPriKeyLen = p - encedPriKey; + + /* import */ + if ((rv = SKF_ImportRSAKeyPair(hContainer, symmAlgId, wrappedKey, wrappedKeyLen, + encedPriKey, encedPriKeyLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_IMPORTRSAPRIVATEKEY, ERR_R_SKF_LIB); + goto end; + } + +end: + OPENSSL_cleanse(&rsaPriKeyBlob, sizeof(rsaPriKeyBlob)); + OPENSSL_cleanse(symmKey, sizeof(symmKey)); + OPENSSL_cleanse(wrappedKey, sizeof(wrappedKey)); + EVP_CIPHER_CTX_free(cctx); + return rv; +} + +ULONG DEVAPI SKF_ImportPrivateKey(DEVHANDLE hDev, HCONTAINER hContainer, + EVP_PKEY *pkey, ULONG symmAlgId) +{ + ULONG rv; + switch (EVP_PKEY_id(pkey)) { + case EVP_PKEY_EC: + if ((rv = SKF_ImportECCPrivateKey(hDev, hContainer, + EVP_PKEY_get0_EC_KEY(pkey), symmAlgId)) != SAR_OK) { + SKFerr(SKF_F_SKF_IMPORTPRIVATEKEY, ERR_R_SKF_LIB); + return rv; + } + break; + case EVP_PKEY_RSA: + if ((rv = SKF_ImportRSAPrivateKey(hDev, hContainer, + EVP_PKEY_get0_RSA(pkey), symmAlgId)) != SAR_OK) { + SKFerr(SKF_F_SKF_IMPORTPRIVATEKEY, ERR_R_SKF_LIB); + return rv; + } + break; + default: + SKFerr(SKF_F_SKF_IMPORTPRIVATEKEY, + SKF_R_UNSUPPORTED_PRIVATE_KEY_TYPE); + return SAR_FAIL; + } + return SAR_OK; +} + +ULONG DEVAPI SKF_ExportECCPublicKey(HCONTAINER hContainer, BOOL bSign, EC_KEY **ec_key) +{ + ULONG rv; + ULONG containerType; + BYTE pubKeyBlob[sizeof(SKF_PUBLICKEYBLOB)]; + ECCPUBLICKEYBLOB *pubKey = (ECCPUBLICKEYBLOB *)pubKeyBlob; + ULONG pubKeyLen = sizeof(SKF_PUBLICKEYBLOB); + + if ((rv = SKF_GetContainerType(hContainer, &containerType)) != SAR_OK) { + SKFerr(SKF_F_SKF_EXPORTECCPUBLICKEY, ERR_R_SKF_LIB); + return rv; + } + if (containerType != SKF_CONTAINER_TYPE_ECC) { + SKFerr(SKF_F_SKF_EXPORTECCPUBLICKEY, SKF_R_CONTAINER_TYPE_NOT_MATCH); + return SAR_FAIL; + } + + if ((rv = SKF_ExportPublicKey(hContainer, bSign, + pubKeyBlob, &pubKeyLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_EXPORTECCPUBLICKEY, ERR_R_SKF_LIB); + return rv; + } + if (pubKeyLen != sizeof(ECCPUBLICKEYBLOB)) { + SKFerr(SKF_F_SKF_EXPORTECCPUBLICKEY, ERR_R_SKF_LIB); + return SAR_FAIL; + } + + if (!(*ec_key = EC_KEY_new_from_ECCPUBLICKEYBLOB(pubKey))) { + SKFerr(SKF_F_SKF_EXPORTECCPUBLICKEY, SKF_R_INVALID_ECC_PUBLIC_KEY); + return SAR_FAIL; + } + return SAR_OK; +} + +ULONG DEVAPI SKF_ExportRSAPublicKey(HCONTAINER hContainer, BOOL bSign, RSA **rsa) +{ + ULONG rv; + ULONG containerType; + BYTE pubKeyBlob[sizeof(SKF_PUBLICKEYBLOB)]; + RSAPUBLICKEYBLOB *pubKey = (RSAPUBLICKEYBLOB *)pubKeyBlob; + ULONG pubKeyLen = sizeof(SKF_PUBLICKEYBLOB); + + if ((rv = SKF_GetContainerType(hContainer, &containerType)) != SAR_OK) { + SKFerr(SKF_F_SKF_EXPORTRSAPUBLICKEY, ERR_R_SKF_LIB); + return rv; + } + if (containerType != SKF_CONTAINER_TYPE_RSA) { + SKFerr(SKF_F_SKF_EXPORTRSAPUBLICKEY, SKF_R_CONTAINER_TYPE_NOT_MATCH); + return SAR_FAIL; + } + + if ((rv = SKF_ExportPublicKey(hContainer, bSign, + pubKeyBlob, &pubKeyLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_EXPORTRSAPUBLICKEY, ERR_R_SKF_LIB); + return rv; + } + if (pubKeyLen != sizeof(RSAPUBLICKEYBLOB)) { + SKFerr(SKF_F_SKF_EXPORTRSAPUBLICKEY, ERR_R_SKF_LIB); + return SAR_FAIL; + } + + if (!(*rsa = RSA_new_from_RSAPUBLICKEYBLOB(pubKey))) { + SKFerr(SKF_F_SKF_EXPORTRSAPUBLICKEY, SKF_R_INVALID_RSA_PUBLIC_KEY); + return SAR_FAIL; + } + return SAR_OK; +} + +ULONG DEVAPI SKF_ExportEVPPublicKey(HCONTAINER hContainer, BOOL bSign, EVP_PKEY **pp) +{ + ULONG rv; + ULONG containerType; + EVP_PKEY *pkey = NULL; + + if ((rv = SKF_GetContainerType(hContainer, &containerType)) != SAR_OK) { + SKFerr(SKF_F_SKF_EXPORTEVPPUBLICKEY, ERR_R_SKF_LIB); + return rv; + } + + if (!(pkey = EVP_PKEY_new())) { + SKFerr(SKF_F_SKF_EXPORTEVPPUBLICKEY, ERR_R_MALLOC_FAILURE); + return SAR_MEMORYERR; + } + + if (containerType == SKF_CONTAINER_TYPE_ECC) { + EC_KEY *ec_key = NULL; + if ((rv = SKF_ExportECCPublicKey(hContainer, bSign, + &ec_key)) != SAR_OK) { + SKFerr(SKF_F_SKF_EXPORTEVPPUBLICKEY, ERR_R_SKF_LIB); + goto end; + } + if (!EVP_PKEY_assign_EC_KEY(pkey, ec_key)) { + EC_KEY_free(ec_key); + rv = SAR_FAIL; + goto end; + } + + } else if (containerType == SKF_CONTAINER_TYPE_RSA) { + RSA *rsa = NULL; + if ((rv = SKF_ExportRSAPublicKey(hContainer, bSign, + &rsa)) != SAR_OK) { + SKFerr(SKF_F_SKF_EXPORTEVPPUBLICKEY, ERR_R_SKF_LIB); + goto end; + } + if (!EVP_PKEY_assign_RSA(pkey, rsa)) { + RSA_free(rsa); + rv = SAR_FAIL; + goto end; + } + + } else { + SKFerr(SKF_F_SKF_EXPORTEVPPUBLICKEY, SKF_R_INVALID_CONTAINER_TYPE); + rv = SAR_FAIL; + goto end; + } + + *pp = pkey; + pkey = NULL; + rv = SAR_OK; + +end: + EVP_PKEY_free(pkey); + return rv; +} + +ULONG DEVAPI SKF_ImportX509Certificate(HCONTAINER hContainer, BOOL bSign, X509 *x509) +{ + int ret = 0; + ULONG containerType; + unsigned char *cert = NULL; + unsigned char *p; + int len; + + if (SKF_GetContainerType(hContainer, &containerType) != SAR_OK) { + return 0; + } + if (containerType == SKF_CONTAINER_TYPE_UNDEF) { + return 0; + } + + switch (EVP_PKEY_id(X509_get0_pubkey(x509))) { + case EVP_PKEY_EC: + if (containerType != SKF_CONTAINER_TYPE_ECC) { + goto end; + } + if (!EC_KEY_is_sm2p256v1(EVP_PKEY_get0_EC_KEY(X509_get0_pubkey(x509)))) { + goto end; + } + break; + + case EVP_PKEY_RSA: + if (containerType != SKF_CONTAINER_TYPE_RSA) { + goto end; + } + break; + default: + goto end; + } + + if (X509_get_key_usage(x509) & (KU_DIGITAL_SIGNATURE| + KU_NON_REPUDIATION|KU_KEY_CERT_SIGN|KU_CRL_SIGN)) { + bSign = SGD_TRUE; + } else if (X509_get_key_usage(x509) & (KU_KEY_ENCIPHERMENT| + KU_DATA_ENCIPHERMENT|KU_KEY_AGREEMENT|KU_ENCIPHER_ONLY)) { + bSign = SGD_FALSE; + } else { + goto end; + } + + if ((len = i2d_X509(x509, NULL)) <= 0 + || !(p = cert = OPENSSL_malloc(len)) + || (len = i2d_X509(x509, &p)) <= 0) { + goto end; + } + + if (SKF_ImportCertificate(hContainer, bSign, cert, (ULONG)len) != SAR_OK) { + goto end; + } + + ret = 1; +end: + X509_free(x509); + OPENSSL_free(cert); + return ret; +} + +ULONG DEVAPI SKF_ImportX509CertificateByKeyUsage(HCONTAINER hContainer, X509 *x509) +{ + ULONG rv; + BOOL bSign; + + if (X509_get_key_usage(x509) & (KU_DIGITAL_SIGNATURE| + KU_NON_REPUDIATION|KU_KEY_CERT_SIGN|KU_CRL_SIGN)) { + bSign = SGD_TRUE; + } else if (X509_get_key_usage(x509) & (KU_KEY_ENCIPHERMENT| + KU_DATA_ENCIPHERMENT|KU_KEY_AGREEMENT|KU_ENCIPHER_ONLY)) { + bSign = SGD_FALSE; + } else { + SKFerr(SKF_F_SKF_IMPORTX509CERTIFICATEBYKEYUSAGE, + SKF_R_UNKNOWN_CERTIFICATE_KEYUSAGE); + return SAR_FAIL; + } + + if ((rv = SKF_ImportX509Certificate(hContainer, bSign, x509)) != SAR_OK) { + SKFerr(SKF_F_SKF_IMPORTX509CERTIFICATEBYKEYUSAGE, ERR_R_SKF_LIB); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ExportX509Certificate(HCONTAINER hContainer, BOOL bSign, X509 **px509) +{ + ULONG rv = SAR_FAIL; + BYTE *pbCert = NULL; + ULONG ulCertLen; + const unsigned char *p; + X509 *x509 = NULL; + + ulCertLen = SKF_MAX_CERTIFICATE_SIZE; + if (!(pbCert = OPENSSL_zalloc(ulCertLen))) { + SKFerr(SKF_F_SKF_EXPORTX509CERTIFICATE, ERR_R_MALLOC_FAILURE); + rv = SAR_MEMORYERR; + goto end; + } + if ((rv = SKF_ExportCertificate(hContainer, bSign, + pbCert, &ulCertLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_EXPORTX509CERTIFICATE, ERR_R_SKF_LIB); + goto end; + } + + p = pbCert; + if (!(x509 = d2i_X509(NULL, &p, (long)ulCertLen))) { + SKFerr(SKF_F_SKF_EXPORTX509CERTIFICATE, + SKF_R_PARSE_CERTIFICATE_FAILURE); + goto end; + } + if (p - pbCert != ulCertLen) { + SKFerr(SKF_F_SKF_EXPORTX509CERTIFICATE, + SKF_R_PARSE_CERTIFICATE_FAILURE); + goto end; + } + + *px509 = x509; + x509 = NULL; + rv = SAR_OK; + +end: + OPENSSL_free(pbCert); + X509_free(x509); + return rv; +} diff --git a/skf/skf_ext.h b/skf/skf_ext.h new file mode 100644 index 00000000..966edc3d --- /dev/null +++ b/skf/skf_ext.h @@ -0,0 +1,129 @@ +/* ==================================================================== + * Copyright (c) 2015 - 2016 The GmSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the GmSSL Project. + * (http://gmssl.org/)" + * + * 4. The name "GmSSL Project" must not be used to endorse or promote + * products derived from this software without prior written + * permission. For written permission, please contact + * guanzhi1980@gmail.com. + * + * 5. Products derived from this software may not be called "GmSSL" + * nor may "GmSSL" appear in their names without prior written + * permission of the GmSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the GmSSL Project + * (http://gmssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ + +#ifndef HEADER_GMSKF_H +#define HEADER_GMSKF_H + +#include +#ifndef OPENSSL_NO_SKF + +#include +#include +#include +#include + +#define SKF_NO_PADDING 0 +#define SKF_PKCS5_PADDING 1 + +#define SKF_DEV_STATE_ABSENT 0x00000000 +#define SKF_DEV_STATE_PRESENT 0x00000001 +#define SKF_DEV_STATE_UNKNOW 0x00000010 + +#define SKF_CONTAINER_TYPE_UNDEF 0 +#define SKF_CONTAINER_TYPE_RSA 1 +#define SKF_CONTAINER_TYPE_ECC 2 + +#define SKF_ENVELOPEDKEYBLOB_VERSION 1 +#define SKF_AUTHKEY_LENGTH 16 +#define SKF_AUTHRAND_LENGTH 16 +#define SKF_MAX_FILE_SIZE (256*1024) +#define SKF_MAX_CERTIFICATE_SIZE (8*1024) + + +#define SKF_DEFAULT_ADMIN_PIN_RETRY_COUNT 6 +#define SKF_DEFAULT_USER_PIN_RETRY_COUNT 6 + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + union { + ECCPUBLICKEYBLOB ecc; + RSAPUBLICKEYBLOB rsa; + } u; +} SKF_PUBLICKEYBLOB; +#define SKF_MAX_PUBLICKEYBOLB_LENGTH sizeof(SKF_PUBLICKEYBLOB) + +typedef struct { + char *name; + unsigned char *buf; + int offset; + int length; +} SKF_FILE_OP_PARAMS; + + +ULONG DEVAPI SKF_LoadLibrary(LPSTR so_path, LPSTR vendor); +ULONG DEVAPI SKF_UnloadLibrary(void); +ULONG DEVAPI SKF_OpenDevice(LPSTR devName, BYTE authKey[16], DEVINFO *devInfo, DEVHANDLE *phDev); +ULONG DEVAPI SKF_CloseDevice(DEVHANDLE hDev); +ULONG DEVAPI SKF_GetDevStateName(ULONG ulDevState, LPSTR *szName); +ULONG DEVAPI SKF_GetContainerTypeName(ULONG ulContainerType, LPSTR *szName); +ULONG DEVAPI SKF_GetAlgorName(ULONG ulAlgID, LPSTR *szName); +ULONG DEVAPI SKF_PrintDevInfo(BIO *out, DEVINFO *devInfo); +ULONG DEVAPI SKF_PrintRSAPublicKey(BIO *out, RSAPUBLICKEYBLOB *blob); +ULONG DEVAPI SKF_PrintRSAPrivateKey(BIO *out, RSAPRIVATEKEYBLOB *blob); +ULONG DEVAPI SKF_PrintECCPublicKey(BIO *out, ECCPUBLICKEYBLOB *blob); +ULONG DEVAPI SKF_PrintECCPrivateKey(BIO *out, ECCPRIVATEKEYBLOB *blob); +ULONG DEVAPI SKF_PrintECCCipher(BIO *out, ECCCIPHERBLOB *blob); +ULONG DEVAPI SKF_PrintECCSignature(BIO *out, ECCSIGNATUREBLOB *blob); +ULONG DEVAPI SKF_GetErrorString(ULONG ulError, LPSTR *szErrorStr); +ULONG DEVAPI SKF_NewECCCipher(ULONG ulCipherLen, ECCCIPHERBLOB **cipherBlob); +ULONG DEVAPI SKF_NewEnvelopedKey(ULONG ulCipherLen, ENVELOPEDKEYBLOB **envelopedKeyBlob); +ULONG DEVAPI SKF_ImportECCPrivateKey(DEVHANDLE hDev, HCONTAINER hContainer, EC_KEY *ec_key, ULONG symmAlgId); +ULONG DEVAPI SKF_ImportRSAPrivateKey(DEVHANDLE hDev, HCONTAINER hContainer, RSA *rsa, ULONG symmAlgId); +ULONG DEVAPI SKF_ImportPrivateKey(DEVHANDLE hDev, HCONTAINER hContainer, EVP_PKEY *pkey, ULONG symmAlgId); +ULONG DEVAPI SKF_ExportECCPublicKey(HCONTAINER hContainer, BOOL bSign, EC_KEY **pp); +ULONG DEVAPI SKF_ExportRSAPublicKey(HCONTAINER hContainer, BOOL bSign, RSA **pp); +ULONG DEVAPI SKF_ExportEVPPublicKey(HCONTAINER hContainer, BOOL bSign, EVP_PKEY **pp); +ULONG DEVAPI SKF_ImportX509CertificateByKeyUsage(HCONTAINER hContainer, X509 *x509); +ULONG DEVAPI SKF_ImportX509Certificate(HCONTAINER hContainer, BOOL bSign, X509 *x509); +ULONG DEVAPI SKF_ExportX509Certificate(HCONTAINER hContainer, BOOL bSign, X509 **px509); + + diff --git a/skf/skf_int.h b/skf/skf_int.h new file mode 100644 index 00000000..30023664 --- /dev/null +++ b/skf/skf_int.h @@ -0,0 +1,618 @@ +/* ==================================================================== + * Copyright (c) 2014 - 2017 The GmSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the GmSSL Project. + * (http://gmssl.org/)" + * + * 4. The name "GmSSL Project" must not be used to endorse or promote + * products derived from this software without prior written + * permission. For written permission, please contact + * guanzhi1980@gmail.com. + * + * 5. Products derived from this software may not be called "GmSSL" + * nor may "GmSSL" appear in their names without prior written + * permission of the GmSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the GmSSL Project + * (http://gmssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ + +#ifndef HEADER_SKF_INT_H +#define HEADER_SKF_INT_H + + +#include +#include "internal/dso.h" + + +typedef ULONG (DEVAPI *SKF_WaitForDevEvent_FuncPtr)( + LPSTR szDevName, + ULONG *pulDevNameLen, + ULONG *pulEvent); + +typedef ULONG (DEVAPI *SKF_CancelWaitForDevEvent_FuncPtr)( + void); + +typedef ULONG (DEVAPI *SKF_EnumDev_FuncPtr)( + BOOL bPresent, + LPSTR szNameList, + ULONG *pulSize); + +typedef ULONG (DEVAPI *SKF_ConnectDev_FuncPtr)( + LPSTR szName, + DEVHANDLE *phDev); + +typedef ULONG (DEVAPI *SKF_DisConnectDev_FuncPtr)( + DEVHANDLE hDev); + +typedef ULONG (DEVAPI *SKF_GetDevState_FuncPtr)( + LPSTR szDevName, + ULONG *pulDevState); + +typedef ULONG (DEVAPI *SKF_SetLabel_FuncPtr)( + DEVHANDLE hDev, + LPSTR szLabel); + +typedef ULONG (DEVAPI *SKF_GetDevInfo_FuncPtr)( + DEVHANDLE hDev, + DEVINFO *pDevInfo); + +typedef ULONG (DEVAPI *SKF_LockDev_FuncPtr)( + DEVHANDLE hDev, + ULONG ulTimeOut); + +typedef ULONG (DEVAPI *SKF_UnlockDev_FuncPtr)( + DEVHANDLE hDev); + +typedef ULONG (DEVAPI *SKF_Transmit_FuncPtr)( + DEVHANDLE hDev, + BYTE *pbCommand, + ULONG ulCommandLen, + BYTE *pbData, + ULONG *pulDataLen); + +typedef ULONG (DEVAPI *SKF_ChangeDevAuthKey_FuncPtr)( + DEVHANDLE hDev, + BYTE *pbKeyValue, + ULONG ulKeyLen); + +typedef ULONG (DEVAPI *SKF_DevAuth_FuncPtr)( + DEVHANDLE hDev, + BYTE *pbAuthData, + ULONG ulLen); + +typedef ULONG (DEVAPI *SKF_ChangePIN_FuncPtr)( + HAPPLICATION hApplication, + ULONG ulPINType, + LPSTR szOldPin, + LPSTR szNewPin, + ULONG *pulRetryCount); + +typedef LONG (DEVAPI *SKF_GetPINInfo_FuncPtr)( + HAPPLICATION hApplication, + ULONG ulPINType, + ULONG *pulMaxRetryCount, + ULONG *pulRemainRetryCount, + BOOL *pbDefaultPin); + +typedef ULONG (DEVAPI *SKF_VerifyPIN_FuncPtr)( + HAPPLICATION hApplication, + ULONG ulPINType, + LPSTR szPIN, + ULONG *pulRetryCount); + +typedef ULONG (DEVAPI *SKF_UnblockPIN_FuncPtr)( + HAPPLICATION hApplication, + LPSTR szAdminPIN, + LPSTR szNewUserPIN, + ULONG *pulRetryCount); + +typedef ULONG (DEVAPI *SKF_ClearSecureState_FuncPtr)( + HAPPLICATION hApplication); + +typedef ULONG (DEVAPI *SKF_CreateApplication_FuncPtr)( + DEVHANDLE hDev, + LPSTR szAppName, + LPSTR szAdminPin, + DWORD dwAdminPinRetryCount, + LPSTR szUserPin, + DWORD dwUserPinRetryCount, + DWORD dwCreateFileRights, + HAPPLICATION *phApplication); + +typedef ULONG (DEVAPI *SKF_EnumApplication_FuncPtr)( + DEVHANDLE hDev, + LPSTR szAppName, + ULONG *pulSize); + +typedef ULONG (DEVAPI *SKF_DeleteApplication_FuncPtr)( + DEVHANDLE hDev, + LPSTR szAppName); + +typedef ULONG (DEVAPI *SKF_OpenApplication_FuncPtr)( + DEVHANDLE hDev, + LPSTR szAppName, + HAPPLICATION *phApplication); + +typedef ULONG (DEVAPI *SKF_CloseApplication_FuncPtr)( + HAPPLICATION hApplication); + +typedef ULONG (DEVAPI *SKF_CreateObject_FuncPtr)( + HAPPLICATION hApplication, + LPSTR szFileName, + ULONG ulFileSize, + ULONG ulReadRights, + ULONG ulWriteRights); + +typedef ULONG (DEVAPI *SKF_DeleteObject_FuncPtr)( + HAPPLICATION hApplication, + LPSTR szFileName); + +typedef ULONG (DEVAPI *SKF_EnumObjects_FuncPtr)( + HAPPLICATION hApplication, + LPSTR szFileList, + ULONG *pulSize); + +typedef ULONG (DEVAPI *SKF_GetObjectInfo_FuncPtr)( + HAPPLICATION hApplication, + LPSTR szFileName, + FILEATTRIBUTE *pFileInfo); + +typedef ULONG (DEVAPI *SKF_ReadObject_FuncPtr)( + HAPPLICATION hApplication, + LPSTR szFileName, + ULONG ulOffset, + ULONG ulSize, + BYTE *pbOutData, + ULONG *pulOutLen); + +typedef ULONG (DEVAPI *SKF_WriteObject_FuncPtr)( + HAPPLICATION hApplication, + LPSTR szFileName, + ULONG ulOffset, + BYTE *pbData, + ULONG ulSize); + +typedef ULONG (DEVAPI *SKF_CreateContainer_FuncPtr)( + HAPPLICATION hApplication, + LPSTR szContainerName, + HCONTAINER *phContainer); + +typedef ULONG (DEVAPI *SKF_DeleteContainer_FuncPtr)( + HAPPLICATION hApplication, + LPSTR szContainerName); + +typedef ULONG (DEVAPI *SKF_EnumContainer_FuncPtr)( + HAPPLICATION hApplication, + LPSTR szContainerName, + ULONG *pulSize); + +typedef ULONG (DEVAPI *SKF_OpenContainer_FuncPtr)( + HAPPLICATION hApplication, + LPSTR szContainerName, + HCONTAINER *phContainer); + +typedef ULONG (DEVAPI *SKF_CloseContainer_FuncPtr)( + HCONTAINER hContainer); + +typedef ULONG (DEVAPI *SKF_GetContainerType_FuncPtr)( + HCONTAINER hContainer, + ULONG *pulContainerType); + +typedef ULONG (DEVAPI *SKF_ImportCertificate_FuncPtr)( + HCONTAINER hContainer, + BOOL bExportSignKey, + BYTE *pbCert, + ULONG ulCertLen); + +typedef ULONG (DEVAPI *SKF_ExportCertificate_FuncPtr)( + HCONTAINER hContainer, + BOOL bSignFlag, + BYTE *pbCert, + ULONG *pulCertLen); + +typedef ULONG (DEVAPI *SKF_ExportPublicKey_FuncPtr)( + HCONTAINER hContainer, + BOOL bSignFlag, + BYTE *pbBlob, + ULONG *pulBlobLen); + +typedef ULONG (DEVAPI *SKF_GenRandom_FuncPtr)( + DEVHANDLE hDev, + BYTE *pbRandom, + ULONG ulRandomLen); + +typedef ULONG (DEVAPI *SKF_GenExtRSAKey_FuncPtr)( + DEVHANDLE hDev, + ULONG ulBitsLen, + RSAPRIVATEKEYBLOB *pBlob); + +typedef ULONG (DEVAPI *SKF_GenRSAKeyPair_FuncPtr)( + HCONTAINER hContainer, + ULONG ulBitsLen, + RSAPUBLICKEYBLOB *pBlob); + +typedef ULONG (DEVAPI *SKF_ImportRSAKeyPair_FuncPtr)( + HCONTAINER hContainer, + ULONG ulSymAlgId, + BYTE *pbWrappedKey, + ULONG ulWrappedKeyLen, + BYTE *pbEncryptedData, + ULONG ulEncryptedDataLen); + +typedef ULONG (DEVAPI *SKF_RSASignData_FuncPtr)( + HCONTAINER hContainer, + BYTE *pbData, + ULONG ulDataLen, + BYTE *pbSignature, + ULONG *pulSignLen); + +typedef ULONG (DEVAPI *SKF_RSAVerify_FuncPtr)( + DEVHANDLE hDev, + RSAPUBLICKEYBLOB *pRSAPubKeyBlob, + BYTE *pbData, + ULONG ulDataLen, + BYTE *pbSignature, + ULONG ulSignLen); + +typedef ULONG (DEVAPI *SKF_RSAExportSessionKey_FuncPtr)( + HCONTAINER hContainer, + ULONG ulAlgId, + RSAPUBLICKEYBLOB *pPubKey, + BYTE *pbData, + ULONG *pulDataLen, + HANDLE *phSessionKey); + +typedef ULONG (DEVAPI *SKF_ExtRSAPubKeyOperation_FuncPtr)( + DEVHANDLE hDev, + RSAPUBLICKEYBLOB *pRSAPubKeyBlob, + BYTE *pbInput, + ULONG ulInputLen, + BYTE *pbOutput, + ULONG *pulOutputLen); + +typedef ULONG (DEVAPI *SKF_ExtRSAPriKeyOperation_FuncPtr)( + DEVHANDLE hDev, + RSAPRIVATEKEYBLOB *pRSAPriKeyBlob, + BYTE *pbInput, + ULONG ulInputLen, + BYTE *pbOutput, + ULONG *pulOutputLen); + +typedef ULONG (DEVAPI *SKF_GenECCKeyPair_FuncPtr)( + HCONTAINER hContainer, + ULONG ulAlgId, + ECCPUBLICKEYBLOB *pBlob); + +typedef ULONG (DEVAPI *SKF_ImportECCKeyPair_FuncPtr)( + HCONTAINER hContainer, + ENVELOPEDKEYBLOB *pEnvelopedKeyBlob); + +typedef ULONG (DEVAPI *SKF_ECCSignData_FuncPtr)( + HCONTAINER hContainer, + BYTE *pbDigest, + ULONG ulDigestLen, + ECCSIGNATUREBLOB *pSignature); + +typedef ULONG (DEVAPI *SKF_ECCVerify_FuncPtr)( + DEVHANDLE hDev, + ECCPUBLICKEYBLOB *pECCPubKeyBlob, + BYTE *pbData, + ULONG ulDataLen, + ECCSIGNATUREBLOB *pSignature); + +typedef ULONG (DEVAPI *SKF_ECCExportSessionKey_FuncPtr)( + HCONTAINER hContainer, + ULONG ulAlgId, + ECCPUBLICKEYBLOB *pPubKey, + ECCCIPHERBLOB *pData, + HANDLE *phSessionKey); + +typedef ULONG (DEVAPI *SKF_ExtECCEncrypt_FuncPtr)( + DEVHANDLE hDev, + ECCPUBLICKEYBLOB *pECCPubKeyBlob, + BYTE *pbPlainText, + ULONG ulPlainTextLen, + ECCCIPHERBLOB *pCipherText); + +typedef ULONG (DEVAPI *SKF_ECCDecrypt_FuncPtr)( + HCONTAINER hContainer, + ECCCIPHERBLOB *pCipherText, + BYTE *pbPlainText, + ULONG *pulPlainTextLen); + +typedef ULONG (DEVAPI *SKF_ExtECCDecrypt_FuncPtr)( + DEVHANDLE hDev, + ECCPRIVATEKEYBLOB *pECCPriKeyBlob, + ECCCIPHERBLOB *pCipherText, + BYTE *pbPlainText, + ULONG *pulPlainTextLen); + +typedef ULONG (DEVAPI *SKF_ExtECCSign_FuncPtr)( + DEVHANDLE hDev, + ECCPRIVATEKEYBLOB *pECCPriKeyBlob, + BYTE *pbData, + ULONG ulDataLen, + ECCSIGNATUREBLOB *pSignature); + +typedef ULONG (DEVAPI *SKF_ExtECCVerify_FuncPtr)( + DEVHANDLE hDev, + ECCPUBLICKEYBLOB *pECCPubKeyBlob, + BYTE *pbData, + ULONG ulDataLen, + ECCSIGNATUREBLOB *pSignature); + +typedef ULONG (DEVAPI *SKF_GenerateAgreementDataWithECC_FuncPtr)( + HCONTAINER hContainer, + ULONG ulAlgId, + ECCPUBLICKEYBLOB *pTempECCPubKeyBlob, + BYTE *pbID, + ULONG ulIDLen, + HANDLE *phAgreementHandle); + +typedef ULONG (DEVAPI *SKF_GenerateAgreementDataAndKeyWithECC_FuncPtr)( + HANDLE hContainer, + ULONG ulAlgId, + ECCPUBLICKEYBLOB *pSponsorECCPubKeyBlob, + ECCPUBLICKEYBLOB *pSponsorTempECCPubKeyBlob, + ECCPUBLICKEYBLOB *pTempECCPubKeyBlob, + BYTE *pbID, + ULONG ulIDLen, + BYTE *pbSponsorID, + ULONG ulSponsorIDLen, + HANDLE *phKeyHandle); + +typedef ULONG (DEVAPI *SKF_GenerateKeyWithECC_FuncPtr)( + HANDLE hAgreementHandle, + ECCPUBLICKEYBLOB *pECCPubKeyBlob, + ECCPUBLICKEYBLOB *pTempECCPubKeyBlob, + BYTE *pbID, + ULONG ulIDLen, + HANDLE *phKeyHandle); + +typedef ULONG (DEVAPI *SKF_ImportSessionKey_FuncPtr)( + HCONTAINER hContainer, + ULONG ulAlgId, + BYTE *pbWrapedData, + ULONG ulWrapedLen, + HANDLE *phKey); + +typedef ULONG (DEVAPI *SKF_SetSymmKey_FuncPtr)( + DEVHANDLE hDev, + BYTE *pbKey, + ULONG ulAlgID, + HANDLE *phKey); + +typedef ULONG (DEVAPI *SKF_EncryptInit_FuncPtr)( + HANDLE hKey, + BLOCKCIPHERPARAM EncryptParam); + +typedef ULONG (DEVAPI *SKF_Encrypt_FuncPtr)( + HANDLE hKey, + BYTE *pbData, + ULONG ulDataLen, + BYTE *pbEncryptedData, + ULONG *pulEncryptedLen); + +typedef ULONG (DEVAPI *SKF_EncryptUpdate_FuncPtr)( + HANDLE hKey, + BYTE *pbData, + ULONG ulDataLen, + BYTE *pbEncryptedData, + ULONG *pulEncryptedLen); + +typedef ULONG (DEVAPI *SKF_EncryptFinal_FuncPtr)( + HANDLE hKey, + BYTE *pbEncryptedData, + ULONG *pulEncryptedDataLen); + +typedef ULONG (DEVAPI *SKF_DecryptInit_FuncPtr)( + HANDLE hKey, + BLOCKCIPHERPARAM DecryptParam); + +typedef ULONG (DEVAPI *SKF_Decrypt_FuncPtr)( + HANDLE hKey, + BYTE *pbEncryptedData, + ULONG ulEncryptedLen, + BYTE *pbData, + ULONG *pulDataLen); + +typedef ULONG (DEVAPI *SKF_DecryptUpdate_FuncPtr)( + HANDLE hKey, + BYTE *pbEncryptedData, + ULONG ulEncryptedLen, + BYTE *pbData, + ULONG *pulDataLen); + +typedef ULONG (DEVAPI *SKF_DecryptFinal_FuncPtr)( + HANDLE hKey, + BYTE *pbDecryptedData, + ULONG *pulDecryptedDataLen); + +typedef ULONG (DEVAPI *SKF_DigestInit_FuncPtr)( + DEVHANDLE hDev, + ULONG ulAlgID, + ECCPUBLICKEYBLOB *pPubKey, + BYTE *pbID, + ULONG ulIDLen, + HANDLE *phHash); + +typedef ULONG (DEVAPI *SKF_Digest_FuncPtr)( + HANDLE hHash, + BYTE *pbData, + ULONG ulDataLen, + BYTE *pbHashData, + ULONG *pulHashLen); + +typedef ULONG (DEVAPI *SKF_DigestUpdate_FuncPtr)( + HANDLE hHash, + BYTE *pbData, + ULONG ulDataLen); + +typedef ULONG (DEVAPI *SKF_DigestFinal_FuncPtr)( + HANDLE hHash, + BYTE *pHashData, + ULONG *pulHashLen); + +typedef ULONG (DEVAPI *SKF_MacInit_FuncPtr)( + HANDLE hKey, + BLOCKCIPHERPARAM *pMacParam, + HANDLE *phMac); + +typedef ULONG (DEVAPI *SKF_Mac_FuncPtr)( + HANDLE hMac, + BYTE *pbData, + ULONG ulDataLen, + BYTE *pbMacData, + ULONG *pulMacLen); + +typedef ULONG (DEVAPI *SKF_MacUpdate_FuncPtr)( + HANDLE hMac, + BYTE *pbData, + ULONG ulDataLen); + +typedef ULONG (DEVAPI *SKF_MacFinal_FuncPtr)( + HANDLE hMac, + BYTE *pbMacData, + ULONG *pulMacDataLen); + +typedef ULONG (DEVAPI *SKF_CloseHandle_FuncPtr)( + HANDLE hHandle); + + +typedef struct skf_method_st { + char *name; + DSO *dso; + SKF_WaitForDevEvent_FuncPtr WaitForDevEvent; + SKF_CancelWaitForDevEvent_FuncPtr CancelWaitForDevEvent; + SKF_EnumDev_FuncPtr EnumDev; + SKF_ConnectDev_FuncPtr ConnectDev; + SKF_DisConnectDev_FuncPtr DisConnectDev; + SKF_GetDevState_FuncPtr GetDevState; + SKF_SetLabel_FuncPtr SetLabel; + SKF_GetDevInfo_FuncPtr GetDevInfo; + SKF_LockDev_FuncPtr LockDev; + SKF_UnlockDev_FuncPtr UnlockDev; + SKF_Transmit_FuncPtr Transmit; + SKF_ChangeDevAuthKey_FuncPtr ChangeDevAuthKey; + SKF_DevAuth_FuncPtr DevAuth; + SKF_ChangePIN_FuncPtr ChangePIN; + SKF_GetPINInfo_FuncPtr GetPINInfo; + SKF_VerifyPIN_FuncPtr VerifyPIN; + SKF_UnblockPIN_FuncPtr UnblockPIN; + SKF_ClearSecureState_FuncPtr ClearSecureState; + SKF_CreateApplication_FuncPtr CreateApplication; + SKF_EnumApplication_FuncPtr EnumApplication; + SKF_DeleteApplication_FuncPtr DeleteApplication; + SKF_OpenApplication_FuncPtr OpenApplication; + SKF_CloseApplication_FuncPtr CloseApplication; + SKF_CreateObject_FuncPtr CreateObject; + SKF_DeleteObject_FuncPtr DeleteObject; + SKF_EnumObjects_FuncPtr EnumObjects; + SKF_GetObjectInfo_FuncPtr GetObjectInfo; + SKF_ReadObject_FuncPtr ReadObject; + SKF_WriteObject_FuncPtr WriteObject; + SKF_CreateContainer_FuncPtr CreateContainer; + SKF_DeleteContainer_FuncPtr DeleteContainer; + SKF_EnumContainer_FuncPtr EnumContainer; + SKF_OpenContainer_FuncPtr OpenContainer; + SKF_CloseContainer_FuncPtr CloseContainer; + SKF_GetContainerType_FuncPtr GetContainerType; + SKF_ImportCertificate_FuncPtr ImportCertificate; + SKF_ExportCertificate_FuncPtr ExportCertificate; + SKF_ExportPublicKey_FuncPtr ExportPublicKey; + SKF_GenRandom_FuncPtr GenRandom; + SKF_GenExtRSAKey_FuncPtr GenExtRSAKey; + SKF_GenRSAKeyPair_FuncPtr GenRSAKeyPair; + SKF_ImportRSAKeyPair_FuncPtr ImportRSAKeyPair; + SKF_RSASignData_FuncPtr RSASignData; + SKF_RSAVerify_FuncPtr RSAVerify; + SKF_RSAExportSessionKey_FuncPtr RSAExportSessionKey; + SKF_ExtRSAPubKeyOperation_FuncPtr ExtRSAPubKeyOperation; + SKF_ExtRSAPriKeyOperation_FuncPtr ExtRSAPriKeyOperation; + SKF_GenECCKeyPair_FuncPtr GenECCKeyPair; + SKF_ImportECCKeyPair_FuncPtr ImportECCKeyPair; + SKF_ECCSignData_FuncPtr ECCSignData; + SKF_ECCVerify_FuncPtr ECCVerify; + SKF_ECCExportSessionKey_FuncPtr ECCExportSessionKey; + SKF_ExtECCEncrypt_FuncPtr ExtECCEncrypt; + SKF_ExtECCDecrypt_FuncPtr ExtECCDecrypt; + SKF_ECCDecrypt_FuncPtr ECCDecrypt; + SKF_ExtECCSign_FuncPtr ExtECCSign; + SKF_ExtECCVerify_FuncPtr ExtECCVerify; + SKF_GenerateAgreementDataWithECC_FuncPtr GenerateAgreementDataWithECC; + SKF_GenerateAgreementDataAndKeyWithECC_FuncPtr GenerateAgreementDataAndKeyWithECC; + SKF_GenerateKeyWithECC_FuncPtr GenerateKeyWithECC; + SKF_ImportSessionKey_FuncPtr ImportSessionKey; + SKF_SetSymmKey_FuncPtr SetSymmKey; + SKF_EncryptInit_FuncPtr EncryptInit; + SKF_Encrypt_FuncPtr Encrypt; + SKF_EncryptUpdate_FuncPtr EncryptUpdate; + SKF_EncryptFinal_FuncPtr EncryptFinal; + SKF_DecryptInit_FuncPtr DecryptInit; + SKF_Decrypt_FuncPtr Decrypt; + SKF_DecryptUpdate_FuncPtr DecryptUpdate; + SKF_DecryptFinal_FuncPtr DecryptFinal; + SKF_DigestInit_FuncPtr DigestInit; + SKF_Digest_FuncPtr Digest; + SKF_DigestUpdate_FuncPtr DigestUpdate; + SKF_DigestFinal_FuncPtr DigestFinal; + SKF_MacInit_FuncPtr MacInit; + SKF_Mac_FuncPtr Mac; + SKF_MacUpdate_FuncPtr MacUpdate; + SKF_MacFinal_FuncPtr MacFinal; + SKF_CloseHandle_FuncPtr CloseHandle; +} SKF_METHOD; + +SKF_METHOD *SKF_METHOD_load_library(const char *so_path); +void SKF_METHOD_free(SKF_METHOD *meth); + + +typedef struct skf_vendor_st { + char *name; + unsigned int authrand_length; + ULONG (*get_cipher_algor)(ULONG vendor_id); + ULONG (*get_cipher_cap)(ULONG vendor_cap); + ULONG (*get_digest_algor)(ULONG vendor_id); + ULONG (*get_digest_cap)(ULONG vendor_cap); + ULONG (*get_pkey_algor)(ULONG vendor_id); + ULONG (*get_pkey_cap)(ULONG vendor_cap); + unsigned long (*get_error_reason)(ULONG err); +} SKF_VENDOR; + +typedef struct { + ULONG err; + unsigned long reason; +} SKF_ERR_REASON; + +#endif diff --git a/skf/skf_lib.c b/skf/skf_lib.c new file mode 100644 index 00000000..005f2441 --- /dev/null +++ b/skf/skf_lib.c @@ -0,0 +1,2772 @@ +/* ==================================================================== + * Copyright (c) 2014 - 2017 The GmSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the GmSSL Project. + * (http://gmssl.org/)" + * + * 4. The name "GmSSL Project" must not be used to endorse or promote + * products derived from this software without prior written + * permission. For written permission, please contact + * guanzhi1980@gmail.com. + * + * 5. Products derived from this software may not be called "GmSSL" + * nor may "GmSSL" appear in their names without prior written + * permission of the GmSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the GmSSL Project + * (http://gmssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ + +#include +#include +#include +#include +#include +#include "internal/dso.h" +#include "internal/skf_int.h" +#include "../../e_os.h" + + +SKF_METHOD *skf_method = NULL; +SKF_VENDOR *skf_vendor = NULL; +extern SKF_VENDOR skf_wisec; + +ULONG SKF_LoadLibrary(LPSTR so_path, LPSTR vendor) +{ + if (skf_method) { + SKF_METHOD_free(skf_method); + skf_method = NULL; + } + + if (!(skf_method = SKF_METHOD_load_library((char *)so_path))) { + SKFerr(SKF_F_SKF_LOADLIBRARY, SKF_R_LOAD_LIBRARY_FAILURE); + return SAR_FAIL; + } + + if (vendor) { + if (strcmp((char *)vendor, skf_wisec.name) == 0) { + skf_vendor = &skf_wisec; + } else { + SKFerr(SKF_F_SKF_LOADLIBRARY, SKF_R_UNKNOWN_VENDOR); + return SAR_FAIL; + } + } + + return SAR_OK; +} + +ULONG SKF_UnloadLibrary(void) +{ + SKF_METHOD_free(skf_method); + skf_method = NULL; + skf_vendor = NULL; + return SAR_OK; +} + +static SKF_ERR_REASON skf_errors[] = { + { SAR_OK, SKF_R_SUCCESS }, + { SAR_FAIL, SKF_R_FAILURE }, + { SAR_UNKNOWNERR, SKF_R_UNKNOWN_ERROR }, + { SAR_NOTSUPPORTYETERR, SKF_R_OPERATION_NOT_SUPPORTED }, + { SAR_FILEERR, SKF_R_FILE_ERROR }, + { SAR_INVALIDHANDLEERR, SKF_R_INVALID_HANDLE }, + { SAR_INVALIDPARAMERR, SKF_R_INVALID_PARAMETER }, + { SAR_READFILEERR, SKF_R_READ_FILE_FAILURE }, + { SAR_WRITEFILEERR, SKF_R_WRITE_FILE_FAILURE }, + { SAR_NAMELENERR, SKF_R_INVALID_NAME_LENGTH }, + { SAR_KEYUSAGEERR, SKF_R_INVALID_KEY_USAGE }, + { SAR_MODULUSLENERR, SKF_R_INVALID_MODULUS_LENGTH }, + { SAR_NOTINITIALIZEERR, SKF_R_NOT_INITIALIZED }, + { SAR_OBJERR, SKF_R_INVALID_OBJECT }, + { SAR_MEMORYERR, SKF_R_MEMORY_ERROR }, + { SAR_TIMEOUTERR, SKF_R_TIMEOUT }, + { SAR_INDATALENERR, SKF_R_INVALID_INPUT_LENGTH }, + { SAR_INDATAERR, SKF_R_INVALID_INPUT_VALUE }, + { SAR_GENRANDERR, SKF_R_RANDOM_GENERATION_FAILED }, + { SAR_HASHOBJERR, SKF_R_INVALID_DIGEST_HANDLE }, + { SAR_HASHERR, SKF_R_DIGEST_ERROR }, + { SAR_GENRSAKEYERR, SKF_R_RSA_KEY_GENERATION_FAILURE }, + { SAR_RSAMODULUSLENERR, SKF_R_INVALID_RSA_MODULUS_LENGTH }, + { SAR_CSPIMPRTPUBKEYERR, SKF_R_CSP_IMPORT_PUBLIC_KEY_ERROR }, + { SAR_RSAENCERR, SKF_R_RSA_ENCRYPTION_FAILURE }, + { SAR_RSADECERR, SKF_R_RSA_DECRYPTION_FAILURE }, + { SAR_HASHNOTEQUALERR, SKF_R_HASH_NOT_EQUAL }, + { SAR_KEYNOTFOUNTERR, SKF_R_KEY_NOT_FOUND }, + { SAR_CERTNOTFOUNTERR, SKF_R_CERTIFICATE_NOT_FOUND }, + { SAR_NOTEXPORTERR, SKF_R_EXPORT_FAILED }, + { SAR_DECRYPTPADERR, SKF_R_DECRYPT_INVALID_PADDING }, + { SAR_MACLENERR, SKF_R_INVALID_MAC_LENGTH }, + { SAR_BUFFER_TOO_SMALL, SKF_R_BUFFER_TOO_SMALL }, + { SAR_KEYINFOTYPEERR, SKF_R_INVALID_KEY_INFO_TYPE }, + { SAR_NOT_EVENTERR, SKF_R_NO_EVENT }, + { SAR_DEVICE_REMOVED, SKF_R_DEVICE_REMOVED }, + { SAR_PIN_INCORRECT, SKF_R_PIN_INCORRECT }, + { SAR_PIN_LOCKED, SKF_R_PIN_LOCKED }, + { SAR_PIN_INVALID, SKF_R_INVALID_PIN }, + { SAR_PIN_LEN_RANGE, SKF_R_INVALID_PIN_LENGTH }, + { SAR_USER_ALREADY_LOGGED_IN, SKF_R_USER_ALREADY_LOGGED_IN }, + { SAR_USER_PIN_NOT_INITIALIZED, SKF_R_USER_PIN_NOT_INITIALIZED }, + { SAR_USER_TYPE_INVALID, SKF_R_INVALID_USER_TYPE }, + { SAR_APPLICATION_NAME_INVALID, SKF_R_INVALID_APPLICATION_NAME }, + { SAR_APPLICATION_EXISTS, SKF_R_APPLICATION_ALREADY_EXIST }, + { SAR_USER_NOT_LOGGED_IN, SKF_R_USER_NOT_LOGGED_IN }, + { SAR_APPLICATION_NOT_EXISTS, SKF_R_APPLICATION_NOT_EXIST }, + { SAR_FILE_ALREADY_EXIST, SKF_R_FILE_ALREADY_EXIST }, + { SAR_NO_ROOM, SKF_R_NO_SPACE }, + { SAR_FILE_NOT_EXIST, SKF_R_FILE_NOT_EXIST }, +}; + +static unsigned long skf_get_error_reason(ULONG ulError) +{ + int i; + for (i = 0; i < OSSL_NELEM(skf_errors); i++) { + if (ulError == skf_errors[i].err) { + return skf_errors[i].reason; + } + } + if (skf_vendor) { + return skf_vendor->get_error_reason(ulError); + } + return 0; +} + +ULONG SKF_GetErrorString(ULONG ulError, LPSTR *szErrorStr) +{ + unsigned long reason; + + if ((reason = skf_get_error_reason(ulError)) != 0) { + *szErrorStr = (LPSTR)ERR_reason_error_string(reason); + } else { + *szErrorStr = (LPSTR)"(unknown)"; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_WaitForDevEvent( + LPSTR szDevName, + ULONG *pulDevNameLen, + ULONG *pulEvent) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_WAITFORDEVEVENT, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->WaitForDevEvent) { + SKFerr(SKF_F_SKF_WAITFORDEVEVENT, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->WaitForDevEvent( + szDevName, + pulDevNameLen, + pulEvent)) != SAR_OK) { + SKFerr(SKF_F_SKF_WAITFORDEVEVENT, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_CancelWaitForDevEvent( + void) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_CANCELWAITFORDEVEVENT, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->CancelWaitForDevEvent) { + SKFerr(SKF_F_SKF_CANCELWAITFORDEVEVENT, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if (skf_method->CancelWaitForDevEvent) { + return skf_method->CancelWaitForDevEvent(); + } + + if ((rv = skf_method->CancelWaitForDevEvent()) != SAR_OK) { + SKFerr(SKF_F_SKF_CANCELWAITFORDEVEVENT, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_EnumDev( + BOOL bPresent, + LPSTR szNameList, + ULONG *pulSize) +{ + ULONG rv; + + + // check output of all enum functions !!!! + + if (!skf_method) { + SKFerr(SKF_F_SKF_ENUMDEV, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->EnumDev) { + SKFerr(SKF_F_SKF_ENUMDEV, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if (szNameList) { + memset(szNameList, 0, *pulSize); + } + + if ((rv = skf_method->EnumDev( + bPresent, + szNameList, + pulSize)) != SAR_OK) { + SKFerr(SKF_F_SKF_ENUMDEV, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ConnectDev( + LPSTR szName, + DEVHANDLE *phDev) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_CONNECTDEV, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->ConnectDev) { + SKFerr(SKF_F_SKF_CONNECTDEV, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->ConnectDev( + szName, + phDev)) != SAR_OK) { + SKFerr(SKF_F_SKF_CONNECTDEV, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_DisConnectDev( + DEVHANDLE hDev) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_DISCONNECTDEV, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->DisConnectDev) { + SKFerr(SKF_F_SKF_DISCONNECTDEV, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->DisConnectDev( + hDev)) != SAR_OK) { + SKFerr(SKF_F_SKF_DISCONNECTDEV, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_GetDevState( + LPSTR szDevName, + ULONG *pulDevState) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_GETDEVSTATE, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->GetDevState) { + SKFerr(SKF_F_SKF_GETDEVSTATE, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->GetDevState( + szDevName, + pulDevState)) != SAR_OK) { + SKFerr(SKF_F_SKF_GETDEVSTATE, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_SetLabel( + DEVHANDLE hDev, + LPSTR szLabel) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_SETLABEL, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->SetLabel) { + SKFerr(SKF_F_SKF_SETLABEL, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->SetLabel( + hDev, + szLabel)) != SAR_OK) { + SKFerr(SKF_F_SKF_SETLABEL, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_GetDevInfo( + DEVHANDLE hDev, + DEVINFO *pDevInfo) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_GETDEVINFO, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->GetDevInfo) { + SKFerr(SKF_F_SKF_GETDEVINFO, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + memset(pDevInfo, 0, sizeof(DEVINFO)); + + if ((rv = skf_method->GetDevInfo( + hDev, + pDevInfo)) != SAR_OK) { + SKFerr(SKF_F_SKF_GETDEVINFO, skf_get_error_reason(rv)); + printf("rv = %8x\n", rv); + return rv; + } + + if (skf_vendor) { + pDevInfo->AlgSymCap = skf_vendor->get_cipher_cap(pDevInfo->AlgSymCap); + pDevInfo->AlgAsymCap = skf_vendor->get_pkey_cap(pDevInfo->AlgAsymCap); + pDevInfo->AlgHashCap = skf_vendor->get_digest_cap(pDevInfo->AlgHashCap); + pDevInfo->DevAuthAlgId = skf_vendor->get_cipher_cap(pDevInfo->DevAuthAlgId); + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_LockDev( + DEVHANDLE hDev, + ULONG ulTimeOut) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_LOCKDEV, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->LockDev) { + SKFerr(SKF_F_SKF_LOCKDEV, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->LockDev( + hDev, + ulTimeOut)) != SAR_OK) { + SKFerr(SKF_F_SKF_LOCKDEV, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_UnlockDev( + DEVHANDLE hDev) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_UNLOCKDEV, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->UnlockDev) { + SKFerr(SKF_F_SKF_UNLOCKDEV, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->UnlockDev( + hDev)) != SAR_OK) { + SKFerr(SKF_F_SKF_UNLOCKDEV, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_Transmit( + DEVHANDLE hDev, + BYTE *pbCommand, + ULONG ulCommandLen, + BYTE *pbData, + ULONG *pulDataLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_TRANSMIT, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->Transmit) { + SKFerr(SKF_F_SKF_TRANSMIT, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->Transmit( + hDev, + pbCommand, + ulCommandLen, + pbData, + pulDataLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_TRANSMIT, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ChangeDevAuthKey( + DEVHANDLE hDev, + BYTE *pbKeyValue, + ULONG ulKeyLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_CHANGEDEVAUTHKEY, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->ChangeDevAuthKey) { + SKFerr(SKF_F_SKF_CHANGEDEVAUTHKEY, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->ChangeDevAuthKey( + hDev, + pbKeyValue, + ulKeyLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_CHANGEDEVAUTHKEY, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_DevAuth( + DEVHANDLE hDev, + BYTE *pbAuthData, + ULONG ulLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_DEVAUTH, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->DevAuth) { + SKFerr(SKF_F_SKF_DEVAUTH, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->DevAuth( + hDev, + pbAuthData, + ulLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_DEVAUTH, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ChangePIN( + HAPPLICATION hApplication, + ULONG ulPINType, + LPSTR szOldPin, + LPSTR szNewPin, + ULONG *pulRetryCount) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_CHANGEPIN, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->ChangePIN) { + SKFerr(SKF_F_SKF_CHANGEPIN, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->ChangePIN( + hApplication, + ulPINType, + szOldPin, + szNewPin, + pulRetryCount)) != SAR_OK) { + SKFerr(SKF_F_SKF_CHANGEPIN, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +LONG DEVAPI SKF_GetPINInfo( + HAPPLICATION hApplication, + ULONG ulPINType, + ULONG *pulMaxRetryCount, + ULONG *pulRemainRetryCount, + BOOL *pbDefaultPin) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_GETPININFO, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->GetPINInfo) { + SKFerr(SKF_F_SKF_GETPININFO, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->GetPINInfo( + hApplication, + ulPINType, + pulMaxRetryCount, + pulRemainRetryCount, + pbDefaultPin)) != SAR_OK) { + SKFerr(SKF_F_SKF_GETPININFO, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_VerifyPIN( + HAPPLICATION hApplication, + ULONG ulPINType, + LPSTR szPIN, + ULONG *pulRetryCount) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_VERIFYPIN, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->VerifyPIN) { + SKFerr(SKF_F_SKF_VERIFYPIN, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->VerifyPIN( + hApplication, + ulPINType, + szPIN, + pulRetryCount)) != SAR_OK) { + SKFerr(SKF_F_SKF_VERIFYPIN, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_UnblockPIN( + HAPPLICATION hApplication, + LPSTR szAdminPIN, + LPSTR szNewUserPIN, + ULONG *pulRetryCount) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_UNBLOCKPIN, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->UnblockPIN) { + SKFerr(SKF_F_SKF_UNBLOCKPIN, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->UnblockPIN( + hApplication, + szAdminPIN, + szNewUserPIN, + pulRetryCount)) != SAR_OK) { + SKFerr(SKF_F_SKF_UNBLOCKPIN, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ClearSecureState( + HAPPLICATION hApplication) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_CLEARSECURESTATE, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->ClearSecureState) { + SKFerr(SKF_F_SKF_CLEARSECURESTATE, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->ClearSecureState( + hApplication)) != SAR_OK) { + SKFerr(SKF_F_SKF_CLEARSECURESTATE, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_CreateApplication( + DEVHANDLE hDev, + LPSTR szAppName, + LPSTR szAdminPin, + DWORD dwAdminPinRetryCount, + LPSTR szUserPin, + DWORD dwUserPinRetryCount, + DWORD dwCreateFileRights, + HAPPLICATION *phApplication) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_CREATEAPPLICATION, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->CreateApplication) { + SKFerr(SKF_F_SKF_CREATEAPPLICATION, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->CreateApplication( + hDev, + szAppName, + szAdminPin, + dwAdminPinRetryCount, + szUserPin, + dwUserPinRetryCount, + dwCreateFileRights, + phApplication)) != SAR_OK) { + SKFerr(SKF_F_SKF_CREATEAPPLICATION, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_EnumApplication( + DEVHANDLE hDev, + LPSTR szAppName, + ULONG *pulSize) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_ENUMAPPLICATION, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->EnumApplication) { + SKFerr(SKF_F_SKF_ENUMAPPLICATION, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->EnumApplication( + hDev, + szAppName, + pulSize)) != SAR_OK) { + SKFerr(SKF_F_SKF_ENUMAPPLICATION, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_DeleteApplication( + DEVHANDLE hDev, + LPSTR szAppName) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_DELETEAPPLICATION, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->DeleteApplication) { + SKFerr(SKF_F_SKF_DELETEAPPLICATION, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->DeleteApplication( + hDev, + szAppName)) != SAR_OK) { + SKFerr(SKF_F_SKF_DELETEAPPLICATION, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_OpenApplication( + DEVHANDLE hDev, + LPSTR szAppName, + HAPPLICATION *phApplication) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_OPENAPPLICATION, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->OpenApplication) { + SKFerr(SKF_F_SKF_OPENAPPLICATION, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->OpenApplication( + hDev, + szAppName, + phApplication)) != SAR_OK) { + SKFerr(SKF_F_SKF_OPENAPPLICATION, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_CloseApplication( + HAPPLICATION hApplication) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_CLOSEAPPLICATION, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->CloseApplication) { + SKFerr(SKF_F_SKF_CLOSEAPPLICATION, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->CloseApplication( + hApplication)) != SAR_OK) { + SKFerr(SKF_F_SKF_CLOSEAPPLICATION, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_CreateFile( + HAPPLICATION hApplication, + LPSTR szFileName, + ULONG ulFileSize, + ULONG ulReadRights, + ULONG ulWriteRights) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_CREATEFILE, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->CreateObject) { + SKFerr(SKF_F_SKF_CREATEFILE, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->CreateObject( + hApplication, + szFileName, + ulFileSize, + ulReadRights, + ulWriteRights)) != SAR_OK) { + SKFerr(SKF_F_SKF_CREATEFILE, skf_get_error_reason(rv)); + + //LPSTR str = NULL; + //printf("error = %08X\n", rv); + //SKF_GetErrorString(rv, &str); + //printf("error = %s\n", (char *)str); + + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_DeleteFile( + HAPPLICATION hApplication, + LPSTR szFileName) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_DELETEFILE, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->DeleteObject) { + SKFerr(SKF_F_SKF_DELETEFILE, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->DeleteObject( + hApplication, + szFileName)) != SAR_OK) { + SKFerr(SKF_F_SKF_DELETEFILE, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_EnumFiles( + HAPPLICATION hApplication, + LPSTR szFileList, + ULONG *pulSize) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_ENUMFILES, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->EnumObjects) { + SKFerr(SKF_F_SKF_ENUMFILES, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->EnumObjects( + hApplication, + szFileList, + pulSize)) != SAR_OK) { + SKFerr(SKF_F_SKF_ENUMFILES, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_GetFileInfo( + HAPPLICATION hApplication, + LPSTR szFileName, + FILEATTRIBUTE *pFileInfo) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_GETFILEINFO, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->GetObjectInfo) { + SKFerr(SKF_F_SKF_GETFILEINFO, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + memset(pFileInfo, 0, sizeof(FILEATTRIBUTE)); + + if ((rv = skf_method->GetObjectInfo( + hApplication, + szFileName, + pFileInfo)) != SAR_OK) { + SKFerr(SKF_F_SKF_GETFILEINFO, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ReadFile( + HAPPLICATION hApplication, + LPSTR szFileName, + ULONG ulOffset, + ULONG ulSize, + BYTE *pbOutData, + ULONG *pulOutLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_READFILE, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->ReadObject) { + SKFerr(SKF_F_SKF_READFILE, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->ReadObject( + hApplication, + szFileName, + ulOffset, + ulSize, + pbOutData, + pulOutLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_READFILE, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_WriteFile( + HAPPLICATION hApplication, + LPSTR szFileName, + ULONG ulOffset, + BYTE *pbData, + ULONG ulSize) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_WRITEFILE, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->WriteObject) { + SKFerr(SKF_F_SKF_WRITEFILE, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->WriteObject( + hApplication, + szFileName, + ulOffset, + pbData, + ulSize)) != SAR_OK) { + SKFerr(SKF_F_SKF_WRITEFILE, skf_get_error_reason(rv)); + + printf("error = %08X\n", rv); + + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_CreateContainer( + HAPPLICATION hApplication, + LPSTR szContainerName, + HCONTAINER *phContainer) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_CREATECONTAINER, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->CreateContainer) { + SKFerr(SKF_F_SKF_CREATECONTAINER, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->CreateContainer( + hApplication, + szContainerName, + phContainer)) != SAR_OK) { + SKFerr(SKF_F_SKF_CREATECONTAINER, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_DeleteContainer( + HAPPLICATION hApplication, + LPSTR szContainerName) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_DELETECONTAINER, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->DeleteContainer) { + SKFerr(SKF_F_SKF_DELETECONTAINER, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->DeleteContainer( + hApplication, + szContainerName)) != SAR_OK) { + SKFerr(SKF_F_SKF_DELETECONTAINER, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_EnumContainer( + HAPPLICATION hApplication, + LPSTR szContainerName, + ULONG *pulSize) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_ENUMCONTAINER, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->EnumContainer) { + SKFerr(SKF_F_SKF_ENUMCONTAINER, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->EnumContainer( + hApplication, + szContainerName, + pulSize)) != SAR_OK) { + SKFerr(SKF_F_SKF_ENUMCONTAINER, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_OpenContainer( + HAPPLICATION hApplication, + LPSTR szContainerName, + HCONTAINER *phContainer) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_OPENCONTAINER, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->OpenContainer) { + SKFerr(SKF_F_SKF_OPENCONTAINER, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->OpenContainer( + hApplication, + szContainerName, + phContainer)) != SAR_OK) { + SKFerr(SKF_F_SKF_OPENCONTAINER, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_CloseContainer( + HCONTAINER hContainer) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_CLOSECONTAINER, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->CloseContainer) { + SKFerr(SKF_F_SKF_CLOSECONTAINER, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->CloseContainer( + hContainer)) != SAR_OK) { + SKFerr(SKF_F_SKF_CLOSECONTAINER, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_GetContainerType( + HCONTAINER hContainer, + ULONG *pulContainerType) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_GETCONTAINERTYPE, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->GetContainerType) { + SKFerr(SKF_F_SKF_GETCONTAINERTYPE, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->GetContainerType( + hContainer, + pulContainerType)) != SAR_OK) { + SKFerr(SKF_F_SKF_GETCONTAINERTYPE, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ImportCertificate( + HCONTAINER hContainer, + BOOL bExportSignKey, + BYTE *pbCert, + ULONG ulCertLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_IMPORTCERTIFICATE, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->ImportCertificate) { + SKFerr(SKF_F_SKF_IMPORTCERTIFICATE, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->ImportCertificate( + hContainer, + bExportSignKey, + pbCert, + ulCertLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_IMPORTCERTIFICATE, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ExportCertificate( + HCONTAINER hContainer, + BOOL bSignFlag, + BYTE *pbCert, + ULONG *pulCertLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_EXPORTCERTIFICATE, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->ExportCertificate) { + SKFerr(SKF_F_SKF_EXPORTCERTIFICATE, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->ExportCertificate( + hContainer, + bSignFlag, + pbCert, + pulCertLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_EXPORTCERTIFICATE, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ExportPublicKey( + HCONTAINER hContainer, + BOOL bSignFlag, + BYTE *pbBlob, + ULONG *pulBlobLen) +{ + ULONG rv; + + // TODO: check the output length, clear the memmory. + // if pbBlob is NULL, return the length + + if (!skf_method) { + SKFerr(SKF_F_SKF_EXPORTPUBLICKEY, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->ExportPublicKey) { + SKFerr(SKF_F_SKF_EXPORTPUBLICKEY, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->ExportPublicKey( + hContainer, + bSignFlag, + pbBlob, + pulBlobLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_EXPORTPUBLICKEY, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_GenRandom( + DEVHANDLE hDev, + BYTE *pbRandom, + ULONG ulRandomLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_GENRANDOM, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->GenRandom) { + SKFerr(SKF_F_SKF_GENRANDOM, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->GenRandom( + hDev, + pbRandom, + ulRandomLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_GENRANDOM, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_GenExtRSAKey( + DEVHANDLE hDev, + ULONG ulBitsLen, + RSAPRIVATEKEYBLOB *pBlob) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_GENEXTRSAKEY, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->GenExtRSAKey) { + SKFerr(SKF_F_SKF_GENEXTRSAKEY, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->GenExtRSAKey( + hDev, + ulBitsLen, + pBlob)) != SAR_OK) { + SKFerr(SKF_F_SKF_GENEXTRSAKEY, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_GenRSAKeyPair( + HCONTAINER hContainer, + ULONG ulBitsLen, + RSAPUBLICKEYBLOB *pBlob) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_GENRSAKEYPAIR, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->GenRSAKeyPair) { + SKFerr(SKF_F_SKF_GENRSAKEYPAIR, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + memset(pBlob, 0, sizeof(RSAPUBLICKEYBLOB)); + if ((rv = skf_method->GenRSAKeyPair( + hContainer, + ulBitsLen, + pBlob)) != SAR_OK) { + SKFerr(SKF_F_SKF_GENRSAKEYPAIR, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ImportRSAKeyPair( + HCONTAINER hContainer, + ULONG ulSymAlgId, + BYTE *pbWrappedKey, + ULONG ulWrappedKeyLen, + BYTE *pbEncryptedData, + ULONG ulEncryptedDataLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_IMPORTRSAKEYPAIR, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->ImportRSAKeyPair) { + SKFerr(SKF_F_SKF_IMPORTRSAKEYPAIR, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if (skf_vendor) { + if (!(ulSymAlgId = skf_vendor->get_cipher_algor(ulSymAlgId))) { + SKFerr(SKF_F_SKF_IMPORTRSAKEYPAIR, + SKF_R_NOT_SUPPORTED_CIPHER_ALGOR); + return SAR_NOTSUPPORTYETERR; + } + } + + if ((rv = skf_method->ImportRSAKeyPair( + hContainer, + ulSymAlgId, + pbWrappedKey, + ulWrappedKeyLen, + pbEncryptedData, + ulEncryptedDataLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_IMPORTRSAKEYPAIR, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_RSASignData( + HCONTAINER hContainer, + BYTE *pbData, + ULONG ulDataLen, + BYTE *pbSignature, + ULONG *pulSignLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_RSASIGNDATA, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->RSASignData) { + SKFerr(SKF_F_SKF_RSASIGNDATA, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->RSASignData( + hContainer, + pbData, + ulDataLen, + pbSignature, + pulSignLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_RSASIGNDATA, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_RSAVerify( + DEVHANDLE hDev, + RSAPUBLICKEYBLOB *pRSAPubKeyBlob, + BYTE *pbData, + ULONG ulDataLen, + BYTE *pbSignature, + ULONG ulSignLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_RSAVERIFY, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->RSAVerify) { + SKFerr(SKF_F_SKF_RSAVERIFY, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->RSAVerify( + hDev, + pRSAPubKeyBlob, + pbData, + ulDataLen, + pbSignature, + ulSignLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_RSAVERIFY, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_RSAExportSessionKey( + HCONTAINER hContainer, + ULONG ulAlgId, + RSAPUBLICKEYBLOB *pPubKey, + BYTE *pbData, + ULONG *pulDataLen, + HANDLE *phSessionKey) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_RSAEXPORTSESSIONKEY, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->RSAExportSessionKey) { + SKFerr(SKF_F_SKF_RSAEXPORTSESSIONKEY, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if (skf_vendor) { + if (!(ulAlgId = skf_vendor->get_cipher_algor(ulAlgId))) { + SKFerr(SKF_F_SKF_RSAEXPORTSESSIONKEY, + SKF_R_NOT_SUPPORTED_CIPHER_ALGOR); + return SAR_NOTSUPPORTYETERR; + } + } + + if ((rv = skf_method->RSAExportSessionKey( + hContainer, + ulAlgId, + pPubKey, + pbData, + pulDataLen, + phSessionKey)) != SAR_OK) { + SKFerr(SKF_F_SKF_RSAEXPORTSESSIONKEY, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ExtRSAPubKeyOperation( + DEVHANDLE hDev, + RSAPUBLICKEYBLOB *pRSAPubKeyBlob, + BYTE *pbInput, + ULONG ulInputLen, + BYTE *pbOutput, + ULONG *pulOutputLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_EXTRSAPUBKEYOPERATION, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->ExtRSAPubKeyOperation) { + SKFerr(SKF_F_SKF_EXTRSAPUBKEYOPERATION, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->ExtRSAPubKeyOperation( + hDev, + pRSAPubKeyBlob, + pbInput, + ulInputLen, + pbOutput, + pulOutputLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_EXTRSAPUBKEYOPERATION, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ExtRSAPriKeyOperation( + DEVHANDLE hDev, + RSAPRIVATEKEYBLOB *pRSAPriKeyBlob, + BYTE *pbInput, + ULONG ulInputLen, + BYTE *pbOutput, + ULONG *pulOutputLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_EXTRSAPRIKEYOPERATION, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->ExtRSAPriKeyOperation) { + SKFerr(SKF_F_SKF_EXTRSAPRIKEYOPERATION, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->ExtRSAPriKeyOperation( + hDev, + pRSAPriKeyBlob, + pbInput, + ulInputLen, + pbOutput, + pulOutputLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_EXTRSAPRIKEYOPERATION, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_GenECCKeyPair( + HCONTAINER hContainer, + ULONG ulAlgId, + ECCPUBLICKEYBLOB *pBlob) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_GENECCKEYPAIR, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->GenECCKeyPair) { + SKFerr(SKF_F_SKF_GENECCKEYPAIR, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if (skf_vendor) { + if (!(ulAlgId = skf_vendor->get_pkey_algor(ulAlgId))) { + SKFerr(SKF_F_SKF_GENECCKEYPAIR, + SKF_R_NOT_SUPPORTED_PKEY_ALGOR); + return SAR_NOTSUPPORTYETERR; + } + } + + memset(pBlob, 0, sizeof(ECCPUBLICKEYBLOB)); + if ((rv = skf_method->GenECCKeyPair( + hContainer, + ulAlgId, + pBlob)) != SAR_OK) { + SKFerr(SKF_F_SKF_GENECCKEYPAIR, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ImportECCKeyPair( + HCONTAINER hContainer, + ENVELOPEDKEYBLOB *pEnvelopedKeyBlob) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_IMPORTECCKEYPAIR, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->ImportECCKeyPair) { + SKFerr(SKF_F_SKF_IMPORTECCKEYPAIR, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->ImportECCKeyPair( + hContainer, + pEnvelopedKeyBlob)) != SAR_OK) { + SKFerr(SKF_F_SKF_IMPORTECCKEYPAIR, skf_get_error_reason(rv)); + printf("%s %d: error = %08X\n", __FILE__, __LINE__, rv); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ECCSignData( + HCONTAINER hContainer, + BYTE *pbDigest, + ULONG ulDigestLen, + ECCSIGNATUREBLOB *pSignature) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_ECCSIGNDATA, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->ECCSignData) { + SKFerr(SKF_F_SKF_ECCSIGNDATA, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->ECCSignData( + hContainer, + pbDigest, + ulDigestLen, + pSignature)) != SAR_OK) { + SKFerr(SKF_F_SKF_ECCSIGNDATA, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ECCVerify( + DEVHANDLE hDev, + ECCPUBLICKEYBLOB *pECCPubKeyBlob, + BYTE *pbData, + ULONG ulDataLen, + ECCSIGNATUREBLOB *pSignature) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_ECCVERIFY, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->ECCVerify) { + SKFerr(SKF_F_SKF_ECCVERIFY, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->ECCVerify( + hDev, + pECCPubKeyBlob, + pbData, + ulDataLen, + pSignature)) != SAR_OK) { + SKFerr(SKF_F_SKF_ECCVERIFY, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ECCExportSessionKey( + HCONTAINER hContainer, + ULONG ulAlgId, + ECCPUBLICKEYBLOB *pPubKey, + ECCCIPHERBLOB *pData, + HANDLE *phSessionKey) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_ECCEXPORTSESSIONKEY, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->ECCExportSessionKey) { + SKFerr(SKF_F_SKF_ECCEXPORTSESSIONKEY, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if (skf_vendor) { + if (!(ulAlgId = skf_vendor->get_cipher_algor(ulAlgId))) { + SKFerr(SKF_F_SKF_ECCEXPORTSESSIONKEY, + SKF_R_NOT_SUPPORTED_CIPHER_ALGOR); + return SAR_NOTSUPPORTYETERR; + } + } + + if ((rv = skf_method->ECCExportSessionKey( + hContainer, + ulAlgId, + pPubKey, + pData, + phSessionKey)) != SAR_OK) { + SKFerr(SKF_F_SKF_ECCEXPORTSESSIONKEY, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ECCDecrypt( + HCONTAINER hContainer, + ECCCIPHERBLOB *pCipherText, + BYTE *pbPlainText, + ULONG *pulPlainTextLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_ECCDECRYPT, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->ECCDecrypt) { + SKFerr(SKF_F_SKF_ECCDECRYPT, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->ECCDecrypt( + hContainer, + pCipherText, + pbPlainText, + pulPlainTextLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_ECCDECRYPT, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ExtECCEncrypt( + DEVHANDLE hDev, + ECCPUBLICKEYBLOB *pECCPubKeyBlob, + BYTE *pbPlainText, + ULONG ulPlainTextLen, + ECCCIPHERBLOB *pCipherText) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_EXTECCENCRYPT, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->ExtECCEncrypt) { + SKFerr(SKF_F_SKF_EXTECCENCRYPT, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->ExtECCEncrypt( + hDev, + pECCPubKeyBlob, + pbPlainText, + ulPlainTextLen, + pCipherText)) != SAR_OK) { + SKFerr(SKF_F_SKF_EXTECCENCRYPT, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ExtECCDecrypt( + DEVHANDLE hDev, + ECCPRIVATEKEYBLOB *pECCPriKeyBlob, + ECCCIPHERBLOB *pCipherText, + BYTE *pbPlainText, + ULONG *pulPlainTextLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_EXTECCDECRYPT, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->ExtECCDecrypt) { + SKFerr(SKF_F_SKF_EXTECCDECRYPT, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->ExtECCDecrypt( + hDev, + pECCPriKeyBlob, + pCipherText, + pbPlainText, + pulPlainTextLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_EXTECCDECRYPT, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ExtECCSign( + DEVHANDLE hDev, + ECCPRIVATEKEYBLOB *pECCPriKeyBlob, + BYTE *pbData, + ULONG ulDataLen, + ECCSIGNATUREBLOB *pSignature) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_EXTECCSIGN, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->ExtECCSign) { + SKFerr(SKF_F_SKF_EXTECCSIGN, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->ExtECCSign( + hDev, + pECCPriKeyBlob, + pbData, + ulDataLen, + pSignature)) != SAR_OK) { + SKFerr(SKF_F_SKF_EXTECCSIGN, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ExtECCVerify( + DEVHANDLE hDev, + ECCPUBLICKEYBLOB *pECCPubKeyBlob, + BYTE *pbData, + ULONG ulDataLen, + ECCSIGNATUREBLOB *pSignature) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_EXTECCVERIFY, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->ExtECCVerify) { + SKFerr(SKF_F_SKF_EXTECCVERIFY, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->ExtECCVerify( + hDev, + pECCPubKeyBlob, + pbData, + ulDataLen, + pSignature)) != SAR_OK) { + SKFerr(SKF_F_SKF_EXTECCVERIFY, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_GenerateAgreementDataWithECC( + HCONTAINER hContainer, + ULONG ulAlgId, + ECCPUBLICKEYBLOB *pTempECCPubKeyBlob, + BYTE *pbID, + ULONG ulIDLen, + HANDLE *phAgreementHandle) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_GENERATEAGREEMENTDATAWITHECC, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->GenerateAgreementDataWithECC) { + SKFerr(SKF_F_SKF_GENERATEAGREEMENTDATAWITHECC, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if (skf_vendor) { + if (!(ulAlgId = skf_vendor->get_cipher_algor(ulAlgId))) { + SKFerr(SKF_F_SKF_GENERATEAGREEMENTDATAWITHECC, + SKF_R_NOT_SUPPORTED_CIPHER_ALGOR); + return SAR_NOTSUPPORTYETERR; + } + } + + if ((rv = skf_method->GenerateAgreementDataWithECC( + hContainer, + ulAlgId, + pTempECCPubKeyBlob, + pbID, + ulIDLen, + phAgreementHandle)) != SAR_OK) { + SKFerr(SKF_F_SKF_GENERATEAGREEMENTDATAWITHECC, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_GenerateAgreementDataAndKeyWithECC( + HANDLE hContainer, + ULONG ulAlgId, + ECCPUBLICKEYBLOB *pSponsorECCPubKeyBlob, + ECCPUBLICKEYBLOB *pSponsorTempECCPubKeyBlob, + ECCPUBLICKEYBLOB *pTempECCPubKeyBlob, + BYTE *pbID, + ULONG ulIDLen, + BYTE *pbSponsorID, + ULONG ulSponsorIDLen, + HANDLE *phKeyHandle) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_GENERATEAGREEMENTDATAANDKEYWITHECC, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->GenerateAgreementDataAndKeyWithECC) { + SKFerr(SKF_F_SKF_GENERATEAGREEMENTDATAANDKEYWITHECC, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if (skf_vendor) { + if (!(ulAlgId = skf_vendor->get_cipher_algor(ulAlgId))) { + SKFerr(SKF_F_SKF_GENERATEAGREEMENTDATAANDKEYWITHECC, + SKF_R_NOT_SUPPORTED_CIPHER_ALGOR); + return SAR_NOTSUPPORTYETERR; + } + } + + if ((rv = skf_method->GenerateAgreementDataAndKeyWithECC( + hContainer, + ulAlgId, + pSponsorECCPubKeyBlob, + pSponsorTempECCPubKeyBlob, + pTempECCPubKeyBlob, + pbID, + ulIDLen, + pbSponsorID, + ulSponsorIDLen, + phKeyHandle)) != SAR_OK) { + SKFerr(SKF_F_SKF_GENERATEAGREEMENTDATAANDKEYWITHECC, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_GenerateKeyWithECC( + HANDLE hAgreementHandle, + ECCPUBLICKEYBLOB *pECCPubKeyBlob, + ECCPUBLICKEYBLOB *pTempECCPubKeyBlob, + BYTE *pbID, + ULONG ulIDLen, + HANDLE *phKeyHandle) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_GENERATEKEYWITHECC, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->GenerateKeyWithECC) { + SKFerr(SKF_F_SKF_GENERATEKEYWITHECC, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->GenerateKeyWithECC( + hAgreementHandle, + pECCPubKeyBlob, + pTempECCPubKeyBlob, + pbID, + ulIDLen, + phKeyHandle)) != SAR_OK) { + SKFerr(SKF_F_SKF_GENERATEKEYWITHECC, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_ImportSessionKey( + HCONTAINER hContainer, + ULONG ulAlgId, + BYTE *pbWrapedData, + ULONG ulWrapedLen, + HANDLE *phKey) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_IMPORTSESSIONKEY, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->ImportSessionKey) { + SKFerr(SKF_F_SKF_IMPORTSESSIONKEY, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if (skf_vendor) { + if (!(ulAlgId = skf_vendor->get_cipher_algor(ulAlgId))) { + SKFerr(SKF_F_SKF_IMPORTSESSIONKEY, + SKF_R_NOT_SUPPORTED_CIPHER_ALGOR); + return SAR_NOTSUPPORTYETERR; + } + } + + if ((rv = skf_method->ImportSessionKey( + hContainer, + ulAlgId, + pbWrapedData, + ulWrapedLen, + phKey)) != SAR_OK) { + SKFerr(SKF_F_SKF_IMPORTSESSIONKEY, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_SetSymmKey( + DEVHANDLE hDev, + BYTE *pbKey, + ULONG ulAlgID, + HANDLE *phKey) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_SETSYMMKEY, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->SetSymmKey) { + SKFerr(SKF_F_SKF_SETSYMMKEY, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if (skf_vendor) { + if (!(ulAlgID = skf_vendor->get_cipher_algor(ulAlgID))) { + SKFerr(SKF_F_SKF_SETSYMMKEY, + SKF_R_NOT_SUPPORTED_CIPHER_ALGOR); + return SAR_NOTSUPPORTYETERR; + } + } + + if ((rv = skf_method->SetSymmKey( + hDev, + pbKey, + ulAlgID, + phKey)) != SAR_OK) { + SKFerr(SKF_F_SKF_SETSYMMKEY, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_EncryptInit( + HANDLE hKey, + BLOCKCIPHERPARAM EncryptParam) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_ENCRYPTINIT, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->EncryptInit) { + SKFerr(SKF_F_SKF_ENCRYPTINIT, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->EncryptInit( + hKey, + EncryptParam)) != SAR_OK) { + SKFerr(SKF_F_SKF_ENCRYPTINIT, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_Encrypt( + HANDLE hKey, + BYTE *pbData, + ULONG ulDataLen, + BYTE *pbEncryptedData, + ULONG *pulEncryptedLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_ENCRYPT, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->Encrypt) { + SKFerr(SKF_F_SKF_ENCRYPT, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->Encrypt( + hKey, + pbData, + ulDataLen, + pbEncryptedData, + pulEncryptedLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_ENCRYPT, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_EncryptUpdate( + HANDLE hKey, + BYTE *pbData, + ULONG ulDataLen, + BYTE *pbEncryptedData, + ULONG *pulEncryptedLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_ENCRYPTUPDATE, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->EncryptUpdate) { + SKFerr(SKF_F_SKF_ENCRYPTUPDATE, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->EncryptUpdate( + hKey, + pbData, + ulDataLen, + pbEncryptedData, + pulEncryptedLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_ENCRYPTUPDATE, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_EncryptFinal( + HANDLE hKey, + BYTE *pbEncryptedData, + ULONG *pulEncryptedDataLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_ENCRYPTFINAL, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->EncryptFinal) { + SKFerr(SKF_F_SKF_ENCRYPTFINAL, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->EncryptFinal( + hKey, + pbEncryptedData, + pulEncryptedDataLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_ENCRYPTFINAL, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_DecryptInit( + HANDLE hKey, + BLOCKCIPHERPARAM DecryptParam) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_DECRYPTINIT, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->DecryptInit) { + SKFerr(SKF_F_SKF_DECRYPTINIT, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->DecryptInit( + hKey, + DecryptParam)) != SAR_OK) { + SKFerr(SKF_F_SKF_DECRYPTINIT, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_Decrypt( + HANDLE hKey, + BYTE *pbEncryptedData, + ULONG ulEncryptedLen, + BYTE *pbData, + ULONG *pulDataLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_DECRYPT, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->Decrypt) { + SKFerr(SKF_F_SKF_DECRYPT, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->Decrypt( + hKey, + pbEncryptedData, + ulEncryptedLen, + pbData, + pulDataLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_DECRYPT, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_DecryptUpdate( + HANDLE hKey, + BYTE *pbEncryptedData, + ULONG ulEncryptedLen, + BYTE *pbData, + ULONG *pulDataLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_DECRYPTUPDATE, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->DecryptUpdate) { + SKFerr(SKF_F_SKF_DECRYPTUPDATE, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->DecryptUpdate( + hKey, + pbEncryptedData, + ulEncryptedLen, + pbData, + pulDataLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_DECRYPTUPDATE, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_DecryptFinal( + HANDLE hKey, + BYTE *pbDecryptedData, + ULONG *pulDecryptedDataLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_DECRYPTFINAL, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->DecryptFinal) { + SKFerr(SKF_F_SKF_DECRYPTFINAL, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->DecryptFinal( + hKey, + pbDecryptedData, + pulDecryptedDataLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_DECRYPTFINAL, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_DigestInit( + DEVHANDLE hDev, + ULONG ulAlgID, + ECCPUBLICKEYBLOB *pPubKey, + BYTE *pbID, + ULONG ulIDLen, + HANDLE *phHash) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_DIGESTINIT, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->DigestInit) { + SKFerr(SKF_F_SKF_DIGESTINIT, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if (skf_vendor) { + if (!(ulAlgID = skf_vendor->get_digest_algor(ulAlgID))) { + SKFerr(SKF_F_SKF_DIGESTINIT, + SKF_R_NOT_SUPPORTED_DIGEST_ALGOR); + return SAR_NOTSUPPORTYETERR; + } + } + + if ((rv = skf_method->DigestInit( + hDev, + ulAlgID, + pPubKey, + pbID, + ulIDLen, + phHash)) != SAR_OK) { + SKFerr(SKF_F_SKF_DIGESTINIT, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_Digest( + HANDLE hHash, + BYTE *pbData, + ULONG ulDataLen, + BYTE *pbHashData, + ULONG *pulHashLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_DIGEST, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->Digest) { + SKFerr(SKF_F_SKF_DIGEST, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->Digest( + hHash, + pbData, + ulDataLen, + pbHashData, + pulHashLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_DIGEST, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_DigestUpdate( + HANDLE hHash, + BYTE *pbData, + ULONG ulDataLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_DIGESTUPDATE, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->DigestUpdate) { + SKFerr(SKF_F_SKF_DIGESTUPDATE, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->DigestUpdate( + hHash, + pbData, + ulDataLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_DIGESTUPDATE, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_DigestFinal( + HANDLE hHash, + BYTE *pHashData, + ULONG *pulHashLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_DIGESTFINAL, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->DigestFinal) { + SKFerr(SKF_F_SKF_DIGESTFINAL, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->DigestFinal( + hHash, + pHashData, + pulHashLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_DIGESTFINAL, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_MacInit( + HANDLE hKey, + BLOCKCIPHERPARAM *pMacParam, + HANDLE *phMac) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_MACINIT, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->MacInit) { + SKFerr(SKF_F_SKF_MACINIT, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->MacInit( + hKey, + pMacParam, + phMac)) != SAR_OK) { + SKFerr(SKF_F_SKF_MACINIT, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_Mac( + HANDLE hMac, + BYTE *pbData, + ULONG ulDataLen, + BYTE *pbMacData, + ULONG *pulMacLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_MAC, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->Mac) { + SKFerr(SKF_F_SKF_MAC, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->Mac( + hMac, + pbData, + ulDataLen, + pbMacData, + pulMacLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_MAC, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_MacUpdate( + HANDLE hMac, + BYTE *pbData, + ULONG ulDataLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_MACUPDATE, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->MacUpdate) { + SKFerr(SKF_F_SKF_MACUPDATE, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->MacUpdate( + hMac, + pbData, + ulDataLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_MACUPDATE, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_MacFinal( + HANDLE hMac, + BYTE *pbMacData, + ULONG *pulMacDataLen) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_MACFINAL, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->MacFinal) { + SKFerr(SKF_F_SKF_MACFINAL, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->MacFinal( + hMac, + pbMacData, + pulMacDataLen)) != SAR_OK) { + SKFerr(SKF_F_SKF_MACFINAL, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + +ULONG DEVAPI SKF_CloseHandle( + HANDLE hHandle) +{ + ULONG rv; + + if (!skf_method) { + SKFerr(SKF_F_SKF_CLOSEHANDLE, + SKF_R_SKF_METHOD_NOT_INITIALIZED); + return SAR_NOTINITIALIZEERR; + } + + if (!skf_method->CloseHandle) { + SKFerr(SKF_F_SKF_CLOSEHANDLE, + SKF_R_FUNCTION_NOT_SUPPORTED); + return SAR_NOTSUPPORTYETERR; + } + + if ((rv = skf_method->CloseHandle( + hHandle)) != SAR_OK) { + SKFerr(SKF_F_SKF_CLOSEHANDLE, skf_get_error_reason(rv)); + return rv; + } + + return SAR_OK; +} + diff --git a/skf/skf_meth.c b/skf/skf_meth.c new file mode 100644 index 00000000..a5fad81f --- /dev/null +++ b/skf/skf_meth.c @@ -0,0 +1,172 @@ +/* ==================================================================== + * Copyright (c) 2014 - 2017 The GmSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the GmSSL Project. + * (http://gmssl.org/)" + * + * 4. The name "GmSSL Project" must not be used to endorse or promote + * products derived from this software without prior written + * permission. For written permission, please contact + * guanzhi1980@gmail.com. + * + * 5. Products derived from this software may not be called "GmSSL" + * nor may "GmSSL" appear in their names without prior written + * permission of the GmSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the GmSSL Project + * (http://gmssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ + +#include +#include +#include "internal/dso.h" +#include "internal/skf_int.h" + + +#define SKF_METHOD_BIND_FUNCTION_EX(func,name) \ + skf->func = (SKF_##func##_FuncPtr)DSO_bind_func(skf->dso, "SKF_"#name) + +#define SKF_METHOD_BIND_FUNCTION(func) \ + SKF_METHOD_BIND_FUNCTION_EX(func,func) + + +SKF_METHOD *SKF_METHOD_load_library(const char *so_path) +{ + SKF_METHOD *ret = NULL; + SKF_METHOD *skf = NULL; + + if (!(skf = OPENSSL_zalloc(sizeof(*skf)))) { + SKFerr(SKF_F_SKF_METHOD_LOAD_LIBRARY, ERR_R_MALLOC_FAILURE); + goto end; + } + if (!(skf->dso = DSO_load(NULL, so_path, NULL, 0))) { + SKFerr(SKF_F_SKF_METHOD_LOAD_LIBRARY, SKF_R_DSO_LOAD_FAILURE); + goto end; + } + + SKF_METHOD_BIND_FUNCTION(WaitForDevEvent); + SKF_METHOD_BIND_FUNCTION(CancelWaitForDevEvent); + SKF_METHOD_BIND_FUNCTION(EnumDev); + SKF_METHOD_BIND_FUNCTION(ConnectDev); + SKF_METHOD_BIND_FUNCTION(DisConnectDev); + SKF_METHOD_BIND_FUNCTION(GetDevState); + SKF_METHOD_BIND_FUNCTION(SetLabel); + SKF_METHOD_BIND_FUNCTION(GetDevInfo); + SKF_METHOD_BIND_FUNCTION(LockDev); + SKF_METHOD_BIND_FUNCTION(UnlockDev); + SKF_METHOD_BIND_FUNCTION(Transmit); + SKF_METHOD_BIND_FUNCTION(ChangeDevAuthKey); + SKF_METHOD_BIND_FUNCTION(DevAuth); + SKF_METHOD_BIND_FUNCTION(ChangePIN); + SKF_METHOD_BIND_FUNCTION(GetPINInfo); + SKF_METHOD_BIND_FUNCTION(VerifyPIN); + SKF_METHOD_BIND_FUNCTION(UnblockPIN); + SKF_METHOD_BIND_FUNCTION(ClearSecureState); + SKF_METHOD_BIND_FUNCTION(CreateApplication); + SKF_METHOD_BIND_FUNCTION(EnumApplication); + SKF_METHOD_BIND_FUNCTION(DeleteApplication); + SKF_METHOD_BIND_FUNCTION(OpenApplication); + SKF_METHOD_BIND_FUNCTION(CloseApplication); + SKF_METHOD_BIND_FUNCTION_EX(CreateObject,CreateFile); + SKF_METHOD_BIND_FUNCTION_EX(DeleteObject,DeleteFile); + SKF_METHOD_BIND_FUNCTION_EX(EnumObjects,EnumFiles); + SKF_METHOD_BIND_FUNCTION_EX(GetObjectInfo,GetFileInfo); + SKF_METHOD_BIND_FUNCTION_EX(ReadObject,ReadFile); + SKF_METHOD_BIND_FUNCTION_EX(WriteObject,WriteFile); + SKF_METHOD_BIND_FUNCTION(CreateContainer); + SKF_METHOD_BIND_FUNCTION(DeleteContainer); + SKF_METHOD_BIND_FUNCTION(EnumContainer); + SKF_METHOD_BIND_FUNCTION(OpenContainer); + SKF_METHOD_BIND_FUNCTION(CloseContainer); + SKF_METHOD_BIND_FUNCTION(GetContainerType); + SKF_METHOD_BIND_FUNCTION(ImportCertificate); + SKF_METHOD_BIND_FUNCTION(ExportCertificate); + SKF_METHOD_BIND_FUNCTION(ExportPublicKey); + SKF_METHOD_BIND_FUNCTION(GenRandom); + SKF_METHOD_BIND_FUNCTION(GenExtRSAKey); + SKF_METHOD_BIND_FUNCTION(GenRSAKeyPair); + SKF_METHOD_BIND_FUNCTION(ImportRSAKeyPair); + SKF_METHOD_BIND_FUNCTION(RSASignData); + SKF_METHOD_BIND_FUNCTION(RSAVerify); + SKF_METHOD_BIND_FUNCTION(RSAExportSessionKey); + SKF_METHOD_BIND_FUNCTION(ExtRSAPubKeyOperation); + SKF_METHOD_BIND_FUNCTION(ExtRSAPriKeyOperation); + SKF_METHOD_BIND_FUNCTION(GenECCKeyPair); + SKF_METHOD_BIND_FUNCTION(ImportECCKeyPair); + SKF_METHOD_BIND_FUNCTION(ECCSignData); + SKF_METHOD_BIND_FUNCTION(ECCVerify); + SKF_METHOD_BIND_FUNCTION(ECCExportSessionKey); + SKF_METHOD_BIND_FUNCTION(ExtECCEncrypt); + SKF_METHOD_BIND_FUNCTION(ExtECCDecrypt); + SKF_METHOD_BIND_FUNCTION(ExtECCSign); + SKF_METHOD_BIND_FUNCTION(ExtECCVerify); + SKF_METHOD_BIND_FUNCTION(GenerateAgreementDataWithECC); + SKF_METHOD_BIND_FUNCTION(GenerateAgreementDataAndKeyWithECC); + SKF_METHOD_BIND_FUNCTION(GenerateKeyWithECC); + SKF_METHOD_BIND_FUNCTION(ImportSessionKey); + SKF_METHOD_BIND_FUNCTION(SetSymmKey); + SKF_METHOD_BIND_FUNCTION(EncryptInit); + SKF_METHOD_BIND_FUNCTION(Encrypt); + SKF_METHOD_BIND_FUNCTION(EncryptUpdate); + SKF_METHOD_BIND_FUNCTION(EncryptFinal); + SKF_METHOD_BIND_FUNCTION(DecryptInit); + SKF_METHOD_BIND_FUNCTION(Decrypt); + SKF_METHOD_BIND_FUNCTION(DecryptUpdate); + SKF_METHOD_BIND_FUNCTION(DecryptFinal); + SKF_METHOD_BIND_FUNCTION(DigestInit); + SKF_METHOD_BIND_FUNCTION(Digest); + SKF_METHOD_BIND_FUNCTION(DigestUpdate); + SKF_METHOD_BIND_FUNCTION(DigestFinal); + SKF_METHOD_BIND_FUNCTION(MacInit); + SKF_METHOD_BIND_FUNCTION(Mac); + SKF_METHOD_BIND_FUNCTION(MacUpdate); + SKF_METHOD_BIND_FUNCTION(MacFinal); + SKF_METHOD_BIND_FUNCTION(CloseHandle); +#ifdef SKF_HAS_ECCDECRYPT + SKF_METHOD_BIND_FUNCTION(ECCDecrypt); +#endif + + ret = skf; + skf = NULL; + +end: + SKF_METHOD_free(skf); + return ret; +} + +void SKF_METHOD_free(SKF_METHOD *meth) +{ + if (meth) + DSO_free(meth->dso); + OPENSSL_free(meth); +} diff --git a/skf/skf_prn.c b/skf/skf_prn.c new file mode 100644 index 00000000..f61bafa5 --- /dev/null +++ b/skf/skf_prn.c @@ -0,0 +1,373 @@ +/* ==================================================================== + * Copyright (c) 2014 - 2019 The GmSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the GmSSL Project. + * (http://gmssl.org/)" + * + * 4. The name "GmSSL Project" must not be used to endorse or promote + * products derived from this software without prior written + * permission. For written permission, please contact + * guanzhi1980@gmail.com. + * + * 5. Products derived from this software may not be called "GmSSL" + * nor may "GmSSL" appear in their names without prior written + * permission of the GmSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the GmSSL Project + * (http://gmssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ + +#include +#include +#include +#include +#include +#include +#include "internal/skf_int.h" +#include "../../e_os.h" + + +static char *skf_algor_name(ULONG ulAlgID) +{ + switch (ulAlgID) { + case SGD_SM1_ECB: return "sm1-ecb"; + case SGD_SM1_CBC: return "sm1-cbc"; + case SGD_SM1_CFB: return "sm1-cfb"; + case SGD_SM1_OFB: return "sm1-ofb128"; + case SGD_SM1_MAC: return "sm1-mac"; + case SGD_SM4_ECB: return "sms4-ecb"; + case SGD_SM4_CBC: return "sms4-cbc"; + case SGD_SM4_CFB: return "sms4-cfb"; + case SGD_SM4_OFB: return "sms4-ofb128"; + case SGD_SM4_MAC: return "sms4-mac"; + case SGD_SSF33_ECB: return "ssf33-ecb"; + case SGD_SSF33_CBC: return "ssf33-cbc"; + case SGD_SSF33_CFB: return "ssf33-cfb"; + case SGD_SSF33_OFB: return "ssf33-ofb128"; + case SGD_SSF33_MAC: return "ssf33-mac"; + case SGD_RSA: return "rsa"; + case SGD_SM2_1: return "sm2sign"; + case SGD_SM2_2: return "sm2encrypt"; + case SGD_SM2_3: return "sm2keyagreement"; + case SGD_SM3: return "sm3"; + case SGD_SHA1: return "sha1"; + case SGD_SHA256: return "sha256"; + } + return NULL; +} + +ULONG SKF_GetDevStateName(ULONG ulDevState, LPSTR *szDevStateName) +{ + if (!szDevStateName) { + return SAR_INDATALENERR; + } + + switch (ulDevState) { + case SKF_DEV_STATE_ABSENT: + *szDevStateName = (LPSTR)"Absent"; + break; + case SKF_DEV_STATE_PRESENT: + *szDevStateName = (LPSTR)"Present"; + break; + case SKF_DEV_STATE_UNKNOW: + *szDevStateName = (LPSTR)"Unknown"; + break; + default: + *szDevStateName = (LPSTR)"(Error)"; + return SAR_INDATALENERR; + } + + return SAR_OK; +} + +ULONG SKF_GetContainerTypeName(ULONG ulContainerType, LPSTR *szName) +{ + switch (ulContainerType) { + case SKF_CONTAINER_TYPE_UNDEF: + *szName = (LPSTR)"(undef)"; + break; + case SKF_CONTAINER_TYPE_RSA: + *szName = (LPSTR)"RSA"; + break; + case SKF_CONTAINER_TYPE_ECC: + *szName = (LPSTR)"EC"; + break; + default: + *szName = (LPSTR)"(unknown)"; + } + /* always success for help functions */ + return SAR_OK; +} + +typedef struct { + ULONG id; + char *name; +} table_item_t; + +static table_item_t skf_cipher_caps[] = { + { SGD_SM1_ECB, "sm1-ecb" }, + { SGD_SM1_CBC, "sm1-cbc" }, + { SGD_SM1_CFB, "sm1-cfb" }, + { SGD_SM1_OFB, "sm1-ofb128" }, + { SGD_SM1_MAC, "cbcmac-sm1" }, + { SGD_SSF33_ECB, "ssf33-ecb" }, + { SGD_SSF33_CBC, "ssf33-cbc" }, + { SGD_SSF33_CFB, "ssf33-cfb" }, + { SGD_SSF33_OFB, "ssf33-ofb128" }, + { SGD_SSF33_MAC, "cbcmac-ssf33" }, + { SGD_SM4_ECB, "sms4-ecb" }, + { SGD_SM4_CBC, "sms4-cbc" }, + { SGD_SM4_CFB, "sms4-cfb" }, + { SGD_SM4_OFB, "sms4-ofb128" }, + { SGD_SM4_MAC, "cbcmac-sms4" }, + { SGD_ZUC_EEA3, "zuc_128eea3" }, + { SGD_ZUC_EIA3, "zuc_128eia3" } +}; + +static table_item_t skf_digest_caps[] = { + { SGD_SM3, "sm3" }, + { SGD_SHA1, "sha1" }, + { SGD_SHA256, "sha256" }, +}; + +static table_item_t skf_pkey_caps[] = { + { SGD_RSA_SIGN, "rsa" }, + { SGD_RSA_ENC, "rsaEncryption" }, + { SGD_SM2_1, "sm2sign" }, + { SGD_SM2_2, "sm2exchange" }, + { SGD_SM2_3, "sm2encrypt" } +}; + +ULONG SKF_PrintDevInfo(BIO *out, DEVINFO *devInfo) +{ + size_t i, n; + char *serial = OPENSSL_buf2hexstr(devInfo->SerialNumber, strlen((char *)devInfo->SerialNumber)); + + BIO_printf(out, " %-16s : %d.%d\n", "Version", devInfo->Version.major, devInfo->Version.minor); + BIO_printf(out, " %-16s : %s\n", "Manufacturer", devInfo->Manufacturer); + BIO_printf(out, " %-16s : %s\n", "Issuer", devInfo->Issuer); + BIO_printf(out, " %-16s : %s\n", "Label", devInfo->Label); + BIO_printf(out, " %-16s : %s\n", "Serial Number", serial); + BIO_printf(out, " %-16s : %d.%d\n", "Firmware Version", devInfo->HWVersion.major, devInfo->HWVersion.minor); + + BIO_printf(out, " %-16s : ", "Ciphers"); + for (i = n = 0; i < OSSL_NELEM(skf_cipher_caps); i++) { + if ((devInfo->AlgSymCap & skf_cipher_caps[i].id) == + skf_cipher_caps[i].id) { + BIO_printf(out, "%s%s", n ? "," : "", skf_cipher_caps[i].name); + n++; + } + } + BIO_puts(out, "\n"); + + BIO_printf(out, " %-16s : ", "Public Keys"); + for (i = n = 0; i < OSSL_NELEM(skf_pkey_caps); i++) { + if ((devInfo->AlgAsymCap & skf_pkey_caps[i].id) == + skf_pkey_caps[i].id) { + BIO_printf(out, "%s%s", n ? "," : "", skf_pkey_caps[i].name); + n++; + } + } + BIO_puts(out, "\n"); + + BIO_printf(out, " %-16s : ", "Digests"); + for (i = n = 0; i < OSSL_NELEM(skf_digest_caps); i++) { + if ((devInfo->AlgHashCap & skf_digest_caps[i].id) == + skf_digest_caps[i].id) { + BIO_printf(out, "%s%s", n ? "," : "", skf_digest_caps[i].name); + n++; + } + } + BIO_puts(out, "\n"); + + BIO_printf(out, " %-16s : ", "Auth Cipher"); + for (i = 0; i < OSSL_NELEM(skf_cipher_caps); i++) { + if (devInfo->DevAuthAlgId == skf_cipher_caps[i].id) { + BIO_printf(out, "%s\n", skf_cipher_caps[i].name); + break; + } + } + if (i == OSSL_NELEM(skf_cipher_caps)) { + BIO_puts(out, "(unknown)\n"); + } + + if (devInfo->TotalSpace == UINT_MAX) + BIO_printf(out, " %-16s : %s\n", "Total Sapce", "(unlimited)"); + else BIO_printf(out, " %-16s : %u\n", "Total Sapce", devInfo->TotalSpace); + + if (devInfo->FreeSpace == UINT_MAX) + BIO_printf(out, " %-16s : %s\n", "Free Space", "(unlimited)"); + else BIO_printf(out, " %-16s : %u\n", "Free Space", devInfo->FreeSpace); + + if (devInfo->MaxECCBufferSize == UINT_MAX) + BIO_printf(out, " %-16s : %s\n", "MAX ECC Input", "(unlimited)"); + else BIO_printf(out, " %-16s : %u\n", "MAX ECC Input", devInfo->MaxECCBufferSize); + + if (devInfo->MaxBufferSize == UINT_MAX) + BIO_printf(out, " %-16s : %s\n", "MAX Cipher Input", "(unlimited)"); + else BIO_printf(out, " %-16s : %u\n", "MAX Cipher Input", devInfo->MaxBufferSize); + + OPENSSL_free(serial); + return SAR_OK; +} + +ULONG SKF_PrintRSAPublicKey(BIO *out, RSAPUBLICKEYBLOB *blob) +{ + BIO_printf(out, "AlgID : %s\n", skf_algor_name(blob->AlgID)); + BIO_printf(out, "BitLen : %u\n", blob->BitLen); + BIO_puts(out, "Modulus:\n"); + BIO_puts(out, " "); + BIO_hex_string(out, 4, 16, blob->Modulus, MAX_RSA_MODULUS_LEN); + BIO_puts(out, "\n"); + BIO_puts(out, "PublicExponent:\n"); + BIO_puts(out, " "); + BIO_hex_string(out, 4, 16, blob->PublicExponent, MAX_RSA_EXPONENT_LEN); + BIO_puts(out, "\n"); + return SAR_OK; +} + +ULONG SKF_PrintRSAPrivateKey(BIO *out, RSAPRIVATEKEYBLOB *blob) +{ + BIO_printf(out, "AlgID : %s\n", skf_algor_name(blob->AlgID)); + BIO_printf(out, "BitLen : %u\n", blob->BitLen); + BIO_puts(out, "Modulus:\n"); + BIO_puts(out, " "); + BIO_hex_string(out, 4, 16, blob->Modulus, MAX_RSA_MODULUS_LEN); + BIO_puts(out, "\n"); + BIO_puts(out, "PublicExponent:\n"); + BIO_puts(out, " "); + BIO_hex_string(out, 4, 16, blob->PublicExponent, MAX_RSA_EXPONENT_LEN); + BIO_puts(out, "\n"); + BIO_puts(out, "PrivateExponent:\n"); + BIO_puts(out, " "); + BIO_hex_string(out, 4, 16, blob->PrivateExponent, MAX_RSA_MODULUS_LEN); + BIO_puts(out, "\n"); + BIO_puts(out, "Prime1:\n"); + BIO_puts(out, " "); + BIO_hex_string(out, 4, 16, blob->Prime1, MAX_RSA_MODULUS_LEN/2); + BIO_puts(out, "\n"); + BIO_puts(out, "Prime2:\n"); + BIO_puts(out, " "); + BIO_hex_string(out, 4, 16, blob->Prime2, MAX_RSA_MODULUS_LEN/2); + BIO_puts(out, "\n"); + BIO_puts(out, "Prime1Exponent:\n"); + BIO_hex_string(out, 4, 16, blob->Prime1Exponent, MAX_RSA_MODULUS_LEN/2); + BIO_puts(out, "\n"); + BIO_puts(out, " "); + BIO_puts(out, "Prime2Exponent:\n"); + BIO_puts(out, " "); + BIO_hex_string(out, 4, 16, blob->Prime2Exponent, MAX_RSA_MODULUS_LEN/2); + BIO_puts(out, "\n"); + BIO_puts(out, "Coefficient:\n"); + BIO_puts(out, " "); + BIO_hex_string(out, 4, 16, blob->Coefficient, MAX_RSA_MODULUS_LEN/2); + BIO_puts(out, "\n"); + return SAR_OK; +} + +ULONG SKF_PrintECCPublicKey(BIO *out, ECCPUBLICKEYBLOB *blob) +{ + BIO_printf(out, "BitLen : %u\n", blob->BitLen); + BIO_puts(out, "XCoordinate:\n"); + BIO_puts(out, " "); + BIO_hex_string(out, 4, 16, blob->XCoordinate, ECC_MAX_XCOORDINATE_BITS_LEN/8); + BIO_puts(out, "\n"); + BIO_puts(out, "YCoordinate:\n"); + BIO_puts(out, " "); + BIO_hex_string(out, 4, 16, blob->YCoordinate, ECC_MAX_XCOORDINATE_BITS_LEN/8); + BIO_puts(out, "\n"); + return SAR_OK; +} + +ULONG SKF_PrintECCPrivateKey(BIO *out, ECCPRIVATEKEYBLOB *blob) +{ + BIO_printf(out, "BitLen : %u\n", blob->BitLen); + BIO_puts(out, "PrivateKey:\n"); + BIO_puts(out, " "); + BIO_hex_string(out, 4, 16, blob->PrivateKey, ECC_MAX_MODULUS_BITS_LEN/8); + BIO_puts(out, "\n"); + return SAR_OK; +} + +ULONG SKF_PrintECCCipher(BIO *out, ECCCIPHERBLOB *blob) +{ + BIO_puts(out, "XCoordinate:\n"); + BIO_puts(out, " "); + BIO_hex_string(out, 4, 16, blob->XCoordinate, ECC_MAX_XCOORDINATE_BITS_LEN/8); + BIO_puts(out, "\n"); + BIO_puts(out, "YCoordinate:\n"); + BIO_puts(out, " "); + BIO_hex_string(out, 4, 16, blob->YCoordinate, ECC_MAX_XCOORDINATE_BITS_LEN/8); + BIO_puts(out, "\n"); + BIO_puts(out, "HASH:\n"); + BIO_puts(out, " "); + BIO_hex_string(out, 4, 16, blob->HASH, 32); + BIO_puts(out, "\n"); + BIO_printf(out, "CipherLen: %u\n", blob->CipherLen); + BIO_puts(out, "Cipher:\n"); + BIO_puts(out, " "); + BIO_hex_string(out, 4, 16, blob->Cipher, blob->CipherLen); + BIO_puts(out, "\n"); + return SAR_OK; +} + +ULONG SKF_PrintECCSignature(BIO *out, ECCSIGNATUREBLOB *blob) +{ + BIO_puts(out, "r:\n"); + BIO_puts(out, " "); + BIO_hex_string(out, 4, 16, blob->r, ECC_MAX_XCOORDINATE_BITS_LEN/8); + BIO_puts(out, "\n"); + BIO_puts(out, "s:\n"); + BIO_puts(out, " "); + BIO_hex_string(out, 4, 16, blob->s, ECC_MAX_XCOORDINATE_BITS_LEN/8); + BIO_puts(out, "\n"); + return SAR_OK; +} + +ULONG DEVAPI SKF_GetAlgorName(ULONG ulAlgID, LPSTR *szName) +{ + char *name; + if ((name = skf_algor_name(ulAlgID)) != NULL) { + *szName = (LPSTR)&name; + return SAR_OK; + } + return SAR_FAIL; +} + +ULONG DEVAPI SKF_PrintErrorString(BIO *out, ULONG ulError) +{ + LPSTR str = NULL; + SKF_GetErrorString(ulError, &str); + BIO_printf(out, "SKF Error: %s\n", (char *)str); + return SAR_OK; +} diff --git a/skf/skf_wisec.c b/skf/skf_wisec.c new file mode 100644 index 00000000..8796c3d6 --- /dev/null +++ b/skf/skf_wisec.c @@ -0,0 +1,200 @@ +/* ==================================================================== + * Copyright (c) 2016 - 2017 The GmSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the GmSSL Project. + * (http://gmssl.org/)" + * + * 4. The name "GmSSL Project" must not be used to endorse or promote + * products derived from this software without prior written + * permission. For written permission, please contact + * guanzhi1980@gmail.com. + * + * 5. Products derived from this software may not be called "GmSSL" + * nor may "GmSSL" appear in their names without prior written + * permission of the GmSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the GmSSL Project + * (http://gmssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ + +#include +#include +#include "internal/skf_int.h" +#include "../../e_os.h" +#include "skf_wisec.h" + +typedef struct { + ULONG std_id; + ULONG vendor_id; +} SKF_ALGOR_PAIR; + +static SKF_ALGOR_PAIR wisec_ciphers[] = { + { SGD_SM1, WISEC_SM1 }, + { SGD_SM1_ECB, WISEC_SM1_ECB }, + { SGD_SM1_CBC, WISEC_SM1_CBC }, + { SGD_SM1_CFB, WISEC_SM1_CFB }, + { SGD_SM1_OFB, WISEC_SM1_OFB }, + { SGD_SM1_MAC, WISEC_SM1_MAC }, + { SGD_SM4, WISEC_SM4 }, + { SGD_SM4_ECB, WISEC_SM4_ECB }, + { SGD_SM4_CBC, WISEC_SM4_CBC }, + { SGD_SM4_CFB, WISEC_SM4_CFB }, + { SGD_SM4_OFB, WISEC_SM4_OFB }, + { SGD_SM4_MAC, WISEC_SM4_MAC }, + { SGD_SSF33, WISEC_SSF33 }, + { SGD_SSF33_ECB, WISEC_SSF33_ECB }, + { SGD_SSF33_CBC, WISEC_SSF33_CBC }, + { SGD_SSF33_CFB, WISEC_SSF33_CFB }, + { SGD_SSF33_OFB, WISEC_SSF33_OFB }, + { SGD_SSF33_MAC, WISEC_SSF33_MAC }, +}; + +static ULONG wisec_get_cipher_algor(ULONG vendor_id) +{ + size_t i; + for (i = 0; i < OSSL_NELEM(wisec_ciphers); i++) { + if (vendor_id == wisec_ciphers[i].vendor_id) { + return wisec_ciphers[i].std_id; + } + } + return 0; +} + +static ULONG wisec_get_cipher_cap(ULONG vendor_cap) +{ + ULONG std_cap = 0; + size_t i; + for (i = 0; i < OSSL_NELEM(wisec_ciphers); i++) { + if (vendor_cap & wisec_ciphers[i].vendor_id) { + std_cap |= wisec_ciphers[i].std_id; + } + } + return std_cap; +} + +static SKF_ALGOR_PAIR wisec_digests[] = { + { SGD_SM3, WISEC_SM3 }, + { SGD_SHA1, WISEC_SHA1 }, + { SGD_SHA256, WISEC_SHA256 }, +}; + +static ULONG wisec_get_digest_algor(ULONG vendor_id) +{ + size_t i; + for (i = 0; i < OSSL_NELEM(wisec_digests); i++) { + if (vendor_id == wisec_digests[i].vendor_id) { + return wisec_digests[i].std_id; + } + } + return 0; +} + +static ULONG wisec_get_digest_cap(ULONG vendor_cap) +{ + ULONG std_cap = 0; + size_t i; + for (i = 0; i < OSSL_NELEM(wisec_digests); i++) { + if (vendor_cap & wisec_digests[i].vendor_id) { + std_cap |= wisec_digests[i].std_id; + } + } + return std_cap; +} + +static SKF_ALGOR_PAIR wisec_pkeys[] = { + { SGD_RSA, WISEC_RSA }, + { SGD_RSA_SIGN, WISEC_RSA_SIGN }, + { SGD_RSA_ENC, WISEC_RSA_ENC }, + { SGD_SM2, WISEC_SM2 }, + { SGD_SM2_1, WISEC_SM2_1 }, + { SGD_SM2_2, WISEC_SM2_2 }, + { SGD_SM2_3, WISEC_SM2_3 }, +}; + +static ULONG wisec_get_pkey_algor(ULONG vendor_id) +{ + size_t i; + for (i = 0; i < OSSL_NELEM(wisec_pkeys); i++) { + if (vendor_id == wisec_pkeys[i].vendor_id) { + return wisec_pkeys[i].std_id; + } + } + return 0; +} + +static ULONG wisec_get_pkey_cap(ULONG vendor_cap) +{ + ULONG std_cap = 0; + size_t i; + for (i = 0; i < OSSL_NELEM(wisec_pkeys); i++) { + if (vendor_cap & wisec_pkeys[i].vendor_id) { + std_cap |= wisec_pkeys[i].std_id; + } + } + return std_cap; +} + +static SKF_ERR_REASON wisec_errors[] = { + { WISEC_AUTH_BLOCKED, SKF_R_WISEC_AUTH_BLOCKED }, + { WISEC_CERTNOUSAGEERR, SKF_R_WISEC_CERTNOUSAGEERR }, + { WISEC_INVALIDCONTAINERERR, SKF_R_WISEC_INVALIDCONTAINERERR }, + { WISEC_CONTAINER_NOT_EXISTS, SKF_R_WISEC_CONTAINER_NOT_EXISTS }, + { WISEC_CONTAINER_EXISTS, SKF_R_WISEC_CONTAINER_EXISTS }, + { WISEC_CERTUSAGEERR, SKF_R_WISEC_CERTUSAGEERR }, + { WISEC_KEYNOUSAGEERR, SKF_R_WISEC_KEYNOUSAGEERR }, + { WISEC_FILEATTRIBUTEERR, SKF_R_WISEC_FILEATTRIBUTEERR }, + { WISEC_DEVNOAUTH, SKF_R_WISEC_DEVNOAUTH }, +}; + +static unsigned long wisec_get_error_reason(ULONG err) +{ + size_t i = 0; + for (i = 0; i < OSSL_NELEM(wisec_errors); i++) { + if (err == wisec_errors[i].err) { + return wisec_errors[i].reason; + } + } + return 0; +} + +SKF_VENDOR skf_wisec = { + "wisec", + 16, + wisec_get_cipher_algor, + wisec_get_cipher_cap, + wisec_get_digest_algor, + wisec_get_digest_cap, + wisec_get_pkey_algor, + wisec_get_pkey_cap, + wisec_get_error_reason, +}; diff --git a/skf/skf_wisec.h b/skf/skf_wisec.h new file mode 100644 index 00000000..ddbcae61 --- /dev/null +++ b/skf/skf_wisec.h @@ -0,0 +1,157 @@ +/* ==================================================================== + * Copyright (c) 2016 - 2017 The GmSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the GmSSL Project. + * (http://gmssl.org/)" + * + * 4. The name "GmSSL Project" must not be used to endorse or promote + * products derived from this software without prior written + * permission. For written permission, please contact + * guanzhi1980@gmail.com. + * + * 5. Products derived from this software may not be called "GmSSL" + * nor may "GmSSL" appear in their names without prior written + * permission of the GmSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the GmSSL Project + * (http://gmssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE GmSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE GmSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ + +#ifndef HEADER_SKF_WISEC_H +#define HEADER_SKF_WISEC_H + +#include +#include + + +#define WISEC_SM1 (SGD_SM1) +#define WISEC_SM1_ECB (SGD_SM1_ECB) +#define WISEC_SM1_CBC (SGD_SM1_CBC) +#define WISEC_SM1_CFB (SGD_SM1_CFB) +#define WISEC_SM1_OFB (SGD_SM1_OFB) +#define WISEC_SM1_MAC (SGD_SM1_MAC) + +#define WISEC_SSF33 (SGD_SSF33) +#define WISEC_SSF33_ECB (SGD_SSF33_ECB) +#define WISEC_SSF33_CBC (SGD_SSF33_CBC) +#define WISEC_SSF33_CFB (SGD_SSF33_CFB) +#define WISEC_SSF33_OFB (SGD_SSF33_OFB) +#define WISEC_SSF33_MAC (SGD_SSF33_MAC) + +#define WISEC_SM4 (SGD_SM4) +#define WISEC_SM4_ECB (WISEC_SM4|SGD_ECB) +#define WISEC_SM4_CBC (WISEC_SM4|SGD_CBC) +#define WISEC_SM4_CFB (WISEC_SM4|SGD_CFB) +#define WISEC_SM4_OFB (WISEC_SM4|SGD_OFB) +#define WISEC_SM4_MAC (WISEC_SM4|SGD_MAC) + +#define WISEC_AES 0x00000800 +#define WISEC_128 0x00000000 +#define WISEC_192 0x00000010 +#define WISEC_256 0x00000020 +#define WISEC_AES128 (WISEC_AES|WISEC_128) +#define WISEC_AES192 (WISEC_AES|WISEC_192) +#define WISEC_AES256 (WISEC_AES|WISEC_256) +#define WISEC_AES128_ECB (WISEC_AES128|SGD_ECB) +#define WISEC_AES128_CBC (WISEC_AES128|SGD_CBC) +#define WISEC_AES128_CFB (WISEC_AES128|SGD_CFB) +#define WISEC_AES128_OFB (WISEC_AES128|SGD_OFB) +#define WISEC_AES128_MAC (WISEC_AES128|SGD_MAC) +#define WISEC_AES192_ECB (WISEC_AES192|SGD_ECB) +#define WISEC_AES192_CBC (WISEC_AES192|SGD_CBC) +#define WISEC_AES192_CFB (WISEC_AES192|SGD_CFB) +#define WISEC_AES192_OFB (WISEC_AES192|SGD_OFB) +#define WISEC_AES192_MAC (WISEC_AES192|SGD_MAC) +#define WISEC_AES256_ECB (WISEC_AES256|SGD_ECB) +#define WISEC_AES256_CBC (WISEC_AES256|SGD_CBC) +#define WISEC_AES256_CFB (WISEC_AES256|SGD_CFB) +#define WISEC_AES256_OFB (WISEC_AES256|SGD_OFB) +#define WISEC_AES256_MAC (WISEC_AES256|SGD_MAC) + +#define WISEC_DES 0x00001000 +#define WISEC_DES_ECB (WISEC_DES|SGD_ECB) +#define WISEC_DES_CBC (WISEC_DES|SGD_CBC) +#define WISEC_DES_CFB (WISEC_DES|SGD_CFB) +#define WISEC_DES_OFB (WISEC_DES|SGD_OFB) +#define WISEC_DES_MAC (WISEC_DES|SGD_MAC) + +#define WISEC_D3DES 0x00001010 +#define WISEC_D3DES_ECB (WISEC_D3DES|SGD_ECB) +#define WISEC_D3DES_CBC (WISEC_D3DES|SGD_CBC) +#define WISEC_D3DES_CFB (WISEC_D3DES|SGD_CFB) +#define WISEC_D3DES_OFB (WISEC_D3DES|SGD_OFB) +#define WISEC_D3DES_MAC (WISEC_D3DES|SGD_MAC) + +#define WISEC_T3DES 0x00001020 +#define WISEC_T3DES_ECB (WISEC_T3DES|SGD_ECB) +#define WISEC_T3DES_CBC (WISEC_T3DES|SGD_CBC) +#define WISEC_T3DES_CFB (WISEC_T3DES|SGD_CFB) +#define WISEC_T3DES_OFB (WISEC_T3DES|SGD_OFB) +#define WISEC_T3DES_MAC (WISEC_T3DES|SGD_MAC) + +#define WISEC_SM3 (SGD_SM3) +#define WISEC_SHA1 (SGD_SHA1) +#define WISEC_SHA256 (SGD_SHA256) + +#define WISEC_RSA (SGD_RSA) +#define WISEC_RSA_SIGN (SGD_RSA_SIGN) +#define WISEC_RSA_ENC (SGD_RSA_ENC) +#define WISEC_SM2 (SGD_SM2) +#define WISEC_SM2_1 (SGD_SM2_1) +#define WISEC_SM2_2 (SGD_SM2_2) +#define WISEC_SM2_3 (SGD_SM2_3) + + +#define WISEC_AUTH_BLOCKED 0x0A000033 +#define WISEC_CERTNOUSAGEERR 0x0A000034 +#define WISEC_INVALIDCONTAINERERR 0x0A000035 +#define WISEC_CONTAINER_NOT_EXISTS 0x0A000036 +#define WISEC_CONTAINER_EXISTS 0x0A000037 +#define WISEC_CERTUSAGEERR 0x0A000038 +#define WISEC_KEYNOUSAGEERR 0x0A000039 +#define WISEC_FILEATTRIBUTEERR 0x0A00003A +#define WISEC_DEVNOAUTH 0x0A00003B + +/* +ULONG DEVAPI SKFE_SetSN(DEVHANDLE hDev, CHAR *SN, UINT SNLen); +ULONG DEVAPI SKFE_GenExtECCKey(DEVHANDLE hDev, PECCPRIVATEKEYBLOB pPriBlob, PECCPUBLICKEYBLOB pPubBlob); +ULONG DEVAPI SKF_ECCDecrypt(HCONTAINER hContainer, PECCCIPHERBLOB pCipherText, BYTE *pbPlainText,ULONG *pulPlainTextLen); +ULONG DEVAPI SKF_GenerateKey(HCONTAINER hContainer, ULONG ulAlgId, HANDLE *phSessionKey) ; +ULONG DEVAPI SKF_ECCExportSessionKeyByHandle(HANDLE phSessionKey, ECCPUBLICKEYBLOB *pPubKey,PECCCIPHERBLOB pData); +ULONG DEVAPI SKF_RSAExportSessionKeyByHandle(HANDLE phSessionKey, RSAPUBLICKEYBLOB*pPubKey,BYTE *pbData, ULONG *pulDataLen); +ULONG DEVAPI SKF_PrvKeyDecrypt(HCONTAINER hContainer, PECCCIPHERBLOB pCipherText, BYTE *pbData, ULONG *pbDataLen); +ULONG DEVAPI SKF_PrvKeyDecrypt(HCONTAINER hContainer, ULONG ulType, PECCCIPHERBLOB pCipherText, BYTE *pbData, ULONG *pbDataLen); +ULONG DEVAPI SKF_RSAPrvKeyDecrypt(HCONTAINER hContainer, BYTE *pCipherData, ULONG pCipherDataLen, BYTE *pbData, ULONG *pbDataLen); +*/ + +#endif diff --git a/tools/skfutil.c b/skf/skfutil.c similarity index 100% rename from tools/skfutil.c rename to skf/skfutil.c diff --git a/src/aes.c b/src/aes.c index 42a63c35..1611f42a 100644 --- a/src/aes.c +++ b/src/aes.c @@ -114,7 +114,7 @@ static uint32_t rot_word(uint32_t A) #ifdef CRYPTO_INFO static void print_rk(const AES_KEY *aes_key) { - int i; + size_t i; for (i = 0; i <= aes_key->rounds; i++) { printf("%08x ", aes_key->rk[4 * i]); printf("%08x ", aes_key->rk[4 * i + 1]); @@ -134,7 +134,7 @@ int aes_set_encrypt_key(AES_KEY *aes_key, const uint8_t *key, size_t keylen) */ uint32_t *W = (uint32_t *)aes_key->rk; size_t Nk = keylen/sizeof(uint32_t); - int i; + size_t i; switch (keylen) { case AES128_KEY_SIZE: @@ -177,7 +177,7 @@ int aes_set_decrypt_key(AES_KEY *aes_key, const uint8_t *key, size_t keylen) { int ret = 0; AES_KEY enc_key; - int i; + size_t i; if (!aes_set_encrypt_key(&enc_key, key, keylen)) { goto end; @@ -402,7 +402,7 @@ static void print_state(const uint8_t S[4][4]) void aes_encrypt(const AES_KEY *key, const uint8_t in[16], uint8_t out[16]) { uint8_t state[4][4]; - int i; + size_t i; /* fill state columns */ for (i = 0; i < 4; i++) { @@ -442,7 +442,7 @@ void aes_encrypt(const AES_KEY *key, const uint8_t in[16], uint8_t out[16]) void aes_decrypt(const AES_KEY *aes_key, const uint8_t in[16], uint8_t out[16]) { uint8_t state[4][4]; - int i; + size_t i; /* fill state columns */ for (i = 0; i < 4; i++) { diff --git a/src/aes_modes.c b/src/aes_modes.c index 169efc15..ca132573 100644 --- a/src/aes_modes.c +++ b/src/aes_modes.c @@ -86,7 +86,7 @@ int aes_cbc_padding_encrypt(const AES_KEY *key, const uint8_t iv[16], { uint8_t block[16]; size_t rem = inlen % 16; - int padding = 16 - rem; + int padding = 16 - inlen % 16; if (in) { memcpy(block, in + inlen - rem, rem); @@ -107,14 +107,15 @@ int aes_cbc_padding_decrypt(const AES_KEY *key, const uint8_t iv[16], uint8_t *out, size_t *outlen) { uint8_t block[16]; + size_t len = sizeof(block); int padding; if (inlen == 0) { - error_print("warning: input lenght = 0"); + error_print(); return 0; } if (inlen%16 != 0 || inlen < 16) { - error_print("invalid cbc ciphertext length"); + error_print(); return -1; } if (inlen > 16) { @@ -127,7 +128,8 @@ int aes_cbc_padding_decrypt(const AES_KEY *key, const uint8_t iv[16], error_print(); return -1; } - memcpy(out + inlen - 16, block, 16 - padding); + len -= padding; + memcpy(out + inlen - 16, block, len); *outlen = inlen - padding; return 1; } diff --git a/src/asn1.c b/src/asn1.c index a347c2ff..6941eb3e 100644 --- a/src/asn1.c +++ b/src/asn1.c @@ -89,7 +89,7 @@ static char *asn1_tag_index[] = { const char *asn1_tag_name(int tag) { if (tag < 0 || tag > 0xff) { - error_print("invalid tag value\n"); + error_print(); return NULL; } @@ -127,7 +127,7 @@ const char *asn1_tag_name(int tag) case ASN1_TAG_SET: return "SET"; } - error_print("unknown universal tag %d\n", tag); + error_print(); return NULL; } @@ -252,7 +252,7 @@ int asn1_length_from_der(size_t *plen, const uint8_t **pin, size_t *pinlen) } if (inlen < len) { - error_print("inlen (%zu) < length(%zu)", inlen, len); + error_print(); return -1; } @@ -573,6 +573,7 @@ int asn1_utc_time_to_der_ex(int tag, time_t a, uint8_t **out, size_t *outlen) return -1; } + // 注意,这个函数可能在Windows上是没有的! gmtime_r(&a, &tm_val); strftime(buf, sizeof(buf), "%y%m%d%H%M%SZ", &tm_val); @@ -886,6 +887,21 @@ int asn1_ia5_string_from_der_ex(int tag, const char **a, size_t *alen, const uin return asn1_type_from_der(tag, (const uint8_t **)a, alen, in, inlen); } +/* +int hh, mm, ss; +struct tm when = {0}; + +sscanf_s(date, "%d:%d:%d", &hh, &mm, &ss); + + +when.tm_hour = hh; +when.tm_min = mm; +when.tm_sec = ss; + +time_t converted; +converted = mktime(&when); +*/ + int asn1_utc_time_from_der_ex(int tag, time_t *t, const uint8_t **pin, size_t *pinlen) { const uint8_t *in = *pin; @@ -920,13 +936,14 @@ int asn1_utc_time_from_der_ex(int tag, time_t *t, const uint8_t **pin, size_t *p buf[1] = '0'; } if (len == sizeof("YYMMDDHHMMSSZ")-1) { - if (!strptime(buf, "%Y%m%d%H%M%SZ", &tm_val)) { + // 这里应该自己写一个函数来解析 + if (!strptime(buf, "%Y%m%d%H%M%SZ", &tm_val)) { // 注意:这个函数在Windows上没有!! return -1; } } else { return -1; } - *t = timegm(&tm_val); + *t = timegm(&tm_val); // FIXME: Windows ! *pin = in + len; *pinlen = inlen - len; diff --git a/src/digest.c b/src/digest.c index 4ac728af..a4c9004f 100644 --- a/src/digest.c +++ b/src/digest.c @@ -283,7 +283,7 @@ static int sha1_digest_finish(DIGEST_CTX *ctx, unsigned char *dgst) static const DIGEST sha1_digest_object = { OID_sha1, - SHA1_DIGEST_LENGTH, + SHA1_DIGEST_SIZE, SHA1_BLOCK_SIZE, sizeof(SHA1_CTX), sha1_digest_init, diff --git a/src/endian.h b/src/endian.h index 1fb67c2d..506003f1 100644 --- a/src/endian.h +++ b/src/endian.h @@ -85,14 +85,14 @@ (p)[3] = (uint8_t)(V)) #define PUTU64(p,V) \ - ((p)[0] = (uint64_t)((V) >> 56), \ - (p)[1] = (uint64_t)((V) >> 48), \ - (p)[2] = (uint64_t)((V) >> 40), \ - (p)[3] = (uint64_t)((V) >> 32), \ - (p)[4] = (uint64_t)((V) >> 24), \ - (p)[5] = (uint64_t)((V) >> 16), \ - (p)[6] = (uint64_t)((V) >> 8), \ - (p)[7] = (uint64_t)(V)) + ((p)[0] = (uint8_t)((V) >> 56), \ + (p)[1] = (uint8_t)((V) >> 48), \ + (p)[2] = (uint8_t)((V) >> 40), \ + (p)[3] = (uint8_t)((V) >> 32), \ + (p)[4] = (uint8_t)((V) >> 24), \ + (p)[5] = (uint8_t)((V) >> 16), \ + (p)[6] = (uint8_t)((V) >> 8), \ + (p)[7] = (uint8_t)(V)) /* Little Endian R/W */ diff --git a/src/gf128.c b/src/gf128.c index 714dde9f..ee7e3ac9 100644 --- a/src/gf128.c +++ b/src/gf128.c @@ -81,11 +81,12 @@ int gf128_equ_hex(gf128_t a, const char *s) return memcmp(bin1, bin2, sizeof(bin1)) == 0; } +// FIXME: 这个函数不支持struct void gf128_print_bits(gf128_t a) { int i; for (i = 0; i < 128; i++) { - printf("%d", (int)(a % 2)); + printf("%d", (int)(a % 2)); //FIXME a >>= 1; } printf("\n"); diff --git a/src/hash_drbg.c b/src/hash_drbg.c index e9947ee6..26977843 100644 --- a/src/hash_drbg.c +++ b/src/hash_drbg.c @@ -212,7 +212,8 @@ end: */ static void drbg_add(uint8_t *R, const uint8_t *A, size_t seedlen) { - int temp = 0, i; + int temp = 0; + size_t i; for (i = seedlen - 1; i >= 0; i--) { temp += R[i] + A[i]; R[i] = temp & 0xff; @@ -222,7 +223,8 @@ static void drbg_add(uint8_t *R, const uint8_t *A, size_t seedlen) static void drbg_add1(uint8_t *R, size_t seedlen) { - int temp = 1, i; + int temp = 1; + size_t i; for (i = seedlen - 1; i >= 0; i--) { temp += R[i]; R[i] = temp & 0xff; @@ -265,7 +267,7 @@ static int drbg_hashgen(HASH_DRBG *drbg, size_t outlen, uint8_t *out) ret = 1; end: - digest_ctx_cleanup(&ctx); + memset(&ctx, 0, sizeof(ctx)); memset(data, 0, sizeof(data)); return ret; } @@ -339,8 +341,3 @@ end: memset(dgst, 0, sizeof(dgst)); return ret; } - -void hash_drbg_cleanup(HASH_DRBG *drbg) -{ - //mem_cleanup(drbg, sizeof(HASH_DRBG)); -} diff --git a/src/hex.c b/src/hex.c index 26a03f09..5bcadb97 100644 --- a/src/hex.c +++ b/src/hex.c @@ -143,13 +143,13 @@ int hex2bin(const char *in, size_t inlen, uint8_t *out) { int c; if (inlen % 2) { - error_print("hex %s len = %zu\n", in, inlen); + error_print_msg("hex %s len = %zu\n", in, inlen); return -1; } while (inlen) { if ((c = hexchar2int(*in++)) < 0) { - error_print(); + error_print_msg("%d", 5); return -1; } *out = (uint8_t)c << 4; @@ -193,3 +193,14 @@ void gmssl_memxor(void *r, const void *a, const void *b, size_t len) pr[i] = pa[i] ^ pb[i]; } } + +int gmssl_memcmp(const void *s1, const void *s2, size_t n) +{ + return memcmp(s1, s2, n); +} + + + + + + diff --git a/src/md5.c b/src/md5.c index aea3619d..0f44fbf6 100755 --- a/src/md5.c +++ b/src/md5.c @@ -52,73 +52,6 @@ #include "endian.h" -static void md5_compress_blocks(uint32_t state[4], - const unsigned char *data, size_t blocks); - - -void md5_init(MD5_CTX *ctx) -{ - memset(ctx, 0, sizeof(*ctx)); - ctx->state[0] = 0x67452301; - ctx->state[1] = 0xefcdab89; - ctx->state[2] = 0x98badcfe; - ctx->state[3] = 0x10325476; -} - -void md5_update(MD5_CTX *ctx, const unsigned char *data, size_t datalen) -{ - size_t blocks; - - if (ctx->num) { - unsigned int left = MD5_BLOCK_SIZE - ctx->num; - if (datalen < left) { - memcpy(ctx->block + ctx->num, data, datalen); - ctx->num += datalen; - return; - } else { - memcpy(ctx->block + ctx->num, data, left); - md5_compress_blocks(ctx->state, ctx->block, 1); - ctx->nblocks++; - data += left; - datalen -= left; - } - } - - blocks = datalen / MD5_BLOCK_SIZE; - md5_compress_blocks(ctx->state, data, blocks); - ctx->nblocks += blocks; - data += MD5_BLOCK_SIZE * blocks; - datalen -= MD5_BLOCK_SIZE * blocks; - - ctx->num = datalen; - if (datalen) { - memcpy(ctx->block, data, datalen); - } -} - -void md5_finish(MD5_CTX *ctx, unsigned char *dgst) -{ - int i; - - ctx->block[ctx->num] = 0x80; - - if (ctx->num + 9 <= MD5_BLOCK_SIZE) { - memset(ctx->block + ctx->num + 1, 0, MD5_BLOCK_SIZE - ctx->num - 9); - } else { - memset(ctx->block + ctx->num + 1, 0, MD5_BLOCK_SIZE - ctx->num - 1); - md5_compress_blocks(ctx->state, ctx->block, 1); - memset(ctx->block, 0, MD5_BLOCK_SIZE - 8); - } - PUTU64_LE(ctx->block + 56, (ctx->nblocks << 9) + (ctx->num << 3)); - md5_compress_blocks(ctx->state, ctx->block, 1); - for (i = 0; i < 4; i++) { - //PUTU32_LE(dgst, ctx->state[i]); - *(uint32_t *)dgst = ctx->state[i]; - dgst += sizeof(uint32_t); - } -} - -//#define ROL32(X, n) (((X) << (n)) | ((X) >> (32-(n)))) #define F(B, C, D) (((B) & (C)) | ((~(B)) & (D))) #define G(B, C, D) (((B) & (D)) | ((C) & (~(D)))) #define H(B, C, D) ((B) ^ (C) ^ (D)) @@ -169,8 +102,7 @@ static void md5_compress_blocks(uint32_t state[4], D = state[3]; for (i = 0; i < 16; i++) { - //W[i] = GETU32_LE(data); - W[i] = *((uint32_t *)data); + W[i] = GETU32_LE(data); data += sizeof(uint32_t); } @@ -213,9 +145,68 @@ static void md5_compress_blocks(uint32_t state[4], } } -void md5_compress(uint32_t state[4], const unsigned char block[64]) +void md5_init(MD5_CTX *ctx) { - return md5_compress_blocks(state, block, 1); + memset(ctx, 0, sizeof(*ctx)); + ctx->state[0] = 0x67452301; + ctx->state[1] = 0xefcdab89; + ctx->state[2] = 0x98badcfe; + ctx->state[3] = 0x10325476; +} + +void md5_update(MD5_CTX *ctx, const unsigned char *data, size_t datalen) +{ + size_t blocks; + + ctx->num &= 0x3f; + if (ctx->num) { + size_t left = MD5_BLOCK_SIZE - ctx->num; + if (datalen < left) { + memcpy(ctx->block + ctx->num, data, datalen); + ctx->num += datalen; + return; + } else { + memcpy(ctx->block + ctx->num, data, left); + md5_compress_blocks(ctx->state, ctx->block, 1); + ctx->nblocks++; + data += left; + datalen -= left; + } + } + + blocks = datalen / MD5_BLOCK_SIZE; + md5_compress_blocks(ctx->state, data, blocks); + ctx->nblocks += blocks; + data += MD5_BLOCK_SIZE * blocks; + datalen -= MD5_BLOCK_SIZE * blocks; + + ctx->num = datalen; + if (datalen) { + memcpy(ctx->block, data, datalen); + } +} + +void md5_finish(MD5_CTX *ctx, unsigned char *dgst) +{ + int i; + + ctx->num &= 0x3f; + ctx->block[ctx->num] = 0x80; + + if (ctx->num <= MD5_BLOCK_SIZE - 9) { + memset(ctx->block + ctx->num + 1, 0, MD5_BLOCK_SIZE - ctx->num - 9); + } else { + memset(ctx->block + ctx->num + 1, 0, MD5_BLOCK_SIZE - ctx->num - 1); + md5_compress_blocks(ctx->state, ctx->block, 1); + memset(ctx->block, 0, MD5_BLOCK_SIZE - 8); + } + PUTU64_LE(ctx->block + 56, (ctx->nblocks << 9) + (ctx->num << 3)); + md5_compress_blocks(ctx->state, ctx->block, 1); + for (i = 0; i < 4; i++) { + PUTU32_LE(dgst, ctx->state[i]); + dgst += sizeof(uint32_t); + } + memset(ctx, 0, sizeof(*ctx)); } void md5_digest(const unsigned char *data, size_t datalen, diff --git a/src/mem.h b/src/mem.h index d459393d..c3b5cb61 100644 --- a/src/mem.h +++ b/src/mem.h @@ -54,5 +54,7 @@ void memxor(void *r, const void *a, size_t len); void gmssl_memxor(void *r, const void *a, const void *b, size_t len); +int gmssl_memcmp(const void *s1, const void *s2, size_t n); + #endif diff --git a/src/oid.c b/src/oid.c index 73a41c32..d9560e01 100644 --- a/src/oid.c +++ b/src/oid.c @@ -574,7 +574,6 @@ int asn1_x509_kp_oid_from_octets(const uint8_t *in, size_t inlen) int asn1_x509_kp_oid_from_name(const char *name) { int i; - assert(i >= 0 && i < sizeof(x509_kp_oids)/sizeof(x509_kp_oids[0])); for (i = 0; i < sizeof(x509_kp_oids)/sizeof(x509_kp_oids[0]); i++) { if (strcmp(name, x509_kp_oids[i].name) == 0) { return OID_kp_serverAuth + i; @@ -598,7 +597,7 @@ void asn1_oid_to_octets(int oid, uint8_t *out, size_t *outlen) } else if (oid <= OID_at_role) { asn1_x509_oid_to_octets(oid, out, outlen); } else { - error_print("unknown oid %d\n", oid); + error_print(); assert(0); } } @@ -639,7 +638,7 @@ int asn1_oid_from_octets(const uint8_t *in, size_t inlen) } if (ret < 0) { - error_print("invalid der\n"); + error_print(); } return ret; } @@ -907,7 +906,7 @@ int test_asn1_object_identifier_to_der(int oid) printf("\n"); if (roid != oid) { - error_print("oid = %d, parsed oid = %d\n", oid, roid); + error_print(); return -1; } if (len != 0) { diff --git a/src/pbkdf2.c b/src/pbkdf2.c index febd26e7..eeadf196 100644 --- a/src/pbkdf2.c +++ b/src/pbkdf2.c @@ -125,7 +125,7 @@ int pbkdf2_genkey(const DIGEST *digest, const char *pass, size_t passlen, - const uint8_t *salt, size_t saltlen, unsigned int count, + const uint8_t *salt, size_t saltlen, size_t count, size_t outlen, uint8_t *out) { HMAC_CTX ctx; @@ -139,7 +139,7 @@ int pbkdf2_genkey(const DIGEST *digest, hmac_init(&ctx_tmpl, digest, (uint8_t *)pass, passlen); while (outlen > 0) { - int i; + size_t i; PUTU32(iter_be, iter); iter++; diff --git a/src/pkcs8.c b/src/pkcs8.c index cfa732f6..3f5669c2 100644 --- a/src/pkcs8.c +++ b/src/pkcs8.c @@ -280,7 +280,7 @@ int pbes2_enc_algor_from_der(int *cipher, const uint8_t **iv, size_t *ivlen, con *cipher = OID_sm4_cbc; } else { size_t i; - error_print("unknown cipher oid :"); + error_print(); for (i = 0; i < nodes_count; i++) { fprintf(stderr, " %d", nodes[i]); } @@ -339,7 +339,7 @@ int pbes2_params_from_der( return -1; } if (keylen >= 0 && keylen != 16) { - error_print("keylen = %d\n", keylen); + error_print(); return -1; } return 1; @@ -436,10 +436,6 @@ int pkcs8_enced_private_key_info_from_der( int ret; const uint8_t *data; size_t datalen; - const uint8_t *algid; - size_t algidlen; - uint32_t nodes[32]; - size_t nodes_count; if ((ret = asn1_sequence_from_der(&data, &datalen, in, inlen)) != 1) { if (ret < 0) error_print(); diff --git a/src/sha1.c b/src/sha1.c index db6cfb80..0dbe89d8 100755 --- a/src/sha1.c +++ b/src/sha1.c @@ -1,5 +1,5 @@ -/* ==================================================================== - * Copyright (c) 2014 - 2017 The GmSSL Project. All rights reserved. +/* + * Copyright (c) 2014 - 2021 The GmSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -44,7 +44,6 @@ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. - * ==================================================================== */ #include @@ -52,73 +51,6 @@ #include "endian.h" -static void sha1_compress_blocks(uint32_t dgst[5], - const unsigned char *data, size_t blocks); - - -void sha1_init(SHA1_CTX *ctx) -{ - memset(ctx, 0, sizeof(*ctx)); - ctx->state[0] = 0x67452301; - ctx->state[1] = 0xEFCDAB89; - ctx->state[2] = 0x98BADCFE; - ctx->state[3] = 0x10325476; - ctx->state[4] = 0xC3D2E1F0; -} - -void sha1_update(SHA1_CTX *ctx, const unsigned char *data, size_t datalen) -{ - size_t blocks; - - if (ctx->num) { - unsigned int left = SHA1_BLOCK_SIZE - ctx->num; - if (datalen < left) { - memcpy(ctx->block + ctx->num, data, datalen); - ctx->num += datalen; - return; - } else { - memcpy(ctx->block + ctx->num, data, left); - sha1_compress_blocks(ctx->state, ctx->block, 1); - ctx->nblocks++; - data += left; - datalen -= left; - } - } - - blocks = datalen / SHA1_BLOCK_SIZE; - sha1_compress_blocks(ctx->state, data, blocks); - ctx->nblocks += blocks; - data += SHA1_BLOCK_SIZE * blocks; - datalen -= SHA1_BLOCK_SIZE * blocks; - - ctx->num = datalen; - if (datalen) { - memcpy(ctx->block, data, datalen); - } -} - -void sha1_finish(SHA1_CTX *ctx, unsigned char *dgst) -{ - int i; - - ctx->block[ctx->num] = 0x80; - - if (ctx->num + 9 <= SHA1_BLOCK_SIZE) { - memset(ctx->block + ctx->num + 1, 0, SHA1_BLOCK_SIZE - ctx->num - 9); - } else { - memset(ctx->block + ctx->num + 1, 0, SHA1_BLOCK_SIZE - ctx->num - 1); - sha1_compress_blocks(ctx->state, ctx->block, 1); - memset(ctx->block, 0, SHA1_BLOCK_SIZE - 8); - } - PUTU32(ctx->block + 56, ctx->nblocks >> 23); - PUTU32(ctx->block + 60, (ctx->nblocks << 9) + (ctx->num << 3)); - - sha1_compress_blocks(ctx->state, ctx->block, 1); - for (i = 0; i < 5; i++) { - PUTU32(dgst + i*4, ctx->state[i]); - } -} - #define F0(B, C, D) (((B) & (C)) | ((~(B)) & (D))) #define F1(B, C, D) ((B) ^ (C) ^ (D)) #define F2(B, C, D) (((B) & (C)) | ((B) & (D)) | ((C) & (D))) @@ -157,7 +89,6 @@ static void sha1_compress_blocks(uint32_t state[5], W[i] = ROL32(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1); } - /* see https://en.wikipedia.org/wiki/SHA-1#/media/File:SHA-1.svg */ for (i = 0; i < 20; i++) { T = E + F0(B, C, D) + ROL32(A, 5) + W[i] + K0; @@ -200,19 +131,77 @@ static void sha1_compress_blocks(uint32_t state[5], } } -void sha1_compress(uint32_t state[5], const unsigned char block[64]) +void sha1_init(SHA1_CTX *ctx) { - return sha1_compress_blocks(state, block, 1); + memset(ctx, 0, sizeof(*ctx)); + ctx->state[0] = 0x67452301; + ctx->state[1] = 0xEFCDAB89; + ctx->state[2] = 0x98BADCFE; + ctx->state[3] = 0x10325476; + ctx->state[4] = 0xC3D2E1F0; +} + +void sha1_update(SHA1_CTX *ctx, const unsigned char *data, size_t datalen) +{ + size_t blocks; + + ctx->num &= 0x3f; + if (ctx->num) { + unsigned int left = SHA1_BLOCK_SIZE - ctx->num; + if (datalen < left) { + memcpy(ctx->block + ctx->num, data, datalen); + ctx->num += datalen; + return; + } else { + memcpy(ctx->block + ctx->num, data, left); + sha1_compress_blocks(ctx->state, ctx->block, 1); + ctx->nblocks++; + data += left; + datalen -= left; + } + } + + blocks = datalen / SHA1_BLOCK_SIZE; + sha1_compress_blocks(ctx->state, data, blocks); + ctx->nblocks += blocks; + data += SHA1_BLOCK_SIZE * blocks; + datalen -= SHA1_BLOCK_SIZE * blocks; + + ctx->num = datalen; + if (datalen) { + memcpy(ctx->block, data, datalen); + } +} + +void sha1_finish(SHA1_CTX *ctx, unsigned char *dgst) +{ + int i; + + ctx->num &= 0x3f; + ctx->block[ctx->num] = 0x80; + + if (ctx->num <= SHA1_BLOCK_SIZE - 9) { + memset(ctx->block + ctx->num + 1, 0, SHA1_BLOCK_SIZE - ctx->num - 9); + } else { + memset(ctx->block + ctx->num + 1, 0, SHA1_BLOCK_SIZE - ctx->num - 1); + sha1_compress_blocks(ctx->state, ctx->block, 1); + memset(ctx->block, 0, SHA1_BLOCK_SIZE - 8); + } + PUTU32(ctx->block + 56, ctx->nblocks >> 23); + PUTU32(ctx->block + 60, (ctx->nblocks << 9) + (ctx->num << 3)); + + sha1_compress_blocks(ctx->state, ctx->block, 1); + for (i = 0; i < 5; i++) { + PUTU32(dgst + i*4, ctx->state[i]); + } + memset(ctx, 0, sizeof(*ctx)); } void sha1_digest(const unsigned char *data, size_t datalen, - unsigned char dgst[SHA1_DIGEST_LENGTH]) + unsigned char dgst[SHA1_DIGEST_SIZE]) { SHA1_CTX ctx; - sha1_init(&ctx); sha1_update(&ctx, data, datalen); - sha1_finish(&ctx, dgst); - - memset(&ctx, 0, sizeof(SHA1_CTX)); + memset(&ctx, 0, sizeof(ctx)); } diff --git a/src/sha256.c b/src/sha256.c index a4af8aeb..8a194d13 100755 --- a/src/sha256.c +++ b/src/sha256.c @@ -1,5 +1,5 @@ -/* ==================================================================== - * Copyright (c) 2014 - 2017 The GmSSL Project. All rights reserved. +/* + * Copyright (c) 2014 - 2021 The GmSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -44,87 +44,13 @@ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. - * ==================================================================== */ -#include -#include #include #include #include "endian.h" -static void sha256_compress_blocks(uint32_t state[8], - const unsigned char *data, size_t blocks); - -void sha256_init(SHA256_CTX *ctx) -{ - memset(ctx, 0, sizeof(*ctx)); - ctx->state[0] = 0x6a09e667; - ctx->state[1] = 0xbb67ae85; - ctx->state[2] = 0x3c6ef372; - ctx->state[3] = 0xa54ff53a; - ctx->state[4] = 0x510e527f; - ctx->state[5] = 0x9b05688c; - ctx->state[6] = 0x1f83d9ab; - ctx->state[7] = 0x5be0cd19; -} - -void sha256_update(SHA256_CTX *ctx, const unsigned char *data, size_t datalen) -{ - size_t blocks; - - if (ctx->num) { - unsigned int left = SHA256_BLOCK_SIZE - ctx->num; - if (datalen < left) { - memcpy(ctx->block + ctx->num, data, datalen); - ctx->num += datalen; - return; - } else { - memcpy(ctx->block + ctx->num, data, left); - sha256_compress_blocks(ctx->state, ctx->block, 1); - ctx->nblocks++; - data += left; - datalen -= left; - } - } - - blocks = datalen / SHA256_BLOCK_SIZE; - sha256_compress_blocks(ctx->state, data, blocks); - ctx->nblocks += blocks; - data += SHA256_BLOCK_SIZE * blocks; - datalen -= SHA256_BLOCK_SIZE * blocks; - - ctx->num = datalen; - if (datalen) { - memcpy(ctx->block, data, datalen); - } -} - -void sha256_finish(SHA256_CTX *ctx, unsigned char dgst[SHA256_DIGEST_SIZE]) -{ - int i; - - ctx->block[ctx->num] = 0x80; - - if (ctx->num + 9 <= SHA256_BLOCK_SIZE) { - memset(ctx->block + ctx->num + 1, 0, SHA256_BLOCK_SIZE - ctx->num - 9); - } else { - memset(ctx->block + ctx->num + 1, 0, SHA256_BLOCK_SIZE - ctx->num - 1); - sha256_compress_blocks(ctx->state, ctx->block, 1); - memset(ctx->block, 0, SHA256_BLOCK_SIZE - 8); - } - PUTU32(ctx->block + 56, ctx->nblocks >> 23); - PUTU32(ctx->block + 60, (ctx->nblocks << 9) + (ctx->num << 3)); - - sha256_compress_blocks(ctx->state, ctx->block, 1); - for (i = 0; i < 8; i++) { - PUTU32(dgst, ctx->state[i]); - dgst += sizeof(uint32_t); - } - memset(ctx, 0, sizeof(SHA256_CTX)); -} - #define Ch(X, Y, Z) (((X) & (Y)) ^ ((~(X)) & (Z))) #define Maj(X, Y, Z) (((X) & (Y)) ^ ((X) & (Z)) ^ ((Y) & (Z))) #define Sigma0(X) (ROR32((X), 2) ^ ROR32((X), 13) ^ ROR32((X), 22)) @@ -209,9 +135,75 @@ static void sha256_compress_blocks(uint32_t state[8], } } -void sha256_compress(uint32_t state[8], const unsigned char block[64]) + +void sha256_init(SHA256_CTX *ctx) { - sha256_compress_blocks(state, block, 1); + memset(ctx, 0, sizeof(*ctx)); + ctx->state[0] = 0x6a09e667; + ctx->state[1] = 0xbb67ae85; + ctx->state[2] = 0x3c6ef372; + ctx->state[3] = 0xa54ff53a; + ctx->state[4] = 0x510e527f; + ctx->state[5] = 0x9b05688c; + ctx->state[6] = 0x1f83d9ab; + ctx->state[7] = 0x5be0cd19; +} + +void sha256_update(SHA256_CTX *ctx, const unsigned char *data, size_t datalen) +{ + size_t blocks; + + ctx->num &= 0x3f; + if (ctx->num) { + unsigned int left = SHA256_BLOCK_SIZE - ctx->num; + if (datalen < left) { + memcpy(ctx->block + ctx->num, data, datalen); + ctx->num += datalen; + return; + } else { + memcpy(ctx->block + ctx->num, data, left); + sha256_compress_blocks(ctx->state, ctx->block, 1); + ctx->nblocks++; + data += left; + datalen -= left; + } + } + + blocks = datalen / SHA256_BLOCK_SIZE; + sha256_compress_blocks(ctx->state, data, blocks); + ctx->nblocks += blocks; + data += SHA256_BLOCK_SIZE * blocks; + datalen -= SHA256_BLOCK_SIZE * blocks; + + ctx->num = datalen; + if (datalen) { + memcpy(ctx->block, data, datalen); + } +} + +void sha256_finish(SHA256_CTX *ctx, unsigned char dgst[SHA256_DIGEST_SIZE]) +{ + int i; + + ctx->num &= 0x3f; + ctx->block[ctx->num] = 0x80; + + if (ctx->num <= SHA256_BLOCK_SIZE - 9) { + memset(ctx->block + ctx->num + 1, 0, SHA256_BLOCK_SIZE - ctx->num - 9); + } else { + memset(ctx->block + ctx->num + 1, 0, SHA256_BLOCK_SIZE - ctx->num - 1); + sha256_compress_blocks(ctx->state, ctx->block, 1); + memset(ctx->block, 0, SHA256_BLOCK_SIZE - 8); + } + PUTU32(ctx->block + 56, ctx->nblocks >> 23); + PUTU32(ctx->block + 60, (ctx->nblocks << 9) + (ctx->num << 3)); + + sha256_compress_blocks(ctx->state, ctx->block, 1); + for (i = 0; i < 8; i++) { + PUTU32(dgst, ctx->state[i]); + dgst += sizeof(uint32_t); + } + memset(ctx, 0, sizeof(*ctx)); } void sha256_digest(const unsigned char *data, size_t datalen, @@ -244,17 +236,12 @@ void sha224_update(SHA224_CTX *ctx, const unsigned char *data, size_t datalen) void sha224_finish(SHA224_CTX *ctx, unsigned char dgst[SHA224_DIGEST_SIZE]) { - unsigned char buf[SHA256_DIGEST_SIZE]; + uint8_t buf[SHA256_DIGEST_SIZE]; sha256_finish((SHA256_CTX *)ctx, buf); memcpy(dgst, buf, SHA224_DIGEST_SIZE); memset(buf, 0, sizeof(buf)); } -void sha224_compress(uint32_t state[8], const unsigned char block[64]) -{ - sha256_compress_blocks(state, block, 1); -} - void sha224_digest(const unsigned char *data, size_t datalen, unsigned char dgst[SHA224_DIGEST_SIZE]) { diff --git a/src/sm2_algo.c b/src/sm2_algo.c index ae79cfe2..93eec4b8 100644 --- a/src/sm2_algo.c +++ b/src/sm2_algo.c @@ -236,7 +236,7 @@ static int bn_print(FILE *fp, const bignum_t a, int format, int indent) if (a[i] >= ((uint64_t)1 << 32)) { printf("bn_print check failed\n"); } - ret += fprintf(fp, "%08llx", a[i]); + ret += fprintf(fp, "%08x", (uint32_t)a[i]); } ret += fprintf(fp, "\n"); return ret; @@ -340,8 +340,9 @@ static void bn_rand_range(bignum_t r, const bignum_t range) static void fp_add(bignum_t r, const bignum_t a, const bignum_t b) { bn_add(r, a, b); - if (bn_cmp(r, SM2_P) >= 0) - return bn_sub(r, r, SM2_P); + if (bn_cmp(r, SM2_P) >= 0) { + bn_sub(r, r, SM2_P); + } } static void fp_sub(bignum_t r, const bignum_t a, const bignum_t b) @@ -540,7 +541,7 @@ static void fn_add(bignum_t r, const bignum_t a, const bignum_t b) { bn_add(r, a, b); if (bn_cmp(r, SM2_N) >= 0) { - return bn_sub(r, r, SM2_N); + bn_sub(r, r, SM2_N); } } @@ -714,7 +715,7 @@ static void fn_mul(bignum_t r, const bignum_t a, const bignum_t b) static void fn_sqr(bignum_t r, const bignum_t a) { - return fn_mul(r, a, a); + fn_mul(r, a, a); } static void fn_exp(bignum_t r, const bignum_t a, const bignum_t e) @@ -747,7 +748,7 @@ static void fn_inv(bignum_t r, const bignum_t a) static void fn_rand(bignum_t r) { - return bn_rand_range(r, SM2_N); + bn_rand_range(r, SM2_N); } #define hex_fp_add_x_y "eefbe4cf140ff8b5b956d329d5a2eae8608c933cb89053217439786e54866567" @@ -1011,8 +1012,8 @@ static void point_dbl(point_t *R, const point_t *P) } -// 这个函数有一个严重的问题,就是我们假定Q是一个已经正规化的点 -// 因此如果这个点不是仿射坐标的就出现问题了 +// FIXME: Q must be affine coordinate +// change API! static void point_add(point_t *R, const point_t *P, const point_t *Q) { const uint64_t *X1 = P->X; @@ -1090,7 +1091,7 @@ static void point_mul(point_t *R, const bignum_t k, const point_t *P) point_t _T, *T = &_T; int i; - // point_add要求输入的P必须为仿射坐标 + // FIXME: point_add need affine, so we can not use point_add if (!bn_is_one(P->Z)) { bignum_t x; bignum_t y; @@ -1600,7 +1601,7 @@ int sm2_do_decrypt(const SM2_KEY *key, const SM2_CIPHERTEXT *in, uint8_t *out, s uint8_t hash[32]; int i; - // FIXME: 检查SM2_CIPHERTEXT格式 + // FIXME: check SM2_CIPHERTEXT format // check C1 point_from_bytes(P, (uint8_t *)&in->point); diff --git a/src/sm2_asn1.c b/src/sm2_asn1.c index cf424d16..2984a2ef 100644 --- a/src/sm2_asn1.c +++ b/src/sm2_asn1.c @@ -90,7 +90,7 @@ int sm2_point_from_der(SM2_POINT *a, const uint8_t **in, size_t *inlen) int ret; const uint8_t *data; size_t datalen; - error_print("inlen = %zu\n", *inlen); + error_print_msg("inlen = %zu\n", *inlen); if ((ret = asn1_octet_string_from_der(&data, &datalen, in, inlen)) != 1) { if (ret < 0) error_print(); @@ -101,7 +101,7 @@ int sm2_point_from_der(SM2_POINT *a, const uint8_t **in, size_t *inlen) error_print(); return -1; } - error_print("inlen = %zu\n", *inlen); + error_print_msg("inlen = %zu\n", *inlen); return 1; } diff --git a/src/sm3.c b/src/sm3.c index 5af6ea97..adfa651a 100755 --- a/src/sm3.c +++ b/src/sm3.c @@ -1,5 +1,5 @@ -/* ==================================================================== - * Copyright (c) 2014 - 2017 The GmSSL Project. All rights reserved. +/* + * Copyright (c) 2014 - 2021 The GmSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -44,13 +44,10 @@ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. - * ==================================================================== */ #include #include -//#include "bswap.h" -//#include "rotate.h" #include "endian.h" #ifdef SM3_SSE3 @@ -61,165 +58,6 @@ _mm_xor_si128(_mm_slli_epi32((X),(i)), _mm_srli_epi32((X),32-(i))) #endif -void sm3_compress_blocks(uint32_t digest[8], const uint8_t *data, size_t blocks); - - -void sm3_init(SM3_CTX *ctx) -{ - memset(ctx, 0, sizeof(*ctx)); - ctx->digest[0] = 0x7380166F; - ctx->digest[1] = 0x4914B2B9; - ctx->digest[2] = 0x172442D7; - ctx->digest[3] = 0xDA8A0600; - ctx->digest[4] = 0xA96F30BC; - ctx->digest[5] = 0x163138AA; - ctx->digest[6] = 0xE38DEE4D; - ctx->digest[7] = 0xB0FB0E4E; -} - -#if 0 -void sm3_compute_id_digest(uint8_t z[32], const char *id, - const uint8_t x[32], const uint8_t y[32]) -{ - uint8_t zin[] = { - 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, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x06, 0x90, - }; - - if (!id || strcmp(id, "1234567812345678")) { - unsigned int digest[8] = { - 0xadadedb5U, 0x0446043fU, 0x08a87aceU, 0xe86d2243U, - 0x8e232383U, 0xbfc81fe2U, 0xcf9117c8U, 0x4707011dU, - }; - memcpy(&zin[128], x, 32); - memcpy(&zin[160], y, 32); - sm3_compress_blocks(digest, zin, 2); - PUTU32(z , digest[0]); - PUTU32(z + 4, digest[1]); - PUTU32(z + 8, digest[2]); - PUTU32(z + 12, digest[3]); - PUTU32(z + 16, digest[4]); - PUTU32(z + 20, digest[5]); - PUTU32(z + 24, digest[6]); - PUTU32(z + 28, digest[7]); - - } else { - SM3_CTX ctx; - uint8_t idbits[2]; - size_t len; - - len = strlen(id); - idbits[0] = (uint8_t)(len >> 5); - idbits[1] = (uint8_t)(len << 3); - - sm3_init(&ctx); - sm3_update(&ctx, idbits, 2); - sm3_update(&ctx, (uint8_t *)id, len); - sm3_update(&ctx, zin + 18, 128); - sm3_update(&ctx, x, 32); - sm3_update(&ctx, y, 32); - sm3_finish(&ctx, z); - } -} - -int sm3_sm2_init(SM3_CTX *ctx, const char *id, - const uint8_t *x, const uint8_t *y) -{ - uint8_t z[32]; - if ((id && strlen(id) > 65535/8) || !x || !y) { - return 0; - } - sm3_compute_id_digest(z, id, x, y); - sm3_init(ctx); - sm3_update(ctx, z, 32); - return 1; -} -#endif - -void sm3_update(SM3_CTX *ctx, const uint8_t *data, size_t data_len) -{ - size_t blocks; - - if (ctx->num) { - unsigned int left = SM3_BLOCK_SIZE - ctx->num; - if (data_len < left) { - memcpy(ctx->block + ctx->num, data, data_len); - ctx->num += data_len; - return; - } else { - memcpy(ctx->block + ctx->num, data, left); - sm3_compress_blocks(ctx->digest, ctx->block, 1); - ctx->nblocks++; - data += left; - data_len -= left; - } - } - - blocks = data_len / SM3_BLOCK_SIZE; - sm3_compress_blocks(ctx->digest, data, blocks); - ctx->nblocks += blocks; - data += SM3_BLOCK_SIZE * blocks; - data_len -= SM3_BLOCK_SIZE * blocks; - - ctx->num = data_len; - if (data_len) { - memcpy(ctx->block, data, data_len); - } -} - -void sm3_finish(SM3_CTX *ctx, uint8_t *digest) -{ - int i; - - ctx->block[ctx->num] = 0x80; - - if (ctx->num + 9 <= SM3_BLOCK_SIZE) { - memset(ctx->block + ctx->num + 1, 0, SM3_BLOCK_SIZE - ctx->num - 9); - } else { - memset(ctx->block + ctx->num + 1, 0, SM3_BLOCK_SIZE - ctx->num - 1); - sm3_compress(ctx->digest, ctx->block); - memset(ctx->block, 0, SM3_BLOCK_SIZE - 8); - } - PUTU32(ctx->block + 56, ctx->nblocks >> 23); - PUTU32(ctx->block + 60, (ctx->nblocks << 9) + (ctx->num << 3)); - - sm3_compress(ctx->digest, ctx->block); - for (i = 0; i < 8; i++) { - PUTU32(digest + i*4, ctx->digest[i]); - } - memset(ctx, 0, sizeof(SM3_CTX)); -} #define ROTL(x,n) (((x)<<(n)) | ((x)>>(32-(n)))) #define P0(x) ((x) ^ ROL32((x), 9) ^ ROL32((x),17)) @@ -492,9 +330,167 @@ void sm3_compress_blocks(uint32_t digest[8], const uint8_t *data, size_t blocks) } } -void sm3_compress(uint32_t digest[8], const uint8_t block[64]) + +void sm3_init(SM3_CTX *ctx) { - return sm3_compress_blocks(digest, block, 1); + memset(ctx, 0, sizeof(*ctx)); + ctx->digest[0] = 0x7380166F; + ctx->digest[1] = 0x4914B2B9; + ctx->digest[2] = 0x172442D7; + ctx->digest[3] = 0xDA8A0600; + ctx->digest[4] = 0xA96F30BC; + ctx->digest[5] = 0x163138AA; + ctx->digest[6] = 0xE38DEE4D; + ctx->digest[7] = 0xB0FB0E4E; +} + + + + +#if 0 +void sm3_compute_id_digest(uint8_t z[32], const char *id, + const uint8_t x[32], const uint8_t y[32]) +{ + uint8_t zin[] = { + 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, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x06, 0x90, + }; + + if (!id || strcmp(id, "1234567812345678")) { + unsigned int digest[8] = { + 0xadadedb5U, 0x0446043fU, 0x08a87aceU, 0xe86d2243U, + 0x8e232383U, 0xbfc81fe2U, 0xcf9117c8U, 0x4707011dU, + }; + memcpy(&zin[128], x, 32); + memcpy(&zin[160], y, 32); + sm3_compress_blocks(digest, zin, 2); + PUTU32(z , digest[0]); + PUTU32(z + 4, digest[1]); + PUTU32(z + 8, digest[2]); + PUTU32(z + 12, digest[3]); + PUTU32(z + 16, digest[4]); + PUTU32(z + 20, digest[5]); + PUTU32(z + 24, digest[6]); + PUTU32(z + 28, digest[7]); + + } else { + SM3_CTX ctx; + uint8_t idbits[2]; + size_t len; + + len = strlen(id); + idbits[0] = (uint8_t)(len >> 5); + idbits[1] = (uint8_t)(len << 3); + + sm3_init(&ctx); + sm3_update(&ctx, idbits, 2); + sm3_update(&ctx, (uint8_t *)id, len); + sm3_update(&ctx, zin + 18, 128); + sm3_update(&ctx, x, 32); + sm3_update(&ctx, y, 32); + sm3_finish(&ctx, z); + } +} + +int sm3_sm2_init(SM3_CTX *ctx, const char *id, + const uint8_t *x, const uint8_t *y) +{ + uint8_t z[32]; + if ((id && strlen(id) > 65535/8) || !x || !y) { + return 0; + } + sm3_compute_id_digest(z, id, x, y); + sm3_init(ctx); + sm3_update(ctx, z, 32); + return 1; +} +#endif + +void sm3_update(SM3_CTX *ctx, const uint8_t *data, size_t data_len) +{ + size_t blocks; + + ctx->num &= 0x3f; + if (ctx->num) { + unsigned int left = SM3_BLOCK_SIZE - ctx->num; + if (data_len < left) { + memcpy(ctx->block + ctx->num, data, data_len); + ctx->num += data_len; + return; + } else { + memcpy(ctx->block + ctx->num, data, left); + sm3_compress_blocks(ctx->digest, ctx->block, 1); + ctx->nblocks++; + data += left; + data_len -= left; + } + } + + blocks = data_len / SM3_BLOCK_SIZE; + sm3_compress_blocks(ctx->digest, data, blocks); + ctx->nblocks += blocks; + data += SM3_BLOCK_SIZE * blocks; + data_len -= SM3_BLOCK_SIZE * blocks; + + ctx->num = data_len; + if (data_len) { + memcpy(ctx->block, data, data_len); + } +} + +void sm3_finish(SM3_CTX *ctx, uint8_t *digest) +{ + int i; + + ctx->num &= 0x3f; + ctx->block[ctx->num] = 0x80; + + if (ctx->num <= SM3_BLOCK_SIZE - 9) { + memset(ctx->block + ctx->num + 1, 0, SM3_BLOCK_SIZE - ctx->num - 9); + } else { + memset(ctx->block + ctx->num + 1, 0, SM3_BLOCK_SIZE - ctx->num - 1); + sm3_compress_blocks(ctx->digest, ctx->block, 1); + memset(ctx->block, 0, SM3_BLOCK_SIZE - 8); + } + PUTU32(ctx->block + 56, ctx->nblocks >> 23); + PUTU32(ctx->block + 60, (ctx->nblocks << 9) + (ctx->num << 3)); + + sm3_compress_blocks(ctx->digest, ctx->block, 1); + for (i = 0; i < 8; i++) { + PUTU32(digest + i*4, ctx->digest[i]); + } + memset(ctx, 0, sizeof(SM3_CTX)); } void sm3_digest(const uint8_t *msg, size_t msglen, diff --git a/src/sm3_hmac.c b/src/sm3_hmac.c index f89ba3fd..d4d91894 100644 --- a/src/sm3_hmac.c +++ b/src/sm3_hmac.c @@ -110,26 +110,7 @@ void sm3_hmac_finish(SM3_HMAC_CTX *ctx, uint8_t mac[SM3_HMAC_SIZE]) sm3_update(&ctx->sm3_ctx, ctx->key, SM3_BLOCK_SIZE); sm3_update(&ctx->sm3_ctx, mac, SM3_DIGEST_SIZE); sm3_finish(&ctx->sm3_ctx, mac); -} - -int sm3_hmac_finish_and_verify(SM3_HMAC_CTX *ctx, const uint8_t mac[SM3_HMAC_SIZE]) -{ - uint8_t buf[32]; - sm3_hmac_finish(ctx, buf); - if (memcmp(mac, buf, sizeof(buf)) == 0) { - return 1; - } else { - error_print("sm3_hmac verify failure"); - return 0; - } -} - -void sm3_hmac_reset(SM3_HMAC_CTX *ctx) -{ - sm3_init(&ctx->sm3_ctx); - sm3_update(&ctx->sm3_ctx, ctx->key, SM3_BLOCK_SIZE); - // 不应该保留原始密钥,而是应该保持这次update之后的状态 - // 这样可以降低reset的工作量 + memset(ctx, 0, sizeof(*ctx)); } void sm3_hmac(const uint8_t *data, size_t data_len, @@ -140,5 +121,4 @@ void sm3_hmac(const uint8_t *data, size_t data_len, sm3_hmac_init(&ctx, key, key_len); sm3_hmac_update(&ctx, data, data_len); sm3_hmac_finish(&ctx, mac); - memset(&ctx, 0, sizeof(ctx)); } diff --git a/src/sm4_modes.c b/src/sm4_modes.c index 5beeecb7..35c2400d 100644 --- a/src/sm4_modes.c +++ b/src/sm4_modes.c @@ -81,7 +81,7 @@ int sm4_cbc_padding_encrypt(const SM4_KEY *key, const uint8_t iv[16], { uint8_t block[16]; size_t rem = inlen % 16; - int padding = 16 - rem; + int padding = 16 - inlen % 16; if (in) { memcpy(block, in + inlen - rem, rem); @@ -102,14 +102,15 @@ int sm4_cbc_padding_decrypt(const SM4_KEY *key, const uint8_t iv[16], uint8_t *out, size_t *outlen) { uint8_t block[16]; + size_t len = sizeof(block); int padding; if (inlen == 0) { - error_print("warning: input lenght = 0"); + error_puts("warning: input lenght = 0"); return 0; } if (inlen%16 != 0 || inlen < 16) { - error_print("invalid cbc ciphertext length"); + error_puts("invalid cbc ciphertext length"); return -1; } if (inlen > 16) { @@ -122,7 +123,8 @@ int sm4_cbc_padding_decrypt(const SM4_KEY *key, const uint8_t iv[16], error_print(); return -1; } - memcpy(out + inlen - 16, block, 16 - padding); + len -= padding; + memcpy(out + inlen - 16, block, len); *outlen = inlen - padding; return 1; } diff --git a/src/tlcp.c b/src/tlcp.c index 3d995b23..4eacfe43 100644 --- a/src/tlcp.c +++ b/src/tlcp.c @@ -341,7 +341,7 @@ int tlcp_connect(TLS_CONNECT *conn, const char *hostname, int port, return -1; } if ( sm2_verify_finish(&verify_ctx, sig, siglen) != 1) { - error_print("ServerKeyExchange signature verification failure"); + error_puts("ServerKeyExchange signature verification failure"); return -1; } @@ -535,7 +535,7 @@ int tlcp_connect(TLS_CONNECT *conn, const char *hostname, int port, return -1; } if (memcmp(local_verify_data, verify_data, 12) != 0) { - error_print("server_finished.verify_data verification failure"); + error_puts("server_finished.verify_data verification failure"); return -1; } @@ -595,7 +595,7 @@ int tlcp_accept(TLS_CONNECT *conn, int port, return -1; } - error_print("start listen ..."); + error_puts("start listen ..."); listen(sock, 5); memset(conn, 0, sizeof(*conn)); @@ -608,7 +608,7 @@ int tlcp_accept(TLS_CONNECT *conn, int port, return -1; } - error_print("connected\n"); + error_puts("connected\n"); @@ -638,7 +638,7 @@ int tlcp_accept(TLS_CONNECT *conn, int port, } } if (conn->cipher_suite == 0) { - error_print("no common cipher_suite"); + error_puts("no common cipher_suite"); return -1; } sm3_update(&sm3_ctx, record + 5, recordlen - 5); @@ -893,7 +893,7 @@ int tlcp_accept(TLS_CONNECT *conn, int port, return -1; } if (memcmp(local_verify_data, verify_data, 12) != 0) { - error_print("client_finished.verify_data verification failure"); + error_puts("client_finished.verify_data verification failure"); return -1; } diff --git a/src/tls.c b/src/tls.c index 8cc3297f..c470e3a2 100644 --- a/src/tls.c +++ b/src/tls.c @@ -337,7 +337,7 @@ int tls_cbc_encrypt(const SM3_HMAC_CTX *inited_hmac_ctx, const SM4_KEY *enc_key, return -1; } if (inlen > (1 << 14)) { - error_print("invalid tls record data length %zu\n", inlen); + error_print_msg("invalid tls record data length %zu\n", inlen); return -1; } @@ -384,6 +384,7 @@ int tls_cbc_decrypt(const SM3_HMAC_CTX *inited_hmac_ctx, const SM4_KEY *dec_key, const uint8_t *mac; uint8_t header[5]; int padding_len; + uint8_t hmac[32]; int i; if (!inited_hmac_ctx || !dec_key || !seq_num || !enced_header || !in || !inlen || !out || !outlen) { @@ -393,7 +394,7 @@ int tls_cbc_decrypt(const SM3_HMAC_CTX *inited_hmac_ctx, const SM4_KEY *dec_key, if (inlen % 16 || inlen < (16 + 0 + 32 + 16) // iv + data + mac + padding || inlen > (16 + (1<<14) + 32 + 256)) { - error_print("invalid tls cbc ciphertext length %zu\n", inlen); + error_print_msg("invalid tls cbc ciphertext length %zu\n", inlen); return -1; } @@ -411,7 +412,7 @@ int tls_cbc_decrypt(const SM3_HMAC_CTX *inited_hmac_ctx, const SM4_KEY *dec_key, } for (i = 0; i < padding_len; i++) { if (padding[i] != padding_len) { - error_print("tls ciphertext cbc-padding check failure"); + error_puts("tls ciphertext cbc-padding check failure"); return -1; } } @@ -428,8 +429,9 @@ int tls_cbc_decrypt(const SM3_HMAC_CTX *inited_hmac_ctx, const SM4_KEY *dec_key, sm3_hmac_update(&hmac_ctx, seq_num, 8); sm3_hmac_update(&hmac_ctx, header, 5); sm3_hmac_update(&hmac_ctx, out, *outlen); - if (sm3_hmac_finish_and_verify(&hmac_ctx, mac) != 1) { - error_print("tls ciphertext mac check failure"); + sm3_hmac_finish(&hmac_ctx, hmac); + if (memcmp(mac, hmac, sizeof(hmac)) != 0) { //FIXME: const time memcmp! + error_puts("tls ciphertext mac check failure"); return -1; } return 1; @@ -634,7 +636,7 @@ int tls_record_set_handshake(uint8_t *record, size_t *recordlen, return -1; } if (datalen > (1 << 14) - 4) { - error_print("gmssl does not support handshake longer than record"); + error_puts("gmssl does not support handshake longer than record"); return -1; } handshakelen = 4 + datalen; @@ -885,7 +887,7 @@ int tls_record_get_handshake_server_hello(const uint8_t *record, return -1; } if (!tls_cipher_suite_name(*cipher_suite)) { - error_print("unknown server cipher_suite 0x%04x", *cipher_suite); + error_print_msg("unknown server cipher_suite 0x%04x", *cipher_suite); return -1; } if (comp_meth != TLS_compression_null) { @@ -894,7 +896,7 @@ int tls_record_get_handshake_server_hello(const uint8_t *record, } if (len > 0) { if (tls_record_version(record) < TLS_version_tls12) { - error_print("warning: should not have extentions"); + error_puts("warning: should not have extentions"); return -1; } // FIXME: 用 tls_extensions_from_bytes() 解析 @@ -1355,7 +1357,7 @@ int tls_record_get_alert(const uint8_t *record, return -1; } if (!tls_alert_description_text(*alert_description)) { - error_print("warning"); + error_puts("warning"); return -1; } return 1; @@ -1394,7 +1396,7 @@ int tls_record_get_change_cipher_spec(const uint8_t *record) return -1; } if (record[5] != TLS_change_cipher_spec) { - error_print("unknown ChangeCipherSpec value %d", record[5]); + error_print_msg("unknown ChangeCipherSpec value %d", record[5]); return -1; } return 1; @@ -1470,11 +1472,11 @@ int tls_record_recv(uint8_t *record, size_t *recordlen, int sock) } if (!tls_record_type_name(record[0])) { - error_print("invalid record type: %d\n", record[0]); + error_print_msg("invalid record type: %d\n", record[0]); return -1; } if (!tls_version_text(tls_record_version(record))) { - error_print("invalid record version: %d.%d\n", record[1], record[2]); + error_print_msg("invalid record version: %d.%d\n", record[1], record[2]); return -1; } len = (size_t)record[3] << 8 | record[4]; @@ -1589,3 +1591,9 @@ int tls_recv(TLS_CONNECT *conn, uint8_t *data, size_t *datalen) *datalen = mlen - 5; return 1; } + +//FIXME: any difference in TLS 1.2 and TLS 1.3? +int tls_shutdown(TLS_CONNECT *conn) +{ + return -1; +} diff --git a/src/tls12.c b/src/tls12.c index 6cda97ce..fdd25bca 100644 --- a/src/tls12.c +++ b/src/tls12.c @@ -560,7 +560,7 @@ int tls12_connect(TLS_CONNECT *conn, const char *hostname, int port, sm3_hash, 32, NULL, 0, 12, local_verify_data); if (memcmp(local_verify_data, verify_data, 12) != 0) { - error_print("server_finished.verify_data verification failure"); + error_puts("server_finished.verify_data verification failure"); return -1; } @@ -625,7 +625,7 @@ int tls12_accept(TLS_CONNECT *conn, int port, return -1; } - error_print("start listen ..."); + error_puts("start listen ..."); listen(sock, 5); memset(conn, 0, sizeof(*conn)); @@ -638,7 +638,7 @@ int tls12_accept(TLS_CONNECT *conn, int port, return -1; } - error_print("connected\n"); + error_puts("connected\n"); @@ -673,7 +673,7 @@ int tls12_accept(TLS_CONNECT *conn, int port, } } if (conn->cipher_suite == 0) { - error_print("no common cipher_suite"); + error_puts("no common cipher_suite"); return -1; } sm3_update(&sm3_ctx, record + 5, recordlen - 5); @@ -930,7 +930,7 @@ int tls12_accept(TLS_CONNECT *conn, int port, sm3_hash, 32, NULL, 0, 12, local_verify_data); if (memcmp(local_verify_data, verify_data, 12) != 0) { - error_print("client_finished.verify_data verification failure"); + error_puts("client_finished.verify_data verification failure"); return -1; } diff --git a/src/tls13.c b/src/tls13.c index dc3ee2f8..5fa05401 100644 --- a/src/tls13.c +++ b/src/tls13.c @@ -1709,7 +1709,7 @@ int tls13_accept(TLS_CONNECT *conn, int port, return -1; } - error_print("start listen ..."); + error_puts("start listen ..."); listen(sock, 5); memset(conn, 0, sizeof(*conn)); @@ -1722,7 +1722,7 @@ int tls13_accept(TLS_CONNECT *conn, int port, return -1; } - error_print("connected\n"); + error_puts("connected\n"); // 1. Recv ClientHello @@ -1753,7 +1753,7 @@ int tls13_accept(TLS_CONNECT *conn, int port, } } if (conn->cipher_suite == 0) { - error_print("no common cipher_suite"); + error_puts("no common cipher_suite"); return -1; } if (tls13_client_hello_extensions_get(exts, extslen, &client_ecdhe_public) != 1) { diff --git a/src/tls_trace.c b/src/tls_trace.c index e251a911..93b62eab 100644 --- a/src/tls_trace.c +++ b/src/tls_trace.c @@ -222,7 +222,7 @@ const char *tls_alert_level_name(int level) case TLS_alert_level_warning: return "warning"; case TLS_alert_level_fatal: return "fatal"; } - error_print("unknown alert level %d", level); + error_print_msg("unknown alert level %d", level); return NULL; } @@ -260,7 +260,7 @@ const char *tls_alert_description_text(int description) case TLS_alert_unsupported_ibcparam: return "unsupported_ibcparam"; case TLS_alert_identity_need: return "identity_need"; } - error_print("unknown alert description %d", description); + error_print_msg("unknown alert description %d", description); return NULL; } diff --git a/src/x509_algor.c b/src/x509_algor.c index 40fc580a..95e7f3aa 100644 --- a/src/x509_algor.c +++ b/src/x509_algor.c @@ -182,7 +182,7 @@ int x509_encryption_algor_from_der(int *cipher, *cipher = OID_sm4_cbc; } else { size_t i; - error_print("unknown cipher oid :"); + error_puts("unknown cipher oid :"); for (i = 0; i < nodes_count; i++) { fprintf(stderr, " %d", nodes[i]); } @@ -273,7 +273,7 @@ int x509_signature_algor_from_der(int *oid, const uint8_t **in, size_t *inlen) return -1; } if (datalen > 0) { - error_print("datalen = %zu", datalen); + error_print_msg("datalen = %zu", datalen); error_print(); return -1; } diff --git a/src/x509_asn1.c b/src/x509_asn1.c index 7f5d8328..7a96e921 100644 --- a/src/x509_asn1.c +++ b/src/x509_asn1.c @@ -79,7 +79,7 @@ int x509_version_to_der(int version, uint8_t **out, size_t *outlen) case X509_version_v3: break; default: - error_print("invalid version"); + error_puts("invalid version"); return -1; } if (asn1_int_to_der(version, NULL, &len) != 1 @@ -112,7 +112,7 @@ int x509_version_from_der(int *version, const uint8_t **in, size_t *inlen) } switch (*version) { case X509_version_v1: - error_print("warning: version v1 should not be encoded"); + error_puts("warning: version v1 should not be encoded"); break; case X509_version_v2: case X509_version_v3: @@ -260,10 +260,10 @@ int x509_directory_string_to_der(int tag, const char *a, size_t alen, uint8_t ** case ASN1_TAG_TeletexString: case ASN1_TAG_UniversalString: case ASN1_TAG_BMPString: - error_print("not implemented"); + error_print(); return -1; default: - error_print("invalid tag"); + error_print(); return -1; } @@ -293,7 +293,7 @@ int x509_directory_string_from_der(int *tag, const char **a, size_t *alen, const case ASN1_TAG_BMPString: break; default: - error_print("DirectoryString tag = %d\n", *tag); + error_print(); return -1; } return 1; @@ -335,7 +335,7 @@ static int x509_rdn_check(int oid, int tag, const char *str, int len) case ASN1_TAG_BMPString: break; default: - error_print("tag = %d\n", tag); + error_print(); return -1; } if (x509_rdns[i].is_printable_string_only && tag != ASN1_TAG_PrintableString) { @@ -511,7 +511,7 @@ const char *x509_name_rdn(const X509_NAME *name, int oid) case OID_at_dnQualifier: return name->dn_qualifier; } - error_print("unsupported X509 NAME OID %d\n", oid); + error_print(); return NULL; } @@ -1015,7 +1015,7 @@ int x509_tbs_certificate_from_der(X509_TBS_CERTIFICATE *a, const uint8_t **in, s || (is_ext = x509_extensions_from_der(&a->extensions, &data, &datalen)) < 0 || datalen > 0) { error_print(); - if (datalen > 0) error_print("datalen = %zu\n", datalen); + if (datalen > 0) error_print(); return -1; } diff --git a/src/x509_ext.c b/src/x509_ext.c index 51e7ad16..67608533 100644 --- a/src/x509_ext.c +++ b/src/x509_ext.c @@ -355,7 +355,7 @@ int x509_key_purpose_to_der(int oid, uint8_t **out, size_t *outlen) return 1; } } - error_print("unknown key purpose oid %d", oid); + error_print_msg("unknown key purpose oid %d", oid); return -1; } @@ -382,7 +382,7 @@ int x509_key_purpose_from_der(int *oid, const uint8_t **in, size_t *inlen) } } // 这种情况下应该把这个值打印出来 - error_print("unknown ExtKeyUsage OID"); + error_puts("unknown ExtKeyUsage OID"); return -1; } diff --git a/src/zuc_core.c b/src/zuc_core.c index c9093dce..a763fcee 100644 --- a/src/zuc_core.c +++ b/src/zuc_core.c @@ -388,8 +388,11 @@ void zuc_mac_finish(ZUC_MAC_CTX *ctx, const unsigned char *data, size_t nbits, u ctx->T = T; PUTU32(mac, T); + + memset(ctx, 0, sizeof(*ctx)); } + typedef unsigned char ZUC_UINT7; static const ZUC_UINT7 ZUC256_D[][16] = { @@ -598,4 +601,6 @@ void zuc256_mac_finish(ZUC256_MAC_CTX *ctx, const unsigned char *data, size_t nb PUTU32(mac, ctx->T[j]); mac += 4; } + + memset(ctx, 0, sizeof(*ctx)); } diff --git a/tests/asn1test.c b/tests/asn1test.c index f5f030bb..6a5884ab 100644 --- a/tests/asn1test.c +++ b/tests/asn1test.c @@ -140,7 +140,7 @@ static int test_asn1_length(void) rv = asn1_length_from_der(&val, &cp, &left); assert(rv > 0); if (val != tests[i]) { - error_print("error decoding %zu-th length: get %zu, should be %zu", i, val, tests[i]); + error_print_msg("error decoding %zu-th length: get %zu, should be %zu", i, val, tests[i]); err++; } } @@ -175,7 +175,7 @@ static int test_asn1_boolean(void) rv = asn1_boolean_from_der(&val, &cp, &left); assert(rv > 0); if (val != tests[i]) { - error_print("error decoding %zu-th: get %d, should be %d", i, val, tests[i]); + error_print_msg("error decoding %zu-th: get %d, should be %d", i, val, tests[i]); err++; } } @@ -210,7 +210,7 @@ static int test_asn1_integer(void) rv = asn1_int_from_der(&val, &cp, &left); assert(rv > 0); if (val != tests[i]) { - error_print("error decoding %zu-th: get %d, should be %d", i, val, tests[i]); + error_print_msg("error decoding %zu-th: get %d, should be %d", i, val, tests[i]); err++; } } @@ -245,7 +245,7 @@ static int test_asn1_bit_string(void) rv = asn1_bits_from_der(&val, &cp, &left); assert(rv > 0); if (val != tests[i]) { - error_print("error decoding %zu-th: get %d, should be %d", i, val, tests[i]); + error_print_msg("error decoding %zu-th: get %d, should be %d", i, val, tests[i]); err++; } } @@ -312,7 +312,7 @@ static int test_asn1_object_identifier(void) rv = asn1_object_identifier_from_der(&val, nodes, &nodes_count, &cp, &left); assert(rv > 0); if (val != tests[i]) { - error_print("error decoding %zu-th: get %d, should be %d", i, val, tests[i]); + error_print_msg("error decoding %zu-th: get %d, should be %d", i, val, tests[i]); err++; } printf("%s\n", asn1_object_identifier_name(val)); @@ -353,7 +353,7 @@ static int test_asn1_printable_string(void) memcpy(str, val, vallen); if (strcmp(str, tests[i]) != 0) { - error_print("error decoding %zu-th: get %s, should be %s", i, str, tests[i]); + error_print_msg("error decoding %zu-th: get %s, should be %s", i, str, tests[i]); err++; } printf("%s\n", str); @@ -394,7 +394,7 @@ static int test_asn1_utf8_string(void) memcpy(str, val, vallen); if (strcmp(str, tests[i]) != 0) { - error_print("error decoding %zu-th: get %s, should be %s", i, str, tests[i]); + error_print_msg("error decoding %zu-th: get %s, should be %s", i, str, tests[i]); err++; } printf("%s\n", str); @@ -435,7 +435,7 @@ static int test_asn1_ia5_string(void) memcpy(str, val, vallen); if (strcmp(str, tests[i]) != 0) { - error_print("error decoding %zu-th: get %s, should be %s", i, str, tests[i]); + error_print_msg("error decoding %zu-th: get %s, should be %s", i, str, tests[i]); err++; } printf("%s\n", str); @@ -451,9 +451,10 @@ static int test_time(void) printf("%s", ctime(&tval)); time(&tval); printf("%s", ctime(&tval)); - printf("%016llx\n", (uint64_t)tval); + printf("%08x%08x\n", (uint32_t)(tval >> 32), (uint32_t)tval); + return 0; } @@ -484,7 +485,7 @@ static int test_asn1_utc_time(void) rv = asn1_utc_time_from_der(&val, &cp, &left); assert(rv > 0); if (val != tests[i]) { - error_print("error decoding %zu-th: get %zu, should be %zu", i, val, tests[i]); + error_print_msg("error decoding %zu-th: get %zu, should be %zu", i, val, tests[i]); err++; } printf("%s", ctime(&val)); @@ -523,7 +524,7 @@ static int test_asn1_generalized_time(void) rv = asn1_generalized_time_from_der(&val, &cp, &left); assert(rv > 0); if (val != tests[i]) { - error_print("error decoding %zu-th: get %zu, should be %zu", i, val, tests[i]); + error_print_msg("error decoding %zu-th: get %zu, should be %zu", i, val, tests[i]); err++; } printf("%s", ctime(&val)); diff --git a/tools/certverify.c b/tools/certverify.c index 833e03b4..fd04a3fa 100644 --- a/tools/certverify.c +++ b/tools/certverify.c @@ -49,7 +49,7 @@ #include #include #include -#include +//#include #include #include #include diff --git a/tools/digest.c b/tools/digest.c index e38a14ee..5582775a 100644 --- a/tools/digest.c +++ b/tools/digest.c @@ -49,7 +49,6 @@ #include #include #include -#include #include #define FORMAT_HEX 1 diff --git a/tools/hmac.c b/tools/hmac.c index d6749497..441b76da 100644 --- a/tools/hmac.c +++ b/tools/hmac.c @@ -49,7 +49,7 @@ #include #include #include -#include +//#include #include #define FORMAT_HEX 1 diff --git a/tools/sm2decrypt.c b/tools/sm2decrypt.c index 108f934d..974311d0 100644 --- a/tools/sm2decrypt.c +++ b/tools/sm2decrypt.c @@ -102,7 +102,7 @@ help: } pass = getpass("Encryption Password : "); if (sm2_enced_private_key_info_from_pem(&key, pass, keyfp) != 1) { - error_print("private key decryption failure"); + error_puts("private key decryption failure"); return -1; } if ((hexlen = fread(hexbuf, 1, sizeof(hexbuf), stdin)) <= 0) { diff --git a/tools/sm2sign.c b/tools/sm2sign.c index 11737665..5824a04e 100644 --- a/tools/sm2sign.c +++ b/tools/sm2sign.c @@ -111,7 +111,7 @@ help: } pass = getpass("Encryption Password : "); if (sm2_enced_private_key_info_from_pem(&key, pass, keyfp) != 1) { - error_print("private key decryption failure"); + error_puts("private key decryption failure"); return -1; } diff --git a/tools/sm3sum.c b/tools/sm3sum.c index 8f6cdbd3..27fd8d56 100644 --- a/tools/sm3sum.c +++ b/tools/sm3sum.c @@ -49,7 +49,6 @@ #include #include #include -#include #include @@ -69,7 +68,7 @@ int main(int argc, char **argv) } sm3_init(&ctx); - while ((len = read(STDIN_FILENO, buf, sizeof(buf))) > 0) { + while ((len = fread(buf, 1, sizeof(buf), stdin)) > 0) { sm3_update(&ctx, buf, len); } sm3_finish(&ctx, dgst); diff --git a/tools/tlcp_client.c b/tools/tlcp_client.c index 7d93d81b..eb328446 100644 --- a/tools/tlcp_client.c +++ b/tools/tlcp_client.c @@ -49,7 +49,6 @@ #include #include #include -#include #include #include