diff --git a/tags/20100201_Sharp_Release/LICENSE_en.txt b/tags/20100201_Sharp_Release/LICENSE_en.txt new file mode 100644 index 0000000..a2c4adc --- /dev/null +++ b/tags/20100201_Sharp_Release/LICENSE_en.txt @@ -0,0 +1,127 @@ + + LICENSE ISSUES + ============== + + The OpenSSL toolkit stays under a dual license, i.e. both the conditions of + the OpenSSL License and the original SSLeay license apply to the toolkit. + See below for the actual license texts. Actually both licenses are BSD-style + Open Source licenses. In case of any license issues related to OpenSSL + please contact openssl-core@openssl.org. + + OpenSSL License + --------------- + +/* ==================================================================== + * Copyright (c) 1998-2008 The OpenSSL 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 OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL 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 OpenSSL 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 product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + + Original SSLeay License + ----------------------- + +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * 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 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 acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS 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 AUTHOR OR 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. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + diff --git a/tags/20100201_Sharp_Release/LICENSE_jp.txt b/tags/20100201_Sharp_Release/LICENSE_jp.txt new file mode 100644 index 0000000..48882ab --- /dev/null +++ b/tags/20100201_Sharp_Release/LICENSE_jp.txt @@ -0,0 +1,37 @@ +OpenSSL ライセンス +Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved. + +ソースおよびバイナリー形式での再配布および使用は、変更の有無に拘らず、次の条件を満たす場合に許可されます。 + +ソース・コードを再配布する場合には、上記の著作権表示、この使用条件および以下の免責表示を含める必要があります。 +バイナリー形式で再配布する場合には、上記の著作権表示、以下の使用条件および免責表示を、配布に際して提供する関連文書および資料に記載する必要があります。 +このソフトウェアの機能または使用について言及するすべての広告用材料では、次の謝辞を表示する必要があります。「この製品には、OpenSSL Toolkit で使用するために OpenSSL Project によって開発されたソフトウェアが組み込まれています。 (http://www.openssl.org/)」 +事前の書面による許可がなければ、「OpenSSL Toolkit」と「OpenSSL Project」の名前を、このソフトウェアから派生した製品の承認または促進に使用してはなりません。書面による許可が必要な場合は、openssl-core@openssl.org に連絡してください。 +OpenSSL Project の事前の書面による許可がなければ、このソフトウェアから派生した製品を「OpenSSL」と呼ぶことはできませんし、また、それらの製品の名前に「OpenSSL」が含まれていてはなりません。 +いかなる形の再配布にも、次の謝辞を表示する必要があります。「この製品には、OpenSSL Toolkit で使用するために OpenSSL Project によって開発されたソフトウェアが含まれています。(http://www.openssl.org/)」 +OpenSSL Project は、このソフトウェアを特定物として現存するままの状態で提供し、法律上の瑕疵担保責任、商品性の保証および特定目的適合性の保証を含むすべての明示もしくは黙示の保証責任を負いません。 起こりうる損害について予見の有無を問わず、「ソフトウェア」を使用したために生じる、直接的、間接的、付帯的、特別、懲罰的、または結果的損害 (代替の製品またはサービスの調達、データまたは利益の喪失、事業の中断などを含み、他のいかなる場合も含む) については、それが契約、厳格な責任、不法行為 (過失の場合もそうでない場合も含む) など、いかなる責任の理論においても、OpenSSL Project およびその寄稿者はその責任を負いません。 + +この製品には、Eric Young (eay@cryptsoft.com) により作成された暗号化ソフトウェアが含まれています。この製品には、Tim Hudson (tjh@cryptsoft.com) により作成されたソフトウェアが含まれています。 + + + +SSLeay ライセンス + +Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) All rights reserved. + +このパッケージは、Eric Young (eay@cryptsoft.com) により作成された SSL インプリメンテーションです。このインプリメンテーションは、Netscape SSL に準拠するように作成されています。 + +このライブラリーは、以下の条件に従う限り、無料での商業および非商業の使用が許可されます。以下の条件は、単に SSL コードだけでなく、この配布に含まれるすべてのコードに適用されます。この場合、そのコードが RC4、RSA、lhash、DES、などにいずれであっても構いません。この配布に含まれる SSL 資料は、著作権所有者が Tim Hudson (tjh@cryptsoft.com) である点を除き、同一著作権によってカバーされます。 + +著作権は Eric Young が所有していますので、コードの著作権表示を除去してはなりません。このパッケージをいずれかの製品に使用する場合は、使用するライブラリー部分の作成者として Eric Young を特定する必要があります。これは、プログラム始動時に、またはこのパッケージと一緒に提供される資料 (オンラインまたはテキスト) にテキスト形式のメッセージとして含めることができます。 + +ソースおよびバイナリー形式での再配布および使用は、変更の有無に拘らず、次の条件を満たす場合に許可されます。 + +ソース・コードを再配布する場合には、この著作権表示、この使用条件および以下の免責表示を含める必要があります。 +バイナリー形式で再配布する場合には、上記の著作権表示、以下の使用条件および免責表示を、配布に際して提供する関連文書および資料に記載する必要があります。 +このソフトウェアの機能と使用に言及するすべての広告用材料では、次のような謝辞を表示する必要があります。「この製品には、Eric Young 氏 (eay@cryptsoft.com) によって作成された暗号ソフトウェアが含まれています」。使用するライブラリーからのルーチンが暗号に関係ない場合は、「暗号」という語を省略することができます。 +apps ディレクトリー (アプリケーション・コード) からの Windows 固有のコード (またはその派生物) を組み込む場合は、次の謝辞を表示する必要があります。「この製品には、Tim Hudson 氏 (tjh@cryptsoft.com) によって作成されたソフトウェアが含まれています。」 +Eric Young は、このソフトウェアを特定物として現存するままの状態で提供し、法律上の瑕疵担保責任、商品性の保証および特定目的適合性の保証を含むすべての明示もしくは黙示の保証責任を負いません。 起こりうる損害について予見の有無を問わず、「ソフトウェア」を使用したために生じる、直接的、間接的、付帯的、特別、懲罰的、または結果的損害 (代替の製品またはサービスの調達、データまたは利益の喪失、事業の中断などを含み、他のいかなる場合も含む) については、それが契約、厳格な責任、不法行為 (過失の場合もそうでない場合も含む) など、いかなる責任の理論においても、作成者および寄稿者はその責任を負いません。 + +このコードのすべての公開済みバージョンまたは派生物のライセンスおよび配布条件は、変更できません。すなわち、このコードは、単にコピーすることも、他の配布ライセンス (GNU Public Licence も含む) に含めることもできません。 + diff --git a/tags/20100201_Sharp_Release/Makefile b/tags/20100201_Sharp_Release/Makefile new file mode 100644 index 0000000..00ea837 --- /dev/null +++ b/tags/20100201_Sharp_Release/Makefile @@ -0,0 +1,224 @@ +# nm ntd_mem_allocator.o | grep " [T|B|D] " +# nm ntd_crypto_ecdsa.o | grep " [T|B|D] " +# nm ntd_crypto_rsa.o | grep " [T|B|D] " +# nm generate_id.o | grep " [T|B|D] " +# nm ../rsa_keysrcgen/rsa1_key.o | grep " [T|B|D] " + + +# 最終的なビルドスイッチの設定は、以下の通り。 +# DEV_CYGWIN = FALSE +# DEBUG_PRINT = FALSE +# DEBUG_OUTPUT = FALSE +# ECDSA_SHA256 = TRUE +# USE_HSM = TRUE +# RESET_HSM = TRUE + +DEV_CYGWIN = FALSE +DEBUG_PRINT = FALSE +DEBUG_OUTPUT = FALSE +ECDSA_SHA256 = TRUE +USE_HSM = TRUE +RESET_HSM = TRUE + +ifeq ($(USE_HSM),TRUE) + +# HSM使用時は強制的にDUMMY_KEYは未使用にする。 +USE_DUMMY_KEY = FALSE + +# nFast Path +NFAST_PATH = /opt/nfast + +# nFast Developer tools installation +NFAST_DEV_PATH = $(NFAST_PATH)/c/ctd/gcc +NFAST_EXAMPLES = $(NFAST_PATH)/c/ctd/examples + +# nFast Developer tools library +NFAST_LIBPATH = $(NFAST_DEV_PATH)/lib + +# nFast Developer tools include +NFAST_INC = $(NFAST_DEV_PATH)/include + +# nFast CPPFLAGS +NFAST_CPPFLAGS = \ + -I$(NFAST_INC)/sworld \ + -I$(NFAST_INC)/hilibs \ + -I$(NFAST_INC)/nflog \ + -I$(NFAST_INC)/cutils \ + -I$(NFAST_EXAMPLES)/sworld \ + -I$(NFAST_EXAMPLES)/hilibs \ + -I$(NFAST_EXAMPLES)/nflog \ + -I$(NFAST_EXAMPLES)/cutils \ + +# nFast LDLIBS +NFAST_LDLIBS = \ + $(NFAST_LIBPATH)/libnfkm.a \ + $(NFAST_LIBPATH)/libnfstub.a \ + $(NFAST_LIBPATH)/libnflog.a \ + $(NFAST_LIBPATH)/libcutils.a \ + +else # !USE_HSM + +# HSMが使用できない場合は、DUMMY_KEYを使ってテストする。 +USE_DUMMY_KEY = TRUE + +endif # USE_HSM + +ifeq ($(USE_DUMMY_KEY),TRUE) +DEV_DER_KEY_DIR = ./dummyKey/dev +PROD_DER_KEY_DIR = ./dummyKey/prod +else # !USE_DUMMY_KEY +DEV_DER_KEY_DIR = ./realKey/dev +PROD_DER_KEY_DIR = ./realKey/prod +endif # USE_DUMMY_KEY + +PACKAGE_DIR = ./package +OPENSSL_DIR = ./openssl-1.0.0-beta5 +# OPENSSL_DIR = ./openssl-0.9.8k + +TARGET_LIB = libgenid.a + +TARGET = gen_id + +KEYS_C = cr_eFuse_iv_prod.c \ + cr_eFuse_iv_dev.c \ + cr_NCT2_pub_prod.c \ + cr_NCT2_pub_dev.c + +ifeq ($(USE_DUMMY_KEY),TRUE) +KEYS_C += cr_eFuse_privKey_prod.c cr_eFuse_pubKey_prod.c \ + cr_eFuse_privKey_dev.c cr_eFuse_pubKey_dev.c \ + cr_eFuse_aesKey_prod.c \ + cr_eFuse_aesKey_dev.c \ + cr_NCT2_priv_prod.c \ + cr_NCT2_priv_dev.c +endif # USE_DUMMY_KEY + +SRCS = main.c +OBJS = $(notdir $(SRCS:.c=.o)) + +LIB_SRCS = cr_generate_id.c cr_id_util.c cr_keyPair.c \ + cr_device_cert.c cr_enc_id.c cr_alloc.c \ + cr_hsm_code.c cr_hsm_alloc.c cr_hsm_bignum.c +LIB_OBJS = $(notdir $(LIB_SRCS:.c=.o)) + +CFLAGS = -Wall -DMEXP=216091 -msse2 -DHAVE_SSE2 +CPPFLAGS= -I. -I$(OPENSSL_DIR)/include -I$(OPENSSL_DIR)/crypto/ec +LDFLAGS = -mwindows -L$(OPENSSL_DIR) +LDLIBS = -lcrypto -lssl +MERGE_PROG = merge_lib_objs.plx + +ifeq ($(DEV_CYGWIN),TRUE) +CC := C:/Cygwin/bin/gcc +LD = C:/Cygwin/bin/gcc +CFLAGS += -mno-cygwin -DDEV_CYGWIN +LDFLAGS += -Wl,--subsystem,console -mno-cygwin +TARGET_DEL = $(TARGET).exe +else # DEV_CYGWIN +CC := /usr/bin/gcc +LD = /usr/bin/gcc +LDFLAGS += -Wl +LDLIBS += -ldl -lnsl +TARGET_DEL = $(TARGET) +endif # DEV_CYGWIN + +ifeq ($(USE_DUMMY_KEY),TRUE) +CFLAGS += -DUSE_DUMMY_KEY +endif + +ifeq ($(DEBUG_PRINT),TRUE) +CFLAGS += -DDEBUG_PRINT +endif + +ifeq ($(DEBUG_OUTPUT),TRUE) +CFLAGS += -DDEBUG_OUTPUT_FILE +endif + +ifeq ($(ECDSA_SHA256),TRUE) +CFLAGS += -DECDSA_SHA256 +endif + +ifeq ($(USE_HSM),TRUE) +CFLAGS += -DUSE_HSM +CPPFLAGS+= $(NFAST_CPPFLAGS) +LDLIBS += $(NFAST_LDLIBS) +MERGE_PROG = merge_lib_objs_hsm.plx +endif + +ifeq ($(RESET_HSM),TRUE) +CFLAGS += -DRESET_HSM +endif + +.SUFFIXES: + +all: package_build $(KEYS_C) $(TARGET_LIB) $(TARGET) + +# install: $(TARGET) +# install -c -m 777 $(TARGET) ../bin + +ifeq ($(DEV_CYGWIN),TRUE) +package_build : + cd $(PACKAGE_DIR);make DEV_CYGWIN=TRUE +else +package_build : + cd $(PACKAGE_DIR);make +endif + +$(TARGET): $(OBJS) $(TARGET_LIB) + $(LD) $(LDFLAGS) $(OBJS) -o $@ $(TARGET_LIB) + +$(TARGET_LIB): $(LIB_OBJS) + ar rcs $@ $(LIB_OBJS) + perl tools/$(MERGE_PROG) + +%.o:%.c + $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@ + +#%.c:$(DER_KEY_DIR)/%.der +# perl tools/bin2c.plx $< + +cr_eFuse_privKey_prod.c : $(PROD_DER_KEY_DIR)/eFuse_privKey.der + perl tools/bin2c.plx $< prod + +cr_eFuse_pubKey_prod.c : $(PROD_DER_KEY_DIR)/eFuse_pubKey.der + perl tools/bin2c.plx $< prod + +cr_eFuse_aesKey_prod.c : $(PROD_DER_KEY_DIR)/eFuse_aesKey.bin + perl tools/bin2c.plx $< prod + +cr_eFuse_iv_prod.c : $(PROD_DER_KEY_DIR)/eFuse_iv.bin + perl tools/bin2c.plx $< prod + +cr_NCT2_priv_prod.c : $(PROD_DER_KEY_DIR)/NCT2_priv.der + perl tools/bin2c.plx $< prod + +cr_NCT2_pub_prod.c : $(PROD_DER_KEY_DIR)/NCT2_pub.der + perl tools/bin2c.plx $< prod + + +cr_eFuse_privKey_dev.c : $(DEV_DER_KEY_DIR)/eFuse_privKey.der + perl tools/bin2c.plx $< dev + +cr_eFuse_pubKey_dev.c : $(DEV_DER_KEY_DIR)/eFuse_pubKey.der + perl tools/bin2c.plx $< dev + +cr_eFuse_aesKey_dev.c : $(DEV_DER_KEY_DIR)/eFuse_aesKey.bin + perl tools/bin2c.plx $< dev + +cr_eFuse_iv_dev.c : $(DEV_DER_KEY_DIR)/eFuse_iv.bin + perl tools/bin2c.plx $< dev + +cr_NCT2_priv_dev.c : $(DEV_DER_KEY_DIR)/NCT2_priv.der + perl tools/bin2c.plx $< dev + +cr_NCT2_pub_dev.c : $(DEV_DER_KEY_DIR)/NCT2_pub.der + perl tools/bin2c.plx $< dev + + +.PHONY: clean clobber +clean: + $(RM) $(LIB_OBJS) $(OBJS) $(TARGET_DEL) $(TARGET_LIB) $(KEYS_C) $(KEYS_H) + +clobber: + $(RM) $(LIB_OBJS) $(OBJS) $(TARGET_DEL) $(TARGET_LIB) $(KEYS_C) $(KEYS_H) + cd $(PACKAGE_DIR);make clobber + diff --git a/tags/20100201_Sharp_Release/Makefile.sharp b/tags/20100201_Sharp_Release/Makefile.sharp new file mode 100644 index 0000000..d1d01b8 --- /dev/null +++ b/tags/20100201_Sharp_Release/Makefile.sharp @@ -0,0 +1,44 @@ + +# Linux 上でビルドする場合は、DEV_CYGWINをコメントアウトしてください。 +#DEV_CYGWIN = TRUE + +TARGET = gen_id + +SRCS = main.c + +OBJS = $(notdir $(SRCS:.c=.o)) + +ifeq ($(DEV_CYGWIN),TRUE) + +CC := C:/Cygwin/bin/gcc +LD = C:/Cygwin/bin/gcc +CFLAGS += -mno-cygwin -DDEV_CYGWIN -Wall -I./ +LDFLAGS += -Wl,--subsystem,console -mwindows -mno-cygwin -L./ +LDLIBS += -lgenid +TARGET_DEL = $(TARGET).exe + +else # DEV_CYGWIN + +CC := /usr/bin/gcc +LD = /usr/bin/gcc +LDFLAGS += -Wl -L./ +LDLIBS += -ldl -lnsl -lgenid +TARGET_DEL = $(TARGET) + +endif # DEV_CYGWIN + +.SUFFIXES: + +all: $(TARGET) + +$(TARGET): $(OBJS) + $(LD) $(LDFLAGS) $(OBJS) -o $@ $(LDLIBS) + +%.o:%.c + $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@ + +.PHONY: clean clobber +clean clobber: + $(RM) $(OBJS) $(TARGET_DEL) + + diff --git a/tags/20100201_Sharp_Release/ReleasePackage.csh b/tags/20100201_Sharp_Release/ReleasePackage.csh new file mode 100644 index 0000000..cd9c8da --- /dev/null +++ b/tags/20100201_Sharp_Release/ReleasePackage.csh @@ -0,0 +1,27 @@ +#!c:/tcsh/tcsh.exe + +set mydir="cr_generate_id" + +set myfiles="Makefile.sharp main.c cr_generate_id.h libgenid.a readme_openssl.txt LICENSE_en.txt LICENSE_jp.txt readme.txt readme_openssl.txt" + + +if(-e $mydir.zip) then + rm -f $mydir.zip +endif + +if(-d $mydir ) then + rm -rf $mydir +endif + +mkdir $mydir + +foreach myfile ($myfiles) + if(-e $mydir/$myfile) then + rm -f $mydir/$myfile + endif + cp $myfile $mydir/$myfile +end + +mv $mydir/Makefile.sharp $mydir/Makefile + +zip $mydir.zip $mydir/* diff --git a/tags/20100201_Sharp_Release/ReleasePackage.sh b/tags/20100201_Sharp_Release/ReleasePackage.sh new file mode 100644 index 0000000..bb5bdde --- /dev/null +++ b/tags/20100201_Sharp_Release/ReleasePackage.sh @@ -0,0 +1,32 @@ +#!/usr/bin/sh + +mydir="generate_id" +echo $mydir + +myfiles="Makefile.sharp main.c cr_generate_id.h libgenid.a readme_openssl.txt LICENSE_en.txt LICENSE_jp.txt readme.txt readme_openssl.txt" + + +if [ -e mydir.zip ] +then + rm -f $mydir.zip +fi + +if [ -e $mydir ] +then + rm -rf $mydir +fi + +mkdir $mydir + +for myfile in $myfiles +do + if [ -e $mydir/$myfile ] + then + rm -f $mydir/$myfile + fi + cp $myfile $mydir/$myfile +done + +mv $mydir/Makefile.sharp $mydir/Makefile + +zip $mydir.zip $mydir/* diff --git a/tags/20100201_Sharp_Release/cr_alloc.c b/tags/20100201_Sharp_Release/cr_alloc.c new file mode 100644 index 0000000..b59fea4 --- /dev/null +++ b/tags/20100201_Sharp_Release/cr_alloc.c @@ -0,0 +1,477 @@ +#include +#include +#include + + +typedef int BOOL; +typedef signed char s8; +typedef unsigned char u8; +typedef unsigned short u16; +typedef unsigned long u32; +typedef unsigned long long u64; + +#include "cr_alloc.h" + +#define OFFSET(n, a) (((u32) (n)) & ((a) - 1)) +#define TRUNC(n, a) (((u32) (n)) & ~((a) - 1)) +#define ROUND(n, a) (((u32) (n) + (a) - 1) & ~((a) - 1)) + +#define ALIGNMENT 32 // alignment in bytes +#define MINOBJSIZE (HEADERSIZE + ALIGNMENT) // smallest object +#define HEADERSIZE ROUND(sizeof(Cell), ALIGNMENT) + +//---- InRange(): True if a <= targ < b +#define InRange(targ, a, b) \ + ((u32)(a) <= (u32)(targ) && (u32)(targ) < (u32)(b)) + +//---- RangeOverlap(): True if the ranges a and b overlap in any way. +#define RangeOverlap(aStart, aEnd, bStart, bEnd) \ + (((u32)(bStart) <= (u32)(aStart)) && ((u32)(aStart) < (u32)(bEnd)) || \ + ((u32)(bStart) < (u32)(aEnd)) && ((u32)(aEnd) <= (u32)(bEnd)) ) + +//---- RangeSubset(): True if range a is a subset of range b +// Assume (aStart < aEnd) and (bStart < bEnd) +#define RangeSubset(aStart, aEnd, bStart, bEnd) \ + ((u32)(bStart) <= (u32)(aStart) && (u32)(aEnd) <= (u32)(bEnd)) + +typedef struct Cell Cell; +typedef struct HeapDesc HeapDesc; + +struct Cell { + struct Cell *prev; + struct Cell *next; + long size; // size of object plus HEADERSIZE +}; + +struct HeapDesc { + long size; // if -1 then heap is free. Note OS_AllocFixed() + // could make a heap empty. + Cell *free; // pointer to the first free cell + Cell *allocated; // pointer to the first used cell +}; + + +typedef struct { + // volatile because some functions use this as hidden macro parameter + void *arenaStart; + void *arenaEnd; + HeapDesc *heapArray; +} OSHeapInfo; + + /* + -- heapInfo - arenaStart + (OSHeapInfo) + -- heapArray -- + (HeapDesc) + -- arenaStart -- + */ + + + +static OSHeapInfo *_sys_heapInfo; + + +static Cell *DLAddFront(Cell * list, Cell * cell) +{ + cell->next = list; + cell->prev = NULL; + if (list) + { + list->prev = cell; + } + return cell; +} + +static Cell *DLExtract(Cell * list, Cell * cell) +{ + if (cell->next) + { + cell->next->prev = cell->prev; + } + + if (cell->prev == NULL) + { + return cell->next; + } + else + { + cell->prev->next = cell->next; + return list; + } +} + +static Cell *DLInsert(Cell * list, Cell * cell) +{ + Cell *prev; + Cell *next; + + for (next = list, prev = NULL; next; prev = next, next = next->next) + { + if (cell <= next) + { + break; + } + } + + cell->next = next; + cell->prev = prev; + if (next) + { + next->prev = cell; + if ((char *)cell + cell->size == (char *)next) + { + //---- Coalesce forward + cell->size += next->size; + cell->next = next = next->next; + if (next) + { + next->prev = cell; + } + } + } + if (prev) + { + prev->next = cell; + if ((char *)prev + prev->size == (char *)cell) + { + //---- Coalesce back + prev->size += cell->size; + prev->next = next; + if (next) + { + next->prev = prev; + } + } + return list; + } + else + { + return cell; // cell becomes new head of list + } +} + + +static void *cr_alloc_Alloc( u32 size) +{ + OSHeapInfo *heapInfo; + HeapDesc *hd; + Cell *cell; // candidate block + Cell *newCell; // ptr to leftover block + long leftoverSize; // size of any leftover + + heapInfo = _sys_heapInfo; + + hd = heapInfo->heapArray; + + // printf("heapArray 2 0x%p\n", hd); + + // Enlarge size to smallest possible cell size + size += HEADERSIZE; + size = ROUND(size, ALIGNMENT); + + // Search for block large enough + for (cell = hd->free; cell != NULL; cell = cell->next) + { + if ((long)size <= cell->size) + { + break; + } + } + + if (cell == NULL) + { + // miya printf("%s %d\n",__FUNCTION__,__LINE__); + return NULL; + } + + leftoverSize = cell->size - (long)size; + if (leftoverSize < MINOBJSIZE) + { + //---- Just extract this cell out since it's too small to split + hd->free = DLExtract(hd->free, cell); + } + else + { + //---- cell is large enough to split into two pieces + cell->size = (long)size; + + //---- Create a new cell + newCell = (Cell *) ((char *)cell + size); + newCell->size = leftoverSize; + + //---- Leave newCell in free, and take cell away + newCell->prev = cell->prev; + newCell->next = cell->next; + + if (newCell->next != NULL) + { + newCell->next->prev = newCell; + } + + if (newCell->prev != NULL) + { + newCell->prev->next = newCell; + } + else + { + // SDK_TASSERTMSG(hd->free == cell, OS_ERR_ALLOCFROMHEAP_BROKENHEAP); + hd->free = newCell; + } + } + + //---- Add to allocated list + hd->allocated = DLAddFront(hd->allocated, cell); + + return (void *)((char *)cell + HEADERSIZE); +} + + +static void cr_alloc_Free( void *ptr) +{ + OSHeapInfo *heapInfo; + HeapDesc *hd; + Cell *cell; + + heapInfo = _sys_heapInfo; + + cell = (Cell *) ((char *)ptr - HEADERSIZE); + hd = heapInfo->heapArray; + + hd->allocated = DLExtract(hd->allocated, cell); + + hd->free = DLInsert(hd->free, cell); +} + + +u32 OSi_GetTotalAllocSize(BOOL isHeadInclude) +{ + OSHeapInfo *heapInfo; + Cell *cell; + u32 sum = 0; + + heapInfo = _sys_heapInfo; + + if (isHeadInclude) + { + for (cell = heapInfo->heapArray->allocated; cell; cell = cell->next) + { + sum += (u32)(cell->size); + } + } + else + { + for (cell = heapInfo->heapArray->allocated; cell; cell = cell->next) + { + sum += (u32)(cell->size - HEADERSIZE); + } + } + return sum; +} + +u32 cr_alloc_GetTotalFreeSize(void) +{ + OSHeapInfo *heapInfo; + Cell *cell; + u32 sum = 0; + + heapInfo = _sys_heapInfo; + + for (cell = heapInfo->heapArray->free; cell; cell = cell->next) + { + sum += (u32)(cell->size - HEADERSIZE); + } + return sum; +} + +u32 cr_alloc_GetMaxFreeSize(void) +{ + OSHeapInfo *heapInfo; + Cell *cell; + u32 candidate = 0; + + heapInfo = _sys_heapInfo; + + for (cell = heapInfo->heapArray->free; cell; cell = cell->next) + { + u32 size = (u32)(cell->size - HEADERSIZE); + if (size > candidate) + { + candidate = size; + } + } + return candidate; +} + + +static void *cr_alloc_InitAlloc(void *arenaStart, void *arenaEnd) +{ + OSHeapInfo *heapInfo; + HeapDesc *hd; + Cell *cell; + + + heapInfo = arenaStart; + _sys_heapInfo = heapInfo; + + + heapInfo->heapArray = (void *)((u32)arenaStart + sizeof(OSHeapInfo)); + + /* + -- heapInfo - arenaStart + (OSHeapInfo) + -- heapArray -- + (HeapDesc) + -- arenaStart -- + */ + + hd = heapInfo->heapArray; + + hd->size = -1; + hd->free = hd->allocated = NULL; + + //---- Set OSi_CurrentHeap to an invalid value + + //---- Reset arenaStart to the nearest reasonable location + arenaStart = (void *)((char *)heapInfo->heapArray + sizeof(HeapDesc) ); + arenaStart = (void *)ROUND(arenaStart, ALIGNMENT); + + heapInfo->arenaStart = arenaStart; + heapInfo->arenaEnd = (void *)TRUNC(arenaEnd, ALIGNMENT); + + + hd = heapInfo->heapArray; + + if (hd->size < 0) { + // hd->size = (char *)end - (char *)start; + hd->size = (char *)(heapInfo->arenaEnd)- (char *)(heapInfo->arenaStart); + + // cell = (Cell *) start; + cell = (Cell *)(heapInfo->arenaStart); + cell->prev = NULL; + cell->next = NULL; + cell->size = hd->size; + hd->free = cell; + hd->allocated = 0; + } + return heapInfo->arenaStart; +} + + +/* */ + +static int alloc_counter = 0; +static int alloc_counter2 = 0; + +//#define TSIZE_KERNEL_BUFFER 0x30000 +#define TSIZE_KERNEL_BUFFER 0x20000 + +static u32 __kernel_bufmgr_buffer[TSIZE_KERNEL_BUFFER/sizeof(u32)]; + + +int cr_mem_get_counter(void) +{ + return alloc_counter; +} + +int cr_mem_get_counter2(void) +{ + return alloc_counter2; +} + + +void cr_mem_bufmgr_initialize(void) +{ + //miya printf("%s %d\n",__FUNCTION__,__LINE__); + memset(__kernel_bufmgr_buffer, 0, TSIZE_KERNEL_BUFFER); + (void)cr_alloc_InitAlloc((void *)__kernel_bufmgr_buffer, + (void *)&(__kernel_bufmgr_buffer[TSIZE_KERNEL_BUFFER/sizeof(u32)])); + alloc_counter = 0; + alloc_counter2 = 0; +} + + + +void *cr_mem_malloc(size_t size) +{ + void *p_blk; + + alloc_counter++; + + p_blk = cr_alloc_Alloc( size ); + + if( NULL == p_blk ) { + //miya fprintf(stderr, "Error:%s %d\n",__FUNCTION__,__LINE__); + return NULL; + } + memset( p_blk, 0 , size); + return p_blk; +} + +void cr_mem_free(void *ptr) +{ + cr_alloc_Free( ptr ); + alloc_counter--; +} + +void *cr_mem_calloc(size_t nmemb, size_t size) +{ + void *p_blk; + + alloc_counter++; + + p_blk = cr_alloc_Alloc( size * nmemb ); + + if( NULL == p_blk ) { + //miya fprintf(stderr, "Error:%s %d\n",__FUNCTION__,__LINE__); + return NULL; + } + + return p_blk; +} + + + +void *cr_mem_realloc(void *ptr, size_t size) +{ + void *p_blk; + + // OSHeapInfo *heapInfo; + // HeapDesc *hd; + // heapInfo = _sys_heapInfo; + // hd = heapInfo->heapArray; + + // KMEMB *hdr; + Cell *cell; + + p_blk = cr_alloc_Alloc( size ); + + if( NULL == p_blk ) { + //miya fprintf(stderr, "Error:call realloc error %d\n",alloc_counter); + return NULL; + } + + // hdr = (KMEMB *)ptr - 1; + cell = (Cell *) ((char *)ptr - HEADERSIZE); + +#if 0 + if( hdr->size > size ) { + memcpy(p_blk, ptr, size); + } + else { + memcpy(p_blk, ptr, hdr->size); + } +#else + if( cell->size > size ) { + memcpy(p_blk, ptr, size); + } + else { + memcpy(p_blk, ptr, cell->size); + } +#endif + + + cr_alloc_Free( ptr ); + + return p_blk; +} + diff --git a/tags/20100201_Sharp_Release/cr_alloc.h b/tags/20100201_Sharp_Release/cr_alloc.h new file mode 100644 index 0000000..d6c6f2c --- /dev/null +++ b/tags/20100201_Sharp_Release/cr_alloc.h @@ -0,0 +1,30 @@ +#ifndef _CR_ALLOC_H_ +#define _CR_ALLOC_H_ + + + +#ifdef __cplusplus +extern "C" { +#endif + +unsigned long cr_alloc_GetMaxFreeSize(void); +unsigned long cr_alloc_GetTotalFreeSize(void); +unsigned long cr_alloc_GetTotalAllocSize(int isHeadInclude); + +void cr_mem_bufmgr_initialize(void); +int cr_mem_get_counter(void); +int cr_mem_get_counter2(void); + +void *cr_mem_realloc(void *ptr, size_t size); +void *cr_mem_calloc(size_t nmemb, size_t size); +void cr_mem_free(void *ptr); +void *cr_mem_malloc(size_t size); + + + +#ifdef __cplusplus +} +#endif + + +#endif /* _CR_ALLOC_H_ */ diff --git a/tags/20100201_Sharp_Release/cr_device_cert.c b/tags/20100201_Sharp_Release/cr_device_cert.c new file mode 100644 index 0000000..8b2788c --- /dev/null +++ b/tags/20100201_Sharp_Release/cr_device_cert.c @@ -0,0 +1,453 @@ +/* ==================================================================== + * Copyright (c) 1998-2008 The OpenSSL 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 OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL 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 OpenSSL 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 product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * 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 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 acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS 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 AUTHOR OR 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. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include +#include +#include +#include +#include +#include + +#ifdef USE_HSM +#include "cr_hsm_code.h" +#include "cr_hsm_bignum.h" + +// for develop +#include +#include +#include +#else +// openssl +#include +#include +#include +#include "cr_NCT2_priv_dev.c" +#include "cr_NCT2_priv_prod.c" +#endif // USE_HSM + +#include "cr_NCT2_pub_dev.c" +#include "cr_NCT2_pub_prod.c" + +#include "cr_generate_id.h" +#include "cr_generate_id_private.h" + + +#define CR_CERT_EXPIRE_SECS ( 60*60*24*365* 20 ) // 繝繝舌う繧ケ險シ譏取嶌譛滄剞 20蟷エ 窶サ縺繧九≧蟷エ縺ッ辟。隕 + +u8 tempSign[ 70 ]; + +// TWL device cert base +typedef struct CR_DeviceCert +{ + u8 sigType [ 4 ]; // 0x000 - 0x003 : 0x00010005, signature type is ECDSA + SHA256 + u8 eccSignature[ 60 ]; // 0x004 - 0x03F : ECDSA using SHA-256 and CA key + u8 padding0 [ 64 ]; // 0x040 - 0x07F : zero-filled + u8 issuerName [ 64 ]; // 0x080 - 0x0BF : issuer name, "Root-CA00000002-MS00000008" + u8 keyType [ 4 ]; // 0x0C0 - 0x0C3 : 0x00000002, cert public key type is ECC233 + u8 subject [ 64 ]; // 0x0C4 - 0x103 : subject field, "CTxxxxxxxx-yy" + u32 expiryDate; // 0x104 - 0x107 : second from Epoch (Jan 1, 1970 00:00) + u8 eccPubKey [ 60 ]; // 0x108 - 0x143 : cert public key (openssl sect233r1) + u8 padding1 [ 60 ]; // 0x144 - 0x17F : zero-filled +} CR_DeviceCert; + +const u8 issuerName[] = { + 0x14, 0x33, 0x34, 0x2E, 0x3F, 0x34, 0x3E, 0x35, + 0x7A, 0x19, 0x1B, 0x7A, 0x77, 0x7A, 0x1D, 0x69, + 0x05, 0x14, 0x33, 0x34, 0x2E, 0x3F, 0x34, 0x3E, + 0x35, 0x19, 0x0E, 0x08, +}; + +static void BN2BinWithPadding( BIGNUM *pBn, u8 *pDst, int dstLen ); + + +// create CTR Device cert +int GenerateCTRDeviceCert( EC_KEY *pECkey, u32 device_id, u8 bonding_option, u8 *pDevCertSign, u32 *pExpiryDate ) +{ + int ret_code = CR_GENID_SUCCESS; + CR_DeviceCert deviceCert; + EC_KEY *NCT2 = NULL; + int i; + +#ifdef DEBUG_PRINT + if ( sizeof( CR_DeviceCert ) > 384 ) + { + printf( "CR_DeviceCert size error. %d\n", sizeof(CR_DeviceCert) ); + } +#endif + + memset( &deviceCert, 0, sizeof(deviceCert) ); + + // sigType + // ECDSA+SHA256 = 0x00010005, ECDSA+SHA1 = 0x00010002 + deviceCert.sigType[0] = 0x00; + deviceCert.sigType[1] = 0x01; + deviceCert.sigType[2] = 0x00; +#ifdef ECDSA_SHA256 + deviceCert.sigType[3] = 0x05; +#else // !ECDSA_SHA256 + deviceCert.sigType[3] = 0x02; +#endif // ECDSA_SHA256 + + // issuerName + for( i = 0; i < sizeof(issuerName); i++ ) { + deviceCert.issuerName[ i ] = issuerName[ i ] ^ 0x5a; + } + sprintf( &deviceCert.issuerName[ sizeof(issuerName) ], "%s", bonding_option ? "dev" : "prod" ); + + // keyType 0x00000002 ECC233 + deviceCert.keyType[0] = 0x00; + deviceCert.keyType[1] = 0x00; + deviceCert.keyType[2] = 0x00; + deviceCert.keyType[3] = 0x02; + + // subject : CT + device_id + bonding_option + sprintf( deviceCert.subject, "CT%08X-%02X", (unsigned int)device_id, bonding_option ); + + // expiryDate +20years + *pExpiryDate += CR_CERT_EXPIRE_SECS; // ID_BUF縺ォ繧りィシ譏取嶌譛滄剞繧偵そ繝繝医☆繧九 + deviceCert.expiryDate = *pExpiryDate; + + // eccPubKey + BN2BinWithPadding( &pECkey->pub_key->X, &deviceCert.eccPubKey[ 0 ], 30 ); + BN2BinWithPadding( &pECkey->pub_key->Y, &deviceCert.eccPubKey[ 30 ], 30 ); +#if 0 + DEBUG_PRINT_ARRAY( "eccPubKey:", (const char *)deviceCert.eccPubKey, 60 ); + DEBUG_PRINT_ARRAY( "eccPubKey.X:", (const char *)pECkey->pub_key->X.d, pECkey->pub_key->X.dmax * 4 ); + DEBUG_PRINT_ARRAY( "eccPubKey.Y:", (const char *)pECkey->pub_key->Y.d, pECkey->pub_key->Y.dmax * 4 ); +#endif + + // eccSignature +#ifdef USE_HSM + + // ECDSA鄂イ蜷堺サ伜刈 +#ifdef ECDSA_SHA256 + u8 sha256Buf[ SHA256_DIGEST_LENGTH ]; + u8 modifyHash[ SHA256_DIGEST_LENGTH ]; + + // CR_DeviceCert縺ョSHA256險育ョ + SHA256( deviceCert.issuerName, (int)&deviceCert + sizeof(CR_DeviceCert) - (int)deviceCert.issuerName, sha256Buf ); + DEBUG_PRINT_ARRAY( "sha256(HSM)", (const char *)sha256Buf, 32 ); + + // HSM 縺ッ蛻繧願ゥー繧√↑縺縺ァ鄂イ蜷阪@縺ヲ縺励∪縺縺ョ縺ァ閾ェ蜑阪〒蜉蟾・縺吶k + memset( modifyHash, 0, sizeof( modifyHash ) ); + modifyHash[2] = sha256Buf[0] >> 7; + for( i = 3; i < SHA256_DIGEST_LENGTH; i++ ) + modifyHash[i] = (sha256Buf[i-3] << 1) | (sha256Buf[i-2] >> 7); + + ret_code = hsm_ecdsa_sign( deviceCert.eccSignature, modifyHash, bonding_option ); +#else // !ECDSA_SHA256 + u8 sha1Buf[ 20 ]; + SHA1( deviceCert.issuerName, (int)&deviceCert + sizeof(CR_DeviceCert) - (int)deviceCert.issuerName, sha1Buf ); + DEBUG_PRINT_ARRAY( "sha1(HSM)", (const char *)sha1Buf, 20 ); + + ret_code = hsm_ecdsa_sign( deviceCert.eccSignature, sha1Buf, bonding_option ); +#endif // ECDSA_SHA256 + + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + memcpy( pDevCertSign, &deviceCert.eccSignature, 60 ); +#else // !USE_HSM + // DER繝輔か繝シ繝槭ャ繝医ョECC骰オ繧定ェュ縺ソ霎シ縺ソ + { + // bonding_option 縺ォ繧医▲縺ヲ縲骰オ繧貞キョ縺玲崛縺 + const unsigned char *der_priv = bonding_option ? cr_NCT2_priv_dev : cr_NCT2_priv_prod; + int priv_len = der_priv[ 8 ] | der_priv[ 9 ] << 8; // KEY髟キ繧貞叙繧雁コ縺 + der_priv += 0x10; // 繝倥ャ繝驛ィ蛻繧帝勁螟悶@縺ヲKEY螳滉ス薙r謖螳 + + // ECC縺ッ縲∫ァ伜ッ骰オ縺ョ縺ソ縺ァ蜈ャ髢矩嵯謌仙繧ゅそ繝繝医&繧後k繧医≧縺ェ縺ョ縺ァ縲∝ャ髢矩嵯縺ッ隱ュ縺ソ霎シ縺セ縺ェ縺縲 + NCT2 = d2i_ECPrivateKey( NULL, &der_priv, priv_len ); + if( NCT2 == NULL ) { + ret_code = CR_GENID_ERROR_ECC_READ_PRIVATE_KEY; + goto end; + } +#if 0 + DEBUG_PRINT_ARRAY( "EC priv:", (const char *)NCT2->priv_key->d, NCT2->priv_key->dmax * 4); + DEBUG_PRINT_ARRAY( "EC pub.X:", (const char *)NCT2->pub_key->X.d, NCT2->pub_key->X.dmax * 4 ); + DEBUG_PRINT_ARRAY( "EC pub.Y:", (const char *)NCT2->pub_key->Y.d, NCT2->pub_key->Y.dmax * 4 ); +#endif + } + // ECDSA鄂イ蜷堺サ伜刈 +#ifdef ECDSA_SHA256 + u8 sha256Buf[ SHA256_DIGEST_LENGTH ]; + u8 ecdsasig[ 0x80 ]; + const u8 *pECDSAsig = ecdsasig; + ECDSA_SIG *sig = NULL; + int signLen = 0; + int test_ret = 0; + + // CR_DeviceCert縺ョSHA256險育ョ + SHA256( deviceCert.issuerName, (int)&deviceCert + sizeof(CR_DeviceCert) - (int)deviceCert.issuerName, sha256Buf ); + + // 荳贋ス232bit蛻縺ァ鄂イ蜷 + memset( ecdsasig, 0, sizeof(ecdsasig) ); + test_ret = ECDSA_sign( 0, sha256Buf, 32, ecdsasig, &signLen, NCT2 ); +#else // !ECDSA_SHA256 + u8 sha1Buf[ 20 ]; + u8 ecdsasig[ 0x80 ]; + const u8 *pECDSAsig = ecdsasig; + ECDSA_SIG *sig = NULL; + int signLen = 0; + int test_ret = 0; + + // CR_DeviceCert縺ョSHA1險育ョ + SHA1( deviceCert.issuerName, (int)&deviceCert + sizeof(CR_DeviceCert) - (int)deviceCert.issuerName, sha1Buf ); + + // 鄂イ蜷 + memset( ecdsasig, 0, sizeof(ecdsasig) ); + test_ret = ECDSA_sign( 0, sha1Buf, 20, ecdsasig, &signLen, NCT2 ); +#endif // ECDSA_SHA256 + + if (test_ret == 0) { + ret_code = CR_GENID_ERROR_ECDSA_SIGN; + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + DEBUG_PRINT_ARRAY( "ECDSA:", (const char *)ecdsasig, signLen ); + + // DER繝繧ウ繝シ繝峨@縺ヲ縲〉 縺ィ s 繧 eccSignature 縺ォ繧サ繝繝 + sig = d2i_ECDSA_SIG( NULL, &pECDSAsig, signLen ); + if( sig == NULL ) { + ret_code = CR_GENID_ERROR_ECDSA_DEC; + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } +#if 0 + DEBUG_PRINT_ARRAY( "ECDSA.r:", (const char *)sig->r->d, sig->r->dmax * 4); + DEBUG_PRINT_ARRAY( "ECDSA.s:", (const char *)sig->s->d, sig->s->dmax * 4 ); +#endif + + BN2BinWithPadding( sig->r, &deviceCert.eccSignature[ 0 ], 30 ); + BN2BinWithPadding( sig->s, &deviceCert.eccSignature[ 30 ], 30 ); + memcpy( pDevCertSign, &deviceCert.eccSignature, 60 ); + if( sig ) ECDSA_SIG_free( sig ); + if( NCT2 ) EC_KEY_free( NCT2 ); + NCT2 = NULL; + +#endif // USE_HSM + +#ifdef DEBUG_OUTPUT_FILE +#ifdef ECDSA_SHA256 + DebugFileOutput( device_id, "dgst", sha256Buf, 32 ); +#else // !ECDSA_SHA256 + DebugFileOutput( device_id, "dgst", sha1Buf, 20 ); +#endif // ECDSA_SHA256 + DebugFileOutput( device_id, "sign", deviceCert.eccSignature, 60 ); +#endif // DEBUG_OUTPUT_FILE + + // ECDSA鄂イ蜷肴、懆ィシ + { + // bonding_option 縺ォ繧医▲縺ヲ縲骰オ繧貞キョ縺玲崛縺 + const unsigned char *der_pub = bonding_option ? cr_NCT2_pub_dev : cr_NCT2_pub_prod; + int pub_len = der_pub[ 8 ] | der_pub[ 9 ] << 8; // KEY髟キ繧貞叙繧雁コ縺 + der_pub += 0x10; // 繝倥ャ繝驛ィ蛻繧帝勁螟悶@縺ヲKEY螳滉ス薙r謖螳 + + // BIT STRING 縺ョ螳溘ョ繝シ繧ソ驛ィ蛻縺ョ縺ソ繧呈欠螳壹☆繧九h縺隱ソ謨エ + pub_len = der_pub[0x15] - 1; + der_pub += 0x17; + + // ECC蜈ャ髢矩嵯縺ョ隱ュ縺ソ霎シ縺ソ + NCT2 = EC_KEY_new_by_curve_name( NID_sect233r1 ); + if( NCT2 == NULL ) { + SetErrorInfo( __FUNCTION__, __LINE__ ); + ret_code = CR_GENID_ERROR_ECC_KEY_NEW; + goto end; + } + if( o2i_ECPublicKey( &NCT2, &der_pub, pub_len ) == NULL ) { + SetErrorInfo( __FUNCTION__, __LINE__ ); + ret_code = CR_GENID_ERROR_ECC_READ_PUBLIC_KEY; + goto end; + } + + // ECDSA鄂イ蜷搾シDERシ峨r蜀肴ァ狗ッ + u8 signBuf[70]; + int signLen = 66; + memset( signBuf, 0, sizeof( signBuf ) ); + signBuf[0] = 0x30; + signBuf[1] = 0x40; + signBuf[2] = 0x02; + signBuf[3] = 0x1E; + memcpy( &signBuf[4], &deviceCert.eccSignature[0], 0x1E ); + signBuf[0x22] = 0x02; + signBuf[0x23] = 0x1E; + memcpy( &signBuf[0x24], &deviceCert.eccSignature[30], 0x1E ); + DEBUG_PRINT_ARRAY( (char*)"sign(HSM)", (const char *)signBuf, signLen ); + + // 鄂イ蜷阪吶Μ繝輔ぃ繧、 +#ifdef ECDSA_SHA256 + ret_code = ECDSA_verify( 0, sha256Buf, 32, signBuf, signLen, NCT2 ); +#else // !ECDSA_SHA256 + ret_code = ECDSA_verify( 0, sha1Buf, 20, signBuf, signLen, NCT2 ); +#endif // ECDSA_SHA256 + if( ret_code != 1) { + ret_code = CR_GENID_ERROR_ECDSA_VERIFY; + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + } + + ret_code = CR_GENID_SUCCESS; + +#ifdef DEBUG_PRINT + if ( cr_print_flag ) + { + int i; + printf( "deviceCert:\n" ); + printf( "sigType : 0x%08X\n", *(unsigned int*)deviceCert.sigType ); + DEBUG_PRINT_ARRAY( "eccSignature:", (const char *)deviceCert.eccSignature, sizeof(deviceCert.eccSignature) ); + DEBUG_PRINT_ARRAY( "padding0:", (const char *)deviceCert.padding0, sizeof(deviceCert.padding0) ); + printf( "issuerName : " ); + for ( i = 0; i < sizeof(deviceCert.issuerName); i++ ) printf( "%c", deviceCert.issuerName[i] ); + printf( "\n" ); + printf( "keyType : 0x%08X\n", *(unsigned int*)deviceCert.keyType ); + printf( "subject : " ); + + for ( i = 0; i < sizeof(deviceCert.subject); i++ ) printf( "%c", deviceCert.subject[i] ); + printf( "\n" ); + printf( "expiryDate : 0x%08X\n", (unsigned int)deviceCert.expiryDate ); + { + struct tm *tmt; + tmt = gmtime( &deviceCert.expiryDate ); + printf( " GMT:%d-%02d-%02d %02d:%02d:%02d\n", + tmt->tm_year+1900, tmt->tm_mon+1, tmt->tm_mday, tmt->tm_hour, tmt->tm_min, tmt->tm_sec ); + } + DEBUG_PRINT_ARRAY( "eccPubKey :", (const char *)deviceCert.eccPubKey, sizeof(deviceCert.eccPubKey) ); + DEBUG_PRINT_ARRAY( "padding1:", (const char *)deviceCert.padding1, sizeof(deviceCert.padding1) ); + } +#endif // DEBUG_PRINT +#ifdef DEBUG_OUTPUT_FILE + DebugFileOutput( device_id, "crt", (const u8 *)&deviceCert, sizeof(CR_DeviceCert) ); +#endif // DEBUG_OUTPUT_FILE + +end: + if( NCT2 ) EC_KEY_free( NCT2 ); + + return ret_code; +} // generate_CTRCustom_deviceCert + + +// 謖螳咤IGNUM繧偵ヰ繧、繝翫Μ螟画鋤縺励※謖螳壹ヰ繝繝輔ぃ縺ォ蜿ウ隧ー繧√〒繧サ繝繝 +static void BN2BinWithPadding( BIGNUM *pBN, u8 *pDst, int dstLen ) +{ + int i; + int bnBitLen, bnByteLen; + u8 buffer[ 32 ]; + memset( buffer, 0, sizeof(buffer) ); + bnBitLen = BN_num_bits( pBN ); + bnByteLen = ( bnBitLen / 8 ) + ( ( bnBitLen % 8 ) ? 1 : 0 ); + BN_bn2bin( pBN, (u8*)buffer ); + for( i = 0; i < bnByteLen; i++ ) { + pDst[ dstLen - 1 - i ] = buffer[ bnByteLen - 1 - i ]; + } +} diff --git a/tags/20100201_Sharp_Release/cr_enc_id.c b/tags/20100201_Sharp_Release/cr_enc_id.c new file mode 100644 index 0000000..bf8c91f --- /dev/null +++ b/tags/20100201_Sharp_Release/cr_enc_id.c @@ -0,0 +1,382 @@ +/* ==================================================================== + * Copyright (c) 1998-2008 The OpenSSL 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 OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL 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 OpenSSL 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 product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * 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 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 acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS 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 AUTHOR OR 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. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include "cr_generate_id.h" +#include "cr_generate_id_private.h" + +#include +#include +#include +#include +#include +#include +#include + +#ifdef USE_HSM +#include "cr_hsm_code.h" +#else // !USE_HSM +#include +#include + +#include "cr_eFuse_privKey_dev.c" +#include "cr_eFuse_pubKey_dev.c" +#include "cr_eFuse_privKey_prod.c" +#include "cr_eFuse_pubKey_prod.c" + +#include "cr_eFuse_aesKey_dev.c" +#include "cr_eFuse_aesKey_prod.c" + +extern RSA *d2i_RSA_PUBKEY(RSA **a, const unsigned char **pp, long length); + +#endif // USE_HSM + +#include "cr_eFuse_iv_dev.c" +#include "cr_eFuse_iv_prod.c" + +#ifdef ENCRYPT_AES +static int crypto_aes_enc_dec( unsigned char *dst_buf,unsigned char *org_buf, u8 bonding_option ); +#else // !ENCRYPT_AES +static int crypto_rsa_enc_dec( unsigned char *dst_buf,unsigned char *org_buf, u8 bonding_option ); +#endif // ENCRYPT_AES + + +static unsigned char local_buf_1[CR_ID_BUF_SIZE]; +static unsigned char local_buf_2[CR_ID_BUF_SIZE]; + +// ビルドスイッチに従ってAES or RSA で指定バッファを暗号化 +int EncryptID( unsigned char *dst_buf, unsigned char *org_buf, u8 bonding_option ) +{ +#ifdef ENCRYPT_AES +#ifdef DEBUG_PRINT + if( cr_print_flag ) printf( "[AES]\n"); +#endif // DEBUG_PRINT + return crypto_aes_enc_dec( dst_buf, org_buf, bonding_option ); // AES +#else // !ENCRYPT_AES +#ifdef DEBUG_PRINT + if( cr_print_flag ) printf( "[RSA]\n"); +#endif // DEBUG_PRINT + return crypto_rsa_enc_dec( dst_buf, org_buf, bonding_option ); // RSA pubKey enc +#endif // ENCRYPT_AES +} + +#ifdef ENCRYPT_AES + +// AES +#ifdef USE_HSM + +int crypto_aes_enc_dec( unsigned char *dst_buf, unsigned char *org_buf, u8 bonding_option ) +{ + int i; + int ret_code = CR_GENID_SUCCESS; + char *pIV = (char *)( bonding_option ? cr_eFuse_iv_dev : cr_eFuse_iv_prod ) + 0x10; + + // encrypt + ret_code = hsm_aes_encrypt( local_buf_1, org_buf, CR_ID_BUF_SIZE, bonding_option, pIV ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // decyrpt + ret_code = hsm_aes_decrypt( local_buf_2, local_buf_1, CR_ID_BUF_SIZE, bonding_option, pIV ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // ベリファイ + for ( i = 0 ; i < CR_ID_BUF_SIZE ; i++ ) + { + if( org_buf[i] != local_buf_2[i] ) + { + ret_code = CR_GENID_ERROR_AES_VERIFY; + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + } + + memcpy( dst_buf, local_buf_1, CR_ID_BUF_SIZE ); + + return CR_GENID_SUCCESS; +} // hsm_crypto_aes_enc_dec + +#else // !USE_HSM + +int crypto_aes_enc_dec( unsigned char *dst_buf, unsigned char *org_buf, u8 bonding_option ) +{ + int i; + AES_KEY aesEncKey; + AES_KEY aesDecKey; + u8 temp_iv[16]; + // 鍵データ取り出し。(ヘッダ部分0x10を除去。) + char *pAesKey = (char *)( bonding_option ? cr_eFuse_aesKey_dev : cr_eFuse_aesKey_prod ) + 0x10; + char *pIV = (char *)( bonding_option ? cr_eFuse_iv_dev : cr_eFuse_iv_prod ) + 0x10; + + memset( local_buf_1, 0, CR_ID_BUF_SIZE ); + memset( local_buf_2, 0, CR_ID_BUF_SIZE ); + + if ( AES_set_encrypt_key( pAesKey, 128, &aesEncKey ) != 0 ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return CR_GENID_ERROR_AES_ENC; + } + + if ( AES_set_decrypt_key( pAesKey, 128, &aesDecKey ) != 0 ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return CR_GENID_ERROR_AES_DEC; + } + + memcpy( temp_iv, pIV, 16 ); + AES_cbc_encrypt ( org_buf, local_buf_1, CR_ID_BUF_SIZE, &aesEncKey, temp_iv, AES_ENCRYPT ); + + memcpy( temp_iv, pIV, 16 ); + AES_cbc_encrypt ( local_buf_1, local_buf_2, CR_ID_BUF_SIZE, &aesDecKey, temp_iv, AES_DECRYPT ); + + // ベリファイ + for ( i = 0 ; i < CR_ID_BUF_SIZE ; i++ ) + { + if( org_buf[i] != local_buf_2[i] ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return CR_GENID_ERROR_AES_VERIFY; + } + } + + memcpy( dst_buf, local_buf_1, CR_ID_BUF_SIZE ); + + return CR_GENID_SUCCESS; +} // crypto_aes_enc_dec + +#endif // USE_HSM + +#else // !ENCRYPT_AES + +// RSA +#ifdef USE_HSM + +int crypto_rsa_enc_dec( unsigned char *dst_buf,unsigned char *org_buf, u8 bonding_option ) +{ + int i; + int ret_code = CR_GENID_SUCCESS; + + // encrypt + ret_code = hsm_rsa_encrypt( local_buf_1, org_buf, CR_ID_BUF_SIZE, bonding_option ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // decyrpt + ret_code = hsm_rsa_decrypt( local_buf_2, local_buf_1, CR_ID_BUF_SIZE, bonding_option ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // ベリファイ + for ( i = 0 ; i < CR_ID_BUF_SIZE ; i++ ) + { + if( org_buf[i] != local_buf_2[i] ) + { + ret_code = CR_GENID_ERROR_RSA_VERIFY; + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + } + + memcpy( dst_buf, local_buf_1, CR_ID_BUF_SIZE ); + + return CR_GENID_SUCCESS; +} // hsm_crypto_rsa_enc_dec + +#else // USE_HSM + +int crypto_rsa_enc_dec( unsigned char *dst_buf,unsigned char *org_buf, u8 bonding_option ) +{ + int ret_code = CR_GENID_SUCCESS; + int rsa_outlen = 0; + RSA *rsa_privkey = NULL; + RSA *rsa_pubkey = NULL; + + memset(local_buf_1, 0,CR_ID_BUF_SIZE); + memset(local_buf_2, 0,CR_ID_BUF_SIZE); + + // DERフォーマットのRSA鍵を読み込み + { + // bonding_option によって、鍵を差し替え + const unsigned char *der_priv = bonding_option ? cr_eFuse_privKey_dev : cr_eFuse_privKey_prod; + const unsigned char *der_pub = bonding_option ? cr_eFuse_pubKey_dev : cr_eFuse_pubKey_prod; + int priv_len = der_priv[ 8 ] | der_priv[ 9 ] << 8; // KEY長を取り出し + int pub_len = der_pub [ 8 ] | der_pub [ 9 ] << 8; // 同上 + der_priv += 0x10; // ヘッダ部分を除外してKEY実体を指定 + der_pub += 0x10; // 同上 + // コマンドラインのopensslが出力する秘密鍵は、PKCS#1 RSAPublicKeyフォーマットなので、この関数を使う。 + rsa_privkey = d2i_RSAPrivateKey( NULL, &der_priv, priv_len ); + if( rsa_privkey == NULL ) { + ret_code = CR_GENID_ERROR_RSA_READ_PRIVATE_KEY; + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + // コマンドラインのopensslが出力する公開鍵は、SubjectPublicKeyInfo形式なので、この関数を使う。 + rsa_pubkey = d2i_RSA_PUBKEY( NULL, &der_pub, pub_len ); + if( rsa_pubkey == NULL ) { + ret_code = CR_GENID_ERROR_RSA_READ_PUBLIC_KEY; + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + } + + if( (rsa_outlen = RSA_private_encrypt(CR_ID_BUF_SIZE, org_buf, local_buf_1, + rsa_privkey, RSA_NO_PADDING)) == -1) { + ret_code = CR_GENID_ERROR_RSA_ENC; + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + else { + if((rsa_outlen = RSA_public_decrypt(rsa_outlen, local_buf_1, local_buf_2, + rsa_pubkey, RSA_NO_PADDING)) == -1) { + ret_code = CR_GENID_ERROR_RSA_DEC; + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + else { + int i; + int error_flag = 0; + for( i = 0 ; i < CR_ID_BUF_SIZE ; i++ ) { + if( org_buf[i] != local_buf_2[i] ) { + error_flag++; + } + } + if( error_flag ) { + ret_code = CR_GENID_ERROR_RSA_VERIFY; + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + } + } + + memcpy(dst_buf,local_buf_1,CR_ID_BUF_SIZE); + +end: + if ( rsa_privkey ) RSA_free( rsa_privkey ); + if ( rsa_pubkey ) RSA_free( rsa_pubkey ); + + return ret_code; +} + +#endif // !USE_HSM + +#endif // ENCRYPT_AES diff --git a/tags/20100201_Sharp_Release/cr_generate_id.c b/tags/20100201_Sharp_Release/cr_generate_id.c new file mode 100644 index 0000000..6ecf7b1 --- /dev/null +++ b/tags/20100201_Sharp_Release/cr_generate_id.c @@ -0,0 +1,441 @@ +/* ==================================================================== + * Copyright (c) 1998-2008 The OpenSSL 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 OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL 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 OpenSSL 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 product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * 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 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 acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS 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 AUTHOR OR 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. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include +#include +#include +#include +#include +#include + +#ifdef USE_HSM +#include "cr_hsm_code.h" +#include "cr_hsm_alloc.h" // temp +#endif // USE_HSM +// openssl +#include +#include + +#include "cr_generate_id.h" +#include "cr_generate_id_private.h" +#include "cr_alloc.h" + +// 繝薙Ν繝画凾縺ョ譌・譎りィ倬鹸 +static struct +{ + const u8 *title; const u8 *date; const u8 *time; +} +buildInfo = { "LIBGENID_BUILD_INFO:", __DATE__, __TIME__ }; + +static u64 generatingCount = 0; // 迴セ蝨ィ逕滓蝉クュ縺ョID(襍キ蜍墓凾縺九i縺ョ騾夂ョ) + +int cr_print_flag = 0; + +// generate_id髢「謨ー縺ョ繧、繝九す繝」繝ゥ繧、繧コ +int cr_generate_id_initialize( u8 err_buf[CR_ID_BUF_SIZE] ) +{ + int ret_code = CR_GENID_SUCCESS; + + // 繝薙Ν繝画ュ蝣ア縺後ョ繝繝峨せ繝医Μ繝繝励&繧後↑縺繧医≧蜿らァ + const u8 *dummyPtr = NULL; + dummyPtr = buildInfo.title; + dummyPtr = NULL; + + // 逕滓舌き繧ヲ繝ウ繧ソ縺ョ蛻晄悄蛹 + generatingCount = 0; + + // init for error info + InitErrorInfo(); + + // OpenSSL 縺ョ繝。繝「繝ェ繝ェ繝シ繧ッ髦イ豁「縺ョ縺溘a縲√が繝ェ繧ク繝翫Ν縺ョ繧「繝ュ繧ア繝シ繧ソ繧剃スソ逕ィ縲 + if ( CRYPTO_set_mem_functions( cr_mem_malloc, cr_mem_realloc, cr_mem_free ) != 1 ) + { + CR_ERR_BUFFER *cr_err_buf = (CR_ERR_BUFFER *)err_buf; + memset( cr_err_buf, 0, sizeof( CR_ERR_BUFFER ) ); + cr_err_buf->errorCode = CR_GENID_ERROR_SET_MEM_FUNCTIONS; + GetErrorInfo( cr_err_buf->callStack, &cr_err_buf->recordSize ); +#ifdef DEBUG_PRINT + printf( "error(%d), CALL_STACK : %s\n", (int)cr_err_buf->errorCode, cr_err_buf->callStack ); +#endif + return CR_GENID_FAILED; + } + +#ifdef USE_HSM + ret_code = hsm_initialize(); + if ( ret_code != CR_GENID_SUCCESS ) + { + CR_ERR_BUFFER *cr_err_buf = (CR_ERR_BUFFER *)err_buf; + memset( cr_err_buf, 0, sizeof( CR_ERR_BUFFER ) ); + cr_err_buf->errorCode = ret_code; + GetErrorInfo( cr_err_buf->callStack, &cr_err_buf->recordSize ); +#ifdef DEBUG_PRINT + printf( "error(%d), CALL_STACK : %s\n", (int)cr_err_buf->errorCode, cr_err_buf->callStack ); +#endif + return CR_GENID_FAILED; + } +#endif + + return ret_code; +} // cr_generate_id_initialize + + +// generate_id髢「謨ー縺ョ繝輔ぃ繧、繝翫Λ繧、繧コ +int cr_generate_id_finalize( u8 err_buf[CR_ID_BUF_SIZE] ) +{ + int ret_code = CR_GENID_SUCCESS; + + // init for error info + InitErrorInfo(); + + // HSM +#ifdef USE_HSM + ret_code = hsm_finalize(); + if ( ret_code != CR_GENID_SUCCESS ) + { + CR_ERR_BUFFER *cr_err_buf = (CR_ERR_BUFFER *)err_buf; + memset( cr_err_buf, 0, sizeof( CR_ERR_BUFFER ) ); + cr_err_buf->errorCode = ret_code; + GetErrorInfo( cr_err_buf->callStack, &cr_err_buf->recordSize ); +#ifdef DEBUG_PRINT + printf( "error(%d), CALL_STACK : %s\n", (int)cr_err_buf->errorCode, cr_err_buf->callStack ); +#endif + } +#endif // USE_HSM + + return ret_code; +} // cr_generate_id_finalize + +// generate_id 髢「謨ー +int cr_generate_id( u32 device_id[CR_NUM_OF_DEVICEID], u8 id_buf[CR_ID_BUF_SIZE], u8 bonding_option ) +{ + int i; + int ret_code = CR_GENID_SUCCESS; + CR_ID_BUFFER *cr_id_buf; + EC_KEY *deviceKeyPair = NULL; + + // 繧ィ繝ゥ繝シ逋コ逕滓凾縺ォ蛯吶∴縺ヲ縲√お繝ゥ繝シ繝舌ャ繝輔ぃ縺ョ蛻晄悄蛹悶→繝医シ繧ソ繝ォ縺ョID逕滓舌き繧ヲ繝ウ繝医そ繝繝 + InitErrorInfo(); + generatingCount++; + +#ifdef DEBUG_PRINT + if( sizeof(CR_ID_BUFFER) != 256 ) { + printf( "CR_ID_BUFFER size error. %d\n", sizeof(CR_ID_BUFFER) ); + } + if( sizeof(CR_ERR_BUFFER) != 256 ) { + printf( "CR_ERR_BUFFER size error. %d\n", sizeof(CR_ERR_BUFFER) ); + } +#endif + + //-------------------------------------------------------------- + // 證怜捷蜃ヲ逅蛻晄悄蛹 + //-------------------------------------------------------------- + cr_mem_bufmgr_initialize(); + +#ifdef MY_CRYPTO_DEBUG + ERR_load_crypto_strings(); +#endif /* MY_CRYPTO_DEBUG */ + + + // 繝繧、繧ク繧ァ繧ケ繝医い繝ォ繧エ繝ェ繧コ繝繧定ソス蜉縺吶k + OpenSSL_add_all_digests(); + + //-------------------------------------------------------------- + // FuseID繝舌ャ繝輔ぃ縺ォ蝗コ螳壹ョ繝シ繧ソ繧サ繝繝 + //-------------------------------------------------------------- + memset(id_buf, 0, CR_ID_BUF_SIZE); + + cr_id_buf = (CR_ID_BUFFER *)id_buf; + cr_id_buf->magic_number = CR_GEN_ID_MAGICCODE; // HSM菴ソ逕ィシ乗悴菴ソ逕ィ縺ァ繝槭ず繝繧ッ繧ウ繝シ繝峨′螟峨o繧九 + cr_id_buf->version = CR_GEN_ID_VERSION; + + //-------------------------------------------------------------- + // 蠑墓焚縺ョ繝懊Φ繝繧」繝ウ繧ー繧ェ繝励す繝ァ繝ウ繧偵そ繝繝 + //-------------------------------------------------------------- + cr_id_buf->bonding_option = bonding_option; + + //-------------------------------------------------------------- + // device_id 繧サ繝繝 + //-------------------------------------------------------------- + for( i = 0 ; i < CR_NUM_OF_DEVICEID ; i++ ) { + cr_id_buf->device_id[i] = device_id[i]; /* device_id[0] => ec priv key */ + } + +#ifdef DEBUG_PRINT + if( cr_print_flag ) { + printf("device_id:\n"); + printf(" 0x%08x\n", (unsigned int)device_id[0] ); + printf(" 0x%08x%08x\n", (unsigned int)device_id[2], (unsigned int)device_id[1] ); + printf(" 0x%08x%08x\n", (unsigned int)device_id[4], (unsigned int)device_id[3] ); + printf("\n"); + } +#endif /* DEBUG_PRINT */ + + //-------------------------------------------------------------- + // 繧ソ繧、繝繧ケ繧ソ繝ウ繝励そ繝繝 + //-------------------------------------------------------------- + ret_code = GetTimestamp( &cr_id_buf->year, + &cr_id_buf->month, + &cr_id_buf->mday, + &cr_id_buf->hour, + &cr_id_buf->min, + &cr_id_buf->sec, + &cr_id_buf->expiryDate ); // 繝繝舌う繧ケ險シ譏取嶌譛滄剞縺ョ蜈繝繝シ繧ソ繧ゅ▽縺縺ァ縺ォ繧サ繝繝医@縺ヲ縺翫¥ + if ( ret_code != CR_GENID_SUCCESS ) { + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + + //-------------------------------------------------------------- + // 荵ア謨ー繧堤函謌舌@縺ヲ繧サ繝繝 + //-------------------------------------------------------------- + ret_code = GenerateRandom( cr_id_buf->random, CR_RANDOM_LENGTH ); + if ( ret_code != CR_GENID_SUCCESS ) { + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + DEBUG_PRINT_ARRAY( "rand:", (const char *)cr_id_buf->random, CR_RANDOM_LENGTH ); + + //-------------------------------------------------------------- + // 讌募譖イ邱夐嵯繝壹い繧堤函謌 + //-------------------------------------------------------------- + ret_code = GenarateECCKeyPair( &deviceKeyPair, cr_id_buf->devicePrivKey ); + if ( ret_code != CR_GENID_SUCCESS ) { + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + + //-------------------------------------------------------------- + // 逕滓舌@縺滄嵯繝壹い繧脱CDSA縺ァ蜍穂ス懃「コ隱 + //-------------------------------------------------------------- + ret_code = TestECDSA( deviceKeyPair ); + if ( ret_code != CR_GENID_SUCCESS ) { + goto end; + } + + //-------------------------------------------------------------- + // 繝繝舌う繧ケ險シ譏取嶌逕滓 + 鄂イ蜷阪ョ莉倅ク + 險シ譏取嶌譛滄剞繧サ繝繝 + //-------------------------------------------------------------- + ret_code = GenerateCTRDeviceCert( deviceKeyPair, + cr_id_buf->device_id[0], + cr_id_buf->bonding_option, + cr_id_buf->deviceCertSign, + &cr_id_buf->expiryDate ); + if ( ret_code != CR_GENID_SUCCESS ) { + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + +#if 0 + DEBUG_PRINT_ARRAY( "deviceCertSign:", (const char *)cr_id_buf->deviceCertSign, ECDSA_SIGN_LENGTH ); +#endif + + //-------------------------------------------------------------- + // FuseID繝舌ャ繝輔ぃ蜈ィ菴薙ョSHA256繝上ャ繧キ繝・繧堤ョ怜コ縺励※繧サ繝繝 + //-------------------------------------------------------------- + SHA256(id_buf, CR_ID_BUF_SIZE - SHA256_DIGEST_LENGTH, cr_id_buf->hash); + DEBUG_PRINT_ARRAY( "SHA256 Digest:", (const char *)cr_id_buf->hash, SHA256_DIGEST_LENGTH ); + + //-------------------------------------------------------------- + // FuseID RAW繝繝シ繧ソ螳梧 + //-------------------------------------------------------------- + DEBUG_PRINT_ARRAY( "RAW eFuseID:", (const char *)id_buf, CR_ID_BUF_SIZE ); +#ifdef DEBUG_OUTPUT_FILE + DebugFileOutput( device_id[ 0 ], "raw", id_buf, CR_ID_BUF_SIZE ); +#endif // DEBUG_OUTPUT_FILE + + //-------------------------------------------------------------- + // FuseID繝舌ャ繝輔ぃ蜈ィ菴薙rAES or RSA縺ァ證怜捷蛹 + //-------------------------------------------------------------- + ret_code = EncryptID( id_buf, id_buf, bonding_option ); + if( ret_code != CR_GENID_SUCCESS ) { + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + + DEBUG_PRINT_ARRAY( "ENC eFuseID:", (const char *)id_buf, CR_ID_BUF_SIZE ); +#ifdef DEBUG_OUTPUT_FILE + DebugFileOutput( device_id[ 0 ], "enc", id_buf, CR_ID_BUF_SIZE ); +#endif // DEBUG_OUTPUT_FILE + + //-------------------------------------------------------------- + // 邨ゆコ蜃ヲ逅 + //-------------------------------------------------------------- +end: + + /* id_buf[]縺ォ繧ィ繝ゥ繝シ繝ュ繧ー繧呈嶌縺崎セシ繧縲 */ + if ( ret_code != CR_GENID_SUCCESS ) + { + CR_ERR_BUFFER *cr_err_buf = (CR_ERR_BUFFER *)id_buf; + memset( cr_err_buf, 0, sizeof( CR_ERR_BUFFER ) ); + cr_err_buf->totalCount = generatingCount; + cr_err_buf->magic_number = 0x01234567; + cr_err_buf->device_id0 = device_id[0]; + cr_err_buf->errorCode = ret_code; + GetErrorInfo( cr_err_buf->callStack, &cr_err_buf->recordSize ); + cr_err_buf->bonding_option = bonding_option; +#ifdef DEBUG_PRINT + printf( "CALL_STACK : %s\n", cr_err_buf->callStack ); +#endif + } + + // 繝ェ繧ス繝シ繧ケ縺ョ隗」謾セ + if ( deviceKeyPair ) EC_KEY_free( deviceKeyPair ); + + ERR_remove_state(0); + EVP_cleanup(); + CRYPTO_cleanup_all_ex_data(); + +#ifdef MY_CRYPTO_DEBUG + ERR_free_strings(); +#endif /* MY_CRYPTO_DEBUG */ + +#if 0 + if ( cr_print_flag ) + { + printf( "hsm alloc counter : %d\n", my_hsm_get_alloc_counter() ); + printf( "hsmbn alloc counter : %d\n", my_bignum_get_alloc_counter() ); + printf( "miya alloc counter : %d\n", cr_mem_get_counter() ); + } +#endif + + return ret_code; /* success */ +} + + +#ifdef DEBUG_PRINT +void DebugPrintArray( char *pStr, const u8 *pData, int length ) +{ + int i; + if( cr_print_flag ) { + printf( "%s", pStr ); + for( i = 0 ; i < length; i++ ) { + if( (i % 16) == 0 ) printf("\n "); + printf("%02X ", pData[ i ] ); + } + printf("\n"); + } +} +#endif + +void DebugFileOutput( u32 device_id, char *pSuffix, const u8 *pSrc, int length ) +{ + if ( cr_print_flag ) + { + // 險シ譏取嶌縺ョ譖ク縺崎セシ縺ソ繝繧ケ繝 + FILE *fp; + char fn[256]; + sprintf( fn, "output/0x%08x.%s", (unsigned int)device_id, pSuffix ); + fp = fopen( fn, "wb" ); + fwrite( pSrc, length, 1, fp ); + fclose( fp ); + } +} diff --git a/tags/20100201_Sharp_Release/cr_generate_id.h b/tags/20100201_Sharp_Release/cr_generate_id.h new file mode 100644 index 0000000..59fd4fe --- /dev/null +++ b/tags/20100201_Sharp_Release/cr_generate_id.h @@ -0,0 +1,160 @@ +/* ==================================================================== + * Copyright (c) 1998-2008 The OpenSSL 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 OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL 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 OpenSSL 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 product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * 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 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 acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS 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 AUTHOR OR 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. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#ifndef _CR_GENERATE_ID_H_ +#define _CR_GENERATE_ID_H_ + +// 成功 or 失敗 (詳細はエラーバッファに格納される) +#define CR_GENID_SUCCESS ( 0) +#define CR_GENID_FAILED ( 1) + +#ifdef __cplusplus +extern "C" { +#endif + +typedef signed char s8; +typedef unsigned char u8; +typedef unsigned short u16; +typedef signed long s32; +typedef unsigned long u32; +typedef unsigned long long u64; + +#define CR_ID_BUF_SIZE (2048/8) +#define CR_NUM_OF_DEVICEID 5 + +/* + device_id と 実際のID との関係は、下記のようになっています。 + ID0 = device_id[ 0 ] + ID1 = device_id[ 1 ] | ( device_id[ 2 ] << 32 ) + ID2 = device_id[ 3 ] | ( device_id[ 4 ] << 32 ) +*/ + +// eFuseID 仕様 +#define CR_ID0_BIT_NUM 32 +#define CR_ID1_BIT_NUM 34 +#define CR_ID2_BIT_NUM 64 +#define CR_ID0_MASK 0xFFFFFFFF // 32bit +#define CR_ID1_MASK 0x00000003FFFFFFFFll // 34bit +#define CR_ID2_MASK 0xFFFFFFFFFFFFFFFFll // 64bit + +extern int cr_generate_id_initialize( u8 err_buf[CR_ID_BUF_SIZE] ); +extern int cr_generate_id( u32 device_id[CR_NUM_OF_DEVICEID], u8 id[CR_ID_BUF_SIZE], u8 bonding_option ); +extern int cr_generate_id_finalize( u8 err_buf[CR_ID_BUF_SIZE] ); + +extern int cr_print_flag; + +#ifdef __cplusplus +} +#endif + + +#endif /* _CR_GENERATE_ID_H_ */ + diff --git a/tags/20100201_Sharp_Release/cr_generate_id_private.h b/tags/20100201_Sharp_Release/cr_generate_id_private.h new file mode 100644 index 0000000..a838f6e --- /dev/null +++ b/tags/20100201_Sharp_Release/cr_generate_id_private.h @@ -0,0 +1,234 @@ +/* ==================================================================== + * Copyright (c) 1998-2008 The OpenSSL 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 OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL 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 OpenSSL 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 product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * 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 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 acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS 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 AUTHOR OR 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. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#ifndef _CR_GENERATE_ID_PRIVATE_H_ +#define _CR_GENERATE_ID_PRIVATE_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef USE_HSM +// nShield +#include "nfastapp.h" +#include "nfkm.h" +#include "rqcard-applic.h" +#include "rqcard-fips.h" +#endif // USE_HSM + +#include +#include +#include +#include "ec_lcl.h" // EC_KEY (=ec_key_st) 構造体の参照に必要 + +#ifdef DEBUG_PRINT +#define DEBUG_PRINT_ARRAY DebugPrintArray +#else // !DEBUG_PRINT +#define DEBUG_PRINT_ARRAY( ... ) ((void)0) +#endif // DEBUG_PRINT + +#define ENCRYPT_AES 1 // 定義を有効でFIX.(これが未定義の場合、IDの暗号化がRSAになる。) + +#define CR_GEN_ID_VERSION 4 // シャープへのリリースごとにUPする。 + // 2010/02/01 Release ver.4 +#ifdef USE_HSM +#define CR_GEN_ID_MAGICCODE 0xdeadb00f; /* 最終的にはこちらで動作。0xdeadbeefにするとRSAでコケる。 */ +#else // !USE_HSM +#define CR_GEN_ID_MAGICCODE 0xabadf00d; +#endif // USE_HSM +#define CR_RANDOM_LENGTH 0x50 +#define EC_PRIVATE_KEY_LENGTH 0x20 +#define ECDSA_SIGN_LENGTH 0x3C +#define CR_RSV_LENGTH 0x10 +#define EC_CURVE_NAME NID_sect233r1 + +//--------------------------------------------------- +// OpenSSLの処理結果によるエラーコード +//--------------------------------------------------- +#define CR_GENID_ERROR_BN_NEW ( -1) +#define CR_GENID_ERROR_ECC_KEY_NEW ( -2) +#define CR_GENID_ERROR_ECC_GENERATE_PRIVATE_KEY ( -3) +#define CR_GENID_ERROR_ECC_GENERATE_PUBLIC_KEY ( -4) +#define CR_GENID_ERROR_ECC_READ_PRIVATE_KEY ( -5) +#define CR_GENID_ERROR_ECC_READ_PUBLIC_KEY ( -6) +#define CR_GENID_ERROR_ECDSA_SIGN ( -7) +#define CR_GENID_ERROR_ECDSA_DEC ( -8) +#define CR_GENID_ERROR_ECDSA_VERIFY ( -9) +#define CR_GENID_ERROR_AES_ENC (-10) +#define CR_GENID_ERROR_AES_DEC (-11) +#define CR_GENID_ERROR_AES_VERIFY (-12) +#define CR_GENID_ERROR_RSA_READ_PRIVATE_KEY (-13) +#define CR_GENID_ERROR_RSA_READ_PUBLIC_KEY (-14) +#define CR_GENID_ERROR_RSA_ENC (-15) +#define CR_GENID_ERROR_RSA_DEC (-16) +#define CR_GENID_ERROR_RSA_VERIFY (-17) +#define CR_GENID_ERROR_SET_MEM_FUNCTIONS (-18) + +typedef struct { + u32 magic_number; /* 0x00 - 0x03 = 0xdeadb00f 確定!*/ + u32 device_id[CR_NUM_OF_DEVICEID]; /* 0x04 - 0x07 32bit device ID + (32bit。1固定カウントアップ。) + (本ID+randomの先頭0x1C bytesを組み合わせて、デバイス秘密鍵とする。) + 0x08 - 0x0F 64bit CTR番号 seed + (34bitのみ使用。1〜4の乱数カウントアップ) + 0x10 - 0x17 64bit 予備ID + (64bitフルに使用。1〜0x100000000の乱数カウントアップ) + */ + u8 version; /* 0x18 = CR_GEN_ID_VERSION */ + u8 bonding_option; /* 0x19 ボンディングオプション */ + u8 year; /* 0x1A デバイス証明書発行時間 (HSMから取得) */ + u8 month; /* 0x1B */ + u8 mday; /* 0x1C */ + u8 hour; /* 0x1D */ + u8 min; /* 0x1E */ + u8 sec; /* 0x1F */ + u32 expiryDate; /* 0x20 - 0x23 デバイス証明書期限 seconds from the Epoch (Jan 1, 1970 00:00) as a 32 bit */ + u8 devicePrivKey[ EC_PRIVATE_KEY_LENGTH ]; + /* 0x24 - 0x43 ECC233 private key (big endian) ユニーク性保証なし */ + u8 deviceCertSign[ ECDSA_SIGN_LENGTH ]; + /* 0x44 - 0x7F ECC233 ECDSA signature (big endian) */ + u8 reserved[ CR_RSV_LENGTH ]; /* 0x80 - 0x8F 予約 */ + u8 random[ CR_RANDOM_LENGTH ]; /* 0x90 - 0xDF 乱数 */ + u8 hash[ SHA256_DIGEST_LENGTH ]; /* 0xE0 - 0xFF "0x00-0xDF"領域のSHA256ハッシュ */ +} CR_ID_BUFFER; /* 合計256bytes = 2048bit */ + +#define CALL_STACK_SIZE (234) +typedef struct { + u64 totalCount; /* 0x00 - 0x07 */ + u32 magic_number; /* 0x08 - 0x0b 0x01234567 確定!*/ + u32 device_id0; /* 0x0c - 0x0f */ + s32 errorCode; /* 0x10 - 0x13 */ + u8 bonding_option; + u8 recordSize; // コールスタックの記録サイズ + u8 callStack[ CALL_STACK_SIZE ]; +} CR_ERR_BUFFER; + +extern int GetTimestamp( u8 *pYear, u8 *pMonth, u8 *pMday, u8 *pHour, u8 *pMin, u8 *pSec, time_t *pTime); +extern int GenerateRandom( u8 *pDst, int length ); +extern int GenarateECCKeyPair( EC_KEY **ppECkey, u8 *pECPrivkey ); + +extern void InitErrorInfo( void ); +extern void SetErrorInfo( const char *funcName, u32 line ); +extern void GetErrorInfo( char *stack, u8 *size ); + +extern int TestECDSA( EC_KEY *pECkey ); +extern int GenerateCTRDeviceCert( EC_KEY *pECkey, u32 device_id, u8 bonding_option, u8 *pDevCertSign, u32 *pExpiryDate ); +extern int EncryptID( unsigned char *dst_buf, unsigned char *org_buf, u8 bonding_option ); +extern void DebugPrintArray( char *pStr, const u8 *pData, int length ); +extern void DebugFileOutput( u32 device_id, char *pSuffix, const u8 *pSrc, int length ); + +#ifdef __cplusplus +} +#endif + + +#endif /* _CR_GENERATE_ID_PRIVATE_H_ */ + diff --git a/tags/20100201_Sharp_Release/cr_hsm_alloc.c b/tags/20100201_Sharp_Release/cr_hsm_alloc.c new file mode 100644 index 0000000..5ded3df --- /dev/null +++ b/tags/20100201_Sharp_Release/cr_hsm_alloc.c @@ -0,0 +1,62 @@ +/* +* my_hsm_alloc.c +*/ + +#include +#include +#include +#include +#include +#include + +#ifdef USE_HSM + +#include "nfastapp.h" +#include "nfutil.h" +#include "cr_hsm_alloc.h" + +/* --------------------- */ + +static int alloc_counter = 0; + +/* --------------------- */ + +const NFast_MallocUpcalls my_hsm_malloc_upcalls = +{ + my_hsm_malloc, my_hsm_realloc, my_hsm_free +}; + +/* --------------------- */ + +void *my_hsm_malloc( size_t nbytes, + struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx ) +{ + alloc_counter++; + return malloc( nbytes ); +} + +/* --------------------- */ + +void *my_hsm_realloc( void *ptr, size_t nbytes, + struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx ) +{ + return realloc( ptr, nbytes ); +} + +/* --------------------- */ + +void my_hsm_free( void *ptr, + struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx ) +{ + free( ptr ); + alloc_counter--; +} + +/* --------------------- */ + +int my_hsm_get_alloc_counter( void ) +{ + return alloc_counter; +} + +#endif // HSM diff --git a/tags/20100201_Sharp_Release/cr_hsm_alloc.h b/tags/20100201_Sharp_Release/cr_hsm_alloc.h new file mode 100644 index 0000000..74e09f9 --- /dev/null +++ b/tags/20100201_Sharp_Release/cr_hsm_alloc.h @@ -0,0 +1,32 @@ +/* +* cr_hsm_alloc.h +*/ + +#ifndef CR_HSM_ALLOC_H +#define CR_HSM_ALLOC_H + +#include "nfastapp.h" + +#ifdef __cplusplus +extern "C" { +#endif + +extern const NFast_MallocUpcalls my_hsm_malloc_upcalls; + +void *my_hsm_malloc( size_t nbytes, + struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx ); + +void *my_hsm_realloc( void *ptr, size_t nbytes, + struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx ); + +void my_hsm_free( void *ptr, + struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx ); + +int my_hsm_get_alloc_counter( void ); + +#ifdef __cplusplus +} +#endif + +#endif // CR_HSM_ALLOC_H + diff --git a/tags/20100201_Sharp_Release/cr_hsm_bignum.c b/tags/20100201_Sharp_Release/cr_hsm_bignum.c new file mode 100644 index 0000000..3df76da --- /dev/null +++ b/tags/20100201_Sharp_Release/cr_hsm_bignum.c @@ -0,0 +1,416 @@ +/* +* SIMPLEBIGNUM.C +* +* Simple bignumber upcalls +* +* This example source code is provided for your information and +* assistance. See the file LICENCE.TXT for details and the +* terms and conditions of the licence which governs the use of the +* source code. By using such source code you will be accepting these +* terms and conditions. If you do not wish to accept these terms and +* conditions, DO NOT OPEN THE FILE OR USE THE SOURCE CODE. +* +* Note that there is NO WARRANTY. +* +* Copyright 2001 - 2002 nCipher Corporation Limited. +*/ + +#include +#include +#include +#include +#include +#include + +#ifdef USE_HSM + +#include "nfastapp.h" +#include "nfutil.h" +#include "cr_hsm_bignum.h" + +/* --------------------- */ + +// original : nfutil_copybytes ( nfutil.c ) +static void my_bignum_copybytes ( unsigned char *dst, const unsigned char *src, + unsigned nbytes, int swapends, int swapwords ) +{ + int inc; + unsigned nwords; + + /* Copies dst to src, swapping endianness and/or word order. dst and src mustn't overlap! */ + + assert( (nbytes & 3)==0 ); /* Must be whole number of M_Words */ + + if ( !swapends && !swapwords ) + { + memcpy(dst, src, nbytes); + return; + } + + if ( swapwords ) + { + dst += (nbytes-4); + inc=-4; + } + else + inc=4; + + nwords = nbytes>>2; + + if ( swapends ) + { + while ( nwords-- > 0 ) + { + dst[0]=src[3]; + dst[1]=src[2]; + dst[2]=src[1]; + dst[3]=src[0]; + dst += inc; + src += 4; + } + } + else + { + while ( nwords-- > 0 ) + { + dst[0]=src[0]; + dst[1]=src[1]; + dst[2]=src[2]; + dst[3]=src[3]; + dst += inc; + src += 4; + } + } +} + +/* --------------------- */ + +int my_bignumreceiveupcall(struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx, + M_Bignum *bignum, int nbytes, + const void *source, + int msbitfirst, int mswordfirst) +{ + struct NFast_Bignum *pBN; + + if ( nbytes > MAXBIGNUMBITS/8 ) return Status_OutOfRange; + assert( (nbytes & 3)==0 ); + + pBN = (struct NFast_Bignum *)NFastApp_Malloc(app, sizeof(struct NFast_Bignum), cctx, tctx); + if ( !pBN ) return NOMEM; + + my_bignum_copybytes(pBN->bytes, (const unsigned char *)source, + nbytes, 0, 0); + + pBN->msb_first = msbitfirst; + pBN->msw_first = mswordfirst; + pBN->nbytes=nbytes; + *bignum=pBN; + return Status_OK; +} + +/* --------------------- */ + +int my_bignumsendlenupcall(struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx, + const M_Bignum *bignum, int *nbytes_r) +{ + assert( ((*bignum)->nbytes & 3)==0 ); + *nbytes_r= (*bignum)->nbytes; + return Status_OK; +} + +/* --------------------- */ + +int my_bignumsendupcall(struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx, + const M_Bignum *bignum, int nbytes, + void *dest, int msbitfirst, int mswordfirst) +{ + int swapends, swapwords; + struct NFast_Bignum *pBN = *bignum; + + assert( pBN->nbytes==nbytes ); + + /* Is format which we're sending in the same as that of the + bignumber? + (NB '!' used to constrain result to 0,1 range) + If not, work out which ends to swap. + */ + + swapends = (!msbitfirst) ^ (!pBN->msb_first); + swapwords = (!mswordfirst) ^ (!pBN->msw_first); + my_bignum_copybytes( (unsigned char *)dest, (*bignum)->bytes, nbytes, + swapends, swapwords ); + return Status_OK; +} + +/* --------------------- */ + +void my_bignumfreeupcall(struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx, + M_Bignum *bignum) +{ + NFastApp_Free(app, (*bignum), cctx, tctx); + *bignum=NULL; +} + +/* --------------------- */ + +int my_bignumformatupcall(struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx, + int *msbitfirst_io, int *mswordfirst_io) +{ + /* Send to the module in little-endian format. + (This is not officially necessary. However, some + versions of the monitor (Maintenance mode) don't accept + big-endian bignums due to a bug) */ + *msbitfirst_io=0; + *mswordfirst_io=0; + return Status_OK; +} + +NFast_BignumUpcalls my_upcalls = { + my_bignumreceiveupcall, + my_bignumsendlenupcall, + my_bignumsendupcall, + my_bignumfreeupcall, + my_bignumformatupcall +}; + +/* --------------------- */ + +static int char2hex ( char c ) +{ + if ( c >= '0' && c <= '9' ) return c-'0'; + if ( c >= 'A' && c <= 'F' ) return c-'A'+10; + if ( c >= 'a' && c <= 'f' ) return c-'a'+10; + return -1; +} + +/* --------------------- */ + +int my_char2bignum ( struct NFast_Bignum **ppBN_out, + const char *text, + struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx ) +{ + struct NFast_Bignum *pBN; + int d; + size_t len, i; + + /* Strip leading whitespace */ + + while ( text[0] != 0 && isspace((unsigned char)text[0]) ) + text++; + + /* Strip trailing whitespace */ + len=strlen(text); + while ( len > 0 && isspace((unsigned char)text[len-1]) ) + len--; + + if ( len > MAXBIGNUMBITS/4 ) return Status_OutOfRange; + + pBN = (struct NFast_Bignum *)NFastApp_Malloc(app, sizeof(struct NFast_Bignum), cctx, tctx); + if ( !pBN ) return NOMEM; + + pBN->msb_first = 0; + pBN->msw_first = 0; + + /* Read in from the LS digit */ + for ( i=0; ibytes[i/2] |= (d << 4); + else + pBN->bytes[i/2] = d; + } + + /* Pad to words if necessary */ + i = (len+1)/2; + while ( (i & 3) != 0 ) + pBN->bytes[i++] = 0; + + assert(i <= INT_MAX); + pBN->nbytes=(int)i; + *ppBN_out=pBN; + return Status_OK; +} + +/* --------------------- */ + +// bin データを NFast_Bignum データに変換する +int my_bin2bignum ( struct NFast_Bignum **ppBN_out, + struct NFast_Application *app, + const unsigned char *bin, const int size ) +{ + struct NFast_Bignum *pBN; + int len, i; + + len = size; + + if ( len > MAXBIGNUMBITS/4 ) return Status_OutOfRange; + + pBN = (struct NFast_Bignum *)NFastApp_Malloc( app, sizeof(struct NFast_Bignum), NULL, NULL ); + if ( !pBN ) return NOMEM; + + pBN->msb_first = 0; + pBN->msw_first = 0; + + for ( i = 0; i < len; i++ ) + pBN->bytes[i] = bin[len-1-i]; + + while ( (i & 3) != 0 ) + pBN->bytes[i++] = 0; + + pBN->nbytes = i; + + *ppBN_out = pBN; + + return Status_OK; +} // my_bin2bignum + +/* --------------------- */ + +static int getbyte ( const struct NFast_Bignum *pN, int pos ) +{ + /* Get a byte from a bignum, taking account of possible strange endianness */ + if ( pos >= pN->nbytes ) return 0; + + if ( pN->msb_first ) pos ^= 3; /* Big endian words */ + + if ( pN->msw_first ) + { + pos = pN->nbytes-1-pos; + pos ^= 3; + } + + return pN->bytes[pos]; +} + +/* --------------------- */ + +static int getbytelen ( const struct NFast_Bignum *pN ) +{ + int n=pN->nbytes-1; + while ( n >= 0 && getbyte(pN, n)==0 ) + n--; + + return n+1; +} + +/* --------------------- */ + +int my_bignum2char ( char *buf, int buflen, + const struct NFast_Bignum *pBN, + struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx ) +{ + int i, d, pos, len; + static const char *hexdigits="0123456789ABCDEF"; + + len = pBN->nbytes; + + pos = len*2+1; + if ( buflen < pos ) + return Status_BufferFull; + + buf[--pos] = 0; + + for ( i=0; i>4) & 0xF]; + } + + return Status_OK; +} + +/* --------------------- */ + +int my_bignum2bin ( unsigned char *buf, int buflen, + struct NFast_Application *app, + const struct NFast_Bignum *pBN ) +{ + int i, pos, len; + + len = pBN->nbytes; + pos = len; + if ( buflen < pos ) + return Status_BufferFull; + + for ( i = 0; i < len; i++ ) + { + buf[--pos] = getbyte( pBN, i ); + } + + return Status_OK; +} // my_bignum2bin + +/* --------------------- */ + +int my_bignumCopy( struct NFast_Bignum **dst, + const struct NFast_Bignum *src, + struct NFast_Application *app ) +{ + struct NFast_Bignum *pBN; + pBN = (struct NFast_Bignum *)NFastApp_Malloc( app, sizeof(struct NFast_Bignum), NULL, NULL ); + if ( !pBN ) return NOMEM; + + pBN->msb_first = src->msb_first; + pBN->msw_first = src->msw_first; + pBN->nbytes = src->nbytes; + memcpy( pBN->bytes, src->bytes, src->nbytes ); + + *dst = pBN; + + return Status_OK; +} + +/* --------------------- */ + +void my_printbignum ( FILE *f, const char *prefix, const struct NFast_Bignum *pBN ) +{ + char buf[MAXBIGNUMBITS/4+1]; + int rc; + + rc = my_bignum2char(buf, sizeof(buf), pBN, NULL, NULL, NULL); + if ( rc != Status_OK ) strcpy(buf, ""); + fprintf( f, "%s=\n %s\n", prefix, buf ); +} + +/* --------------------- */ + +int my_compare ( const struct NFast_Bignum *pA, + const struct NFast_Bignum *pB ) +{ + int i, aa, bb; + + aa=getbytelen(pA); + bb=getbytelen(pB); + if ( aa != bb ) return (aa > bb) ? 1 : -1; + + i=aa; + while ( i-- > 0 ) + { + aa=getbyte(pA,i); + bb=getbyte(pB,i); + if ( aa != bb ) return (aa > bb) ? 1 : -1; + } + + return 0; +} + +/* --------------------- */ + +#endif // HSM diff --git a/tags/20100201_Sharp_Release/cr_hsm_bignum.h b/tags/20100201_Sharp_Release/cr_hsm_bignum.h new file mode 100644 index 0000000..21b098a --- /dev/null +++ b/tags/20100201_Sharp_Release/cr_hsm_bignum.h @@ -0,0 +1,177 @@ +/** \file simplebignum.h Simple bignum support + * + * Illustrates simple easy-to-use bignumber format. This provides a + * definition of the \ref NFast_Bignum structure which can be used + * in applications which do not already have an equivalent structure + * defined. + * + * See also: + * - \ref nfastapp.h + * - \ref gsbignum + */ +/* Copyright 1999-2002 nCipher Corporation Limited. +* +* This example source code is provided for your information and +* assistance. See the file LICENCE.TXT for details and the +* terms and conditions of the licence which governs the use of the +* source code. By using such source code you will be accepting these +* terms and conditions. If you do not wish to accept these terms and +* conditions, DO NOT OPEN THE FILE OR USE THE SOURCE CODE. +* +* Note that there is NO WARRANTY. +* +*/ + +#ifndef CR_HSM_BIGNUM_H +#define CR_HSM_BIGNUM_H + +#include "nfastapp.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef MAXBIGNUMBITS +/** Maximum size of a bignum in bits */ +#define MAXBIGNUMBITS 16384 +#endif + +/** Structure of a bignum + * + * \ref M_Bignum will be a pointer to this structure. */ +struct NFast_Bignum { + /** Byte order + * + * If this is set then each 32-bit word in the bignum is big-endian + * (most-significant byte first); otherwise it is little-endian + * (least-significant byte first). */ + int msb_first; + /** Word order + * + * If this is set then 32-bit words in the bignum are in big-endian order + * (most-significant word first); otherwise they are in little-endian + * order (least-significant words first). + */ + int msw_first; + /** Number of bytes */ + int nbytes; + /** Bignum data + * + * Only the first \a nbytes are used. */ + unsigned char bytes[MAXBIGNUMBITS/8]; +}; + +/* Bignum send & receive upcalls -------------------------- */ + +/* As well as being used directly as upcalls, + these can be used to create bignums from data blocks and + extract data from bignums. + */ + +/** Bignum receive upcall + * + * See \ref NFast_BignumReceiveUpcall_t */ +extern int my_bignumreceiveupcall(struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx, + M_Bignum *bignum, int nbytes, + const void *source, + int msbitfirst, int mswordfirst); + + +/** Bignum send-length upcall + * + * See \ref NFast_BignumSendLenUpcall_t */ +extern int my_bignumsendlenupcall(struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx, + const M_Bignum *bignum, int *nbytes_r); + +/** Bignum send upcall + * + * See \ref NFast_BignumSendUpcall_t */ +extern int my_bignumsendupcall(struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx, + const M_Bignum *bignum, int nbytes, + void *dest, int msbitfirst, int mswordfirst); + + +/** Free bignum upcall + * + * See \ref NFast_BignumFreeUpcall_t */ +extern void my_bignumfreeupcall(struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx, + M_Bignum *bignum); + +/** Bignum format upcall + * + * See \ref NFast_BignumFormatUpcall_t */ +extern int my_bignumformatupcall(struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx, + int *msbitfirst_io, int *mswordfirst_io); + +/** Structure containing bignum upcalls + * + * See \ref NFastAppInitArgs and \ref NFAPP_IF_BIGNUM */ +extern NFast_BignumUpcalls my_upcalls; + +/* Bignum utility functions ----------------------------- */ + +/** Convert a hex string to a bignum + * + * \return Status code + */ +extern int my_char2bignum ( struct NFast_Bignum **ppBN_out, + const char *text, + struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx ); + +// convert binary to NFast_Bignum +extern int my_bin2bignum ( struct NFast_Bignum **ppBN_out, + struct NFast_Application *app, + const unsigned char *bin, const int size ); + +/** Convert a bignum to a hex string + * + * \return Status code + */ +extern int my_bignum2char ( char *buf, int buflen, + const struct NFast_Bignum *pBN, + struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx ); + +// convert NFast_Bignum to binary +int my_bignum2bin ( unsigned char *buf, int buflen, + struct NFast_Application *app, + const struct NFast_Bignum *pBN ); + +// NFast_Bignum copy +int my_bignumCopy( struct NFast_Bignum **dst, + const struct NFast_Bignum *src, + struct NFast_Application *app ); + +/** Print a bignum in hex to a file + * + * Call ferror() to test for output errors. + */ +extern void my_printbignum ( FILE *f, + const char *prefix, const struct NFast_Bignum *pBN ); + + +/** Compare two bignums + * + * \return -1, 0 or 1 if A\B + */ +extern int my_compare ( const struct NFast_Bignum *pA, + const struct NFast_Bignum *pB ); + +#ifdef __cplusplus +} +#endif + +#endif // CR_HSM_BIGNUM_H diff --git a/tags/20100201_Sharp_Release/cr_hsm_code.c b/tags/20100201_Sharp_Release/cr_hsm_code.c new file mode 100644 index 0000000..8bd9581 --- /dev/null +++ b/tags/20100201_Sharp_Release/cr_hsm_code.c @@ -0,0 +1,1010 @@ +/* ==================================================================== + * Copyright (c) 1998-2008 The OpenSSL 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 OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL 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 OpenSSL 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 product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * 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 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 acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS 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 AUTHOR OR 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. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef USE_HSM +#include "cr_hsm_code.h" +#include "cr_hsm_alloc.h" +#include "cr_hsm_bignum.h" +#include "cr_generate_id.h" +#include "cr_generate_id_private.h" + +// nShield +#include "nfastapp.h" +#include "nfkm.h" +#include "rqcard-applic.h" +#include "rqcard-fips.h" + +// nFast variables +NFast_AppHandle hsmHandle; +NFastApp_Connection hsmConnection; +NFKM_WorldInfo *hsmWorld = NULL; // allocate + +#ifdef ENCRYPT_AES +M_KeyID hsmAesKeyidDev, hsmAesKeyidProd; +const NFKM_KeyIdent hsmAesKeyidentDev = { (char*)"simple", (char*)"efuse-aes-dev" }; +const NFKM_KeyIdent hsmAesKeyidentProd = { (char*)"simple", (char*)"efuse-aes-prod" }; + +static int hsm_aes_load_key( NFKM_KeyIdent keyident, M_KeyID *keyid ); +#else // !ENCRYPT_AES +M_KeyID hsmRsaPrivkeyidDev, hsmRsaPubkeyidDev, hsmRsaPrivkeyidProd, hsmRsaPubkeyidProd; +const NFKM_KeyIdent hsmRsaKeyidentDev = { (char*)"simple", (char*)"efuse-rsa-priv-dev" }; +const NFKM_KeyIdent hsmRsaKeyidentProd = { (char*)"simple", (char*)"efuse-rsa-priv-prod" }; + +static int hsm_rsa_load_keypair( NFKM_KeyIdent keyident, M_KeyID *privKeyid, M_KeyID *pubKeyid ); +#endif // ENCRYPT_AES + +// ECDSA key +M_KeyID hsmEcdsaPrivkeyidDev, hsmEcdsaPubkeyidDev; +M_KeyID hsmEcdsaPrivkeyidProd, hsmEcdsaPubkeyidProd; + +const NFKM_KeyIdent hsmEcdsaPrivkeyidentDev = { (char*)"simple", (char*)"nct2-priv-dev" }; +const NFKM_KeyIdent hsmEcdsaPubkeyidentDev = { (char*)"simple", (char*)"nct2-pub-dev" }; +const NFKM_KeyIdent hsmEcdsaPrivkeyidentProd = { (char*)"simple", (char*)"nct2-priv-prod" }; +const NFKM_KeyIdent hsmEcdsaPubkeyidentProd = { (char*)"simple", (char*)"nct2-pub-prod" }; +int hsm_ecdsa_load_keypair( NFKM_KeyIdent privKeyident, M_KeyID *privKeyid, + NFKM_KeyIdent pubKeyident, M_KeyID *pubKeyid ); + +// init HSM +int hsm_initialize( void ) +{ + int ret_code = CR_GENID_SUCCESS; + +#ifdef RESET_HSM + // HSM のリセット処理 + ret_code = hsm_reset_module(); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } +#endif // RESET_HSM + + // init HSM + ret_code = NFastApp_Init( &hsmHandle, my_hsm_malloc, my_hsm_realloc, my_hsm_free, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // set BigNum upcalls for HSM + ret_code = NFastApp_SetBignumUpcalls( + hsmHandle, + my_bignumreceiveupcall, + my_bignumsendlenupcall, + my_bignumsendupcall, + my_bignumfreeupcall, + my_bignumformatupcall, + NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // connect HSM + ret_code = NFastApp_Connect( hsmHandle, &hsmConnection, 0 /* flag */, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // get NFKM info + ret_code = NFKM_getinfo( hsmHandle, &hsmWorld, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + +#ifdef ENCRYPT_AES + // load aes dev key + ret_code = hsm_aes_load_key( hsmAesKeyidentDev, &hsmAesKeyidDev ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // load aes prod key + ret_code = hsm_aes_load_key( hsmAesKeyidentProd, &hsmAesKeyidProd ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } +#else // !ENCRYPT_AES + // load rsa dev keypair + ret_code = hsm_rsa_load_keypair( hsmRsaKeyidentDev, &hsmRsaPrivkeyidDev, &hsmRsaPubkeyidDev ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // load rsa prod keypair + ret_code = hsm_rsa_load_keypair( hsmRsaKeyidentProd, &hsmRsaPrivkeyidProd, &hsmRsaPubkeyidProd ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } +#endif // ENCRYPT_AES + + // load ecdsa dev keypair + ret_code = hsm_ecdsa_load_keypair( hsmEcdsaPrivkeyidentDev, &hsmEcdsaPrivkeyidDev, + hsmEcdsaPubkeyidentDev, &hsmEcdsaPubkeyidDev ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // load ecdsa prod keypair + ret_code = hsm_ecdsa_load_keypair( hsmEcdsaPrivkeyidentProd, &hsmEcdsaPrivkeyidProd, + hsmEcdsaPubkeyidentProd, &hsmEcdsaPubkeyidProd ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + return ret_code; +} // hsm_initialize + +int hsm_finalize( void ) +{ + int ret_code = CR_GENID_SUCCESS; + + // void + NFKM_freeinfo( hsmHandle, &hsmWorld, NULL ); + + ret_code = NFastApp_Disconnect( hsmConnection, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + } + + // void + NFastApp_Finish( hsmHandle, NULL ); + + return ret_code; +} // hsm_finalize + +int hsm_reset_module( void ) +{ + int ret_code = CR_GENID_SUCCESS; + NFast_AppHandle handle; + NFastApp_Connection connection; + M_Command cmd; + M_Reply reply; + + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // init HSM + ret_code = NFastApp_InitEx( &handle, NULL, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // 特権モードで接続しないと、ClerUnit, RetryFailedModuleコマンドが発行できない + ret_code = NFastApp_Connect( handle, &connection, NFastApp_ConnectionFlags_Privileged, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // モジュールの状態確認 + cmd.cmd = Cmd_NewEnquiry; + cmd.args.newenquiry.version = EnqVer_Six; + cmd.args.newenquiry.module = HSM_MODULE_ID; + ret_code = NFastApp_Transact( connection, NULL, &cmd, &reply, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + ret_code = reply.status; + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // モジュールが failed state でないなら以下は必要ないので即終了 + if ( reply.reply.newenquiry.flags & Cmd_NewEnquiry_Reply_flags_Failed ) + { + NFastApp_Free_Reply( handle, NULL, NULL, &reply ); + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // failed state からの復旧要求 + // 必ず Status_OK を返してくるので信用できない + cmd.cmd = Cmd_RetryFailedModule; + cmd.args.retryfailedmodule.module = HSM_MODULE_ID; + ret_code = NFastApp_Transact( connection, NULL, &cmd, &reply, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + ret_code = reply.status; + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + } // 復旧処理 + + NFastApp_Free_Reply( handle, NULL, NULL, &reply ); + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // モジュールのリセット + cmd.cmd = Cmd_ClearUnit; + cmd.args.clearunit.module = HSM_MODULE_ID; + ret_code = NFastApp_Transact( connection, NULL, &cmd, &reply, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + ret_code = reply.status; + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + NFastApp_Free_Reply( handle, NULL, NULL, &reply ); + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) );; + + // モジュールの状態を再度確認 + cmd.cmd = Cmd_NewEnquiry; + cmd.args.newenquiry.module = HSM_MODULE_ID; + cmd.args.newenquiry.version = EnqVer_Six; + ret_code = NFastApp_Transact( connection, NULL, &cmd, &reply, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + ret_code = reply.status; + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // まだ failed state ならば、終了するしかない + if ( reply.reply.newenquiry.flags & Cmd_NewEnquiry_Reply_flags_Failed ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return Status_HardwareFailed; + } + + NFastApp_Free_Reply( handle, NULL, NULL, &reply ); + + // 切断 + ret_code = NFastApp_Disconnect( connection, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // ハンドル破棄 + NFastApp_Finish( handle, NULL ); + + return ret_code; +} // hsm_reset_module + +int hsm_generate_random( unsigned char *buf, int bytes ) +{ + int ret_code = CR_GENID_SUCCESS; + M_Command cmd; + M_Reply reply; + + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // コマンドに値をセットする + cmd.cmd = Cmd_GenerateRandom; + cmd.args.generaterandom.lenbytes = bytes; + + // 命令発行 + ret_code = NFastApp_Transact( hsmConnection, NULL, &cmd, &reply, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + ret_code = reply.status; + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // buffer copy + memcpy( buf, reply.reply.generaterandom.data.ptr, bytes ); + + NFastApp_Free_Command( hsmHandle, NULL, NULL, &cmd ); + NFastApp_Free_Reply( hsmHandle, NULL, NULL, &reply ); + + return CR_GENID_SUCCESS; +} // hsm_generate_rand + +int hsm_get_rtc( time_t *time ) +{ + int ret_code = CR_GENID_SUCCESS; + + M_Command cmd; + M_Reply reply; + + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // コマンドに値をセットする + cmd.cmd = Cmd_GetRTC; + cmd.args.getrtc.module = HSM_MODULE_ID; + + // 命令発行 + ret_code = NFastApp_Transact( hsmConnection, NULL, &cmd, &reply, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + ret_code = reply.status; + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + *time = (int)reply.reply.getrtc.time.currenttimelow; + + NFastApp_Free_Command( hsmHandle, NULL, NULL, &cmd ); + NFastApp_Free_Reply( hsmHandle, NULL, NULL, &reply ); + + return CR_GENID_SUCCESS; +} // hsm_get_rtc + +#ifdef ENCRYPT_AES + +int hsm_aes_load_key( NFKM_KeyIdent keyident, M_KeyID *keyid ) +{ + int ret_code = CR_GENID_SUCCESS; + NFKM_Key *keyinfo = NULL; + NFKM_ModuleInfo *moduleinfo = NULL; + M_ByteBlock *blobPtr = NULL; + + // find key + ret_code = NFKM_findkey( hsmHandle, keyident, &keyinfo, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + + // get usable Module + moduleinfo = hsmWorld->modules[0]; + ret_code = NFKM_getusablemodule( hsmWorld, HSM_MODULE_ID, &moduleinfo ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + + // load key blob + blobPtr = &keyinfo->privblob; + ret_code = NFKM_cmd_loadblob( hsmHandle, hsmConnection, + moduleinfo->module, blobPtr, + 0, keyid, "loading aes key blob", NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + +end: + if ( keyinfo != NULL ) + NFKM_freekey( hsmHandle, keyinfo, NULL ); + + return ret_code; +} // hsm_aes_load_key + +int hsm_aes_encrypt( unsigned char *dst_buf, unsigned char *org_buf, int size, u8 bonding_option, u8 *pIV ) +{ + int ret_code = CR_GENID_SUCCESS; + + M_KeyID keyid; + M_Command cmd; + M_Reply reply; + M_IV enc_iv; + + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // key set + keyid = bonding_option ? hsmAesKeyidDev : hsmAesKeyidProd; + + // iv set + enc_iv.mech = Mech_RijndaelmCBCpNONE; + memcpy( enc_iv.iv.generic128.iv.bytes, pIV, sizeof( enc_iv.iv.generic128.iv.bytes ) ); + + // encrypt command set + cmd.cmd = Cmd_Encrypt; + cmd.args.encrypt.key = keyid; + cmd.args.encrypt.mech = Mech_RijndaelmCBCpNONE; + cmd.args.encrypt.plain.type = PlainTextType_Bytes; + cmd.args.encrypt.plain.data.bytes.data.len = size; + cmd.args.encrypt.plain.data.bytes.data.ptr = org_buf; + cmd.args.encrypt.flags = Cmd_Encrypt_Args_flags_given_iv_present; + cmd.args.encrypt.given_iv = &enc_iv; + + // encrypt command issue + ret_code = NFastApp_Transact( hsmConnection, NULL, &cmd, &reply, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + ret_code = reply.status; + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // buffer copy + memcpy( dst_buf, reply.reply.encrypt.cipher.data.generic128.cipher.ptr, size ); + + //NFastApp_Free_Command( hsmHandle, NULL, NULL, &cmd ); // 何故かアボートする + NFastApp_Free_Reply( hsmHandle, NULL, NULL, &reply ); + + return CR_GENID_SUCCESS; +} // hsm_aes_encrypt + +int hsm_aes_decrypt( unsigned char *dst_buf, unsigned char *org_buf, int size, u8 bonding_option, u8 *pIV ) +{ + int ret_code = CR_GENID_SUCCESS; + + M_KeyID keyid; + M_Command cmd; + M_Reply reply; + M_IV dec_iv; + + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // key set + keyid = bonding_option ? hsmAesKeyidDev : hsmAesKeyidProd; + + // iv set + dec_iv.mech = Mech_RijndaelmCBCpNONE; + memcpy( dec_iv.iv.generic128.iv.bytes, pIV, sizeof( dec_iv.iv.generic128.iv.bytes ) ); + + // decyrpt + cmd.cmd = Cmd_Decrypt; + cmd.args.decrypt.flags = 0; + cmd.args.decrypt.key = keyid; + cmd.args.decrypt.mech = Mech_RijndaelmCBCpNONE; + cmd.args.decrypt.cipher.mech = Mech_RijndaelmCBCpNONE; + cmd.args.decrypt.cipher.data.generic128.cipher.len = size; + cmd.args.decrypt.cipher.data.generic128.cipher.ptr = org_buf; + cmd.args.decrypt.cipher.iv = dec_iv.iv; + cmd.args.decrypt.reply_type = PlainTextType_Bytes; + + // decrypt command issue + ret_code = NFastApp_Transact( hsmConnection, NULL, &cmd, &reply, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + ret_code = reply.status; + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // buffer copy + memcpy( dst_buf, reply.reply.decrypt.plain.data.bytes.data.ptr, size ); + + //NFastApp_Free_Command( hsmHandle, NULL, NULL, &cmd ); // 何故かアボートする + NFastApp_Free_Reply( hsmHandle, NULL, NULL, &reply ); + + return CR_GENID_SUCCESS; +} // hsm_aes_decrypt + +#else // !ENCRYPT_AES + + +int hsm_rsa_load_keypair( NFKM_KeyIdent keyident, M_KeyID *privKeyid, M_KeyID *pubKeyid ) +{ + int ret_code = CR_GENID_SUCCESS; + NFKM_Key *keyinfo = NULL; + NFKM_ModuleInfo *moduleinfo = NULL; + M_ByteBlock *blobPtr = NULL; + + // find key + ret_code = NFKM_findkey( hsmHandle, keyident, &keyinfo, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + + // get usable Module + moduleinfo = hsmWorld->modules[0]; + ret_code = NFKM_getusablemodule( hsmWorld, HSM_MODULE_ID, &moduleinfo ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + + // load private key blob + blobPtr = &keyinfo->privblob; + ret_code = NFKM_cmd_loadblob( hsmHandle, hsmConnection, + moduleinfo->module, blobPtr, + 0, privKeyid, + "loading priv key blob", NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + + // load public key blob + blobPtr = &keyinfo->pubblob; + ret_code = NFKM_cmd_loadblob( hsmHandle, hsmConnection, + moduleinfo->module, blobPtr, + 0, pubKeyid, + "loading pub key blob", NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + +end: + NFKM_freekey( hsmHandle, keyinfo, NULL ); + + return ret_code; +} // hsm_rsa_load_keypair + +int hsm_rsa_encrypt( unsigned char *dst_buf, unsigned char *org_buf, int size, u8 bonding_option ) +{ + int ret_code = CR_GENID_SUCCESS; + + M_KeyID keyid; + M_Command cmd; + M_Reply reply; + + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // key set + keyid = bonding_option ? hsmRsaPubkeyidDev : hsmRsaPubkeyidProd; + + // encrypt command set + cmd.cmd = Cmd_Encrypt; + cmd.args.encrypt.flags = 0; + cmd.args.encrypt.key = keyid; + cmd.args.encrypt.mech = Mech_RSApPKCS1; + cmd.args.encrypt.plain.type = PlainTextType_Bytes; + cmd.args.encrypt.plain.data.bytes.data.len = size; + cmd.args.encrypt.plain.data.bytes.data.ptr = org_buf; + + // encrypt command issue + ret_code = NFastApp_Transact( hsmConnection, NULL, &cmd, &reply, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + ret_code = reply.status; + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // buffer copy + memcpy( dst_buf, reply.reply.decrypt.plain.data.bytes.data.ptr, size ); + + //NFastApp_Free_Command( hsmHandle, NULL, NULL, &cmd ); // 何故かアボートする + NFastApp_Free_Reply( hsmHandle, NULL, NULL, &reply ); + + return CR_GENID_SUCCESS; +} // hsm_rsa_encrypt + +int hsm_rsa_decrypt( unsigned char *dst_buf, unsigned char *org_buf, int size, u8 bonding_option ) +{ + int ret_code = CR_GENID_SUCCESS; + + M_KeyID keyid; + M_Command cmd; + M_Reply reply; + + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // key set + keyid = bonding_option ? hsmRsaPrivkeyidDev : hsmRsaPrivkeyidProd; + + // decyrpt command set + cmd.cmd = Cmd_Decrypt; + cmd.args.decrypt.flags = 0; + cmd.args.decrypt.key = keyid; + cmd.args.decrypt.mech = Mech_Any; + cmd.args.decrypt.cipher.mech = Mech_RSApPKCS1; + cmd.args.decrypt.cipher.data.generic128.cipher.len = size; + cmd.args.decrypt.cipher.data.generic128.cipher.ptr = org_buf; + cmd.args.decrypt.reply_type = PlainTextType_Bytes; + + // decrypt command issue + ret_code = NFastApp_Transact( hsmConnection, NULL, &cmd, &reply, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + ret_code = reply.status; + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // buffer copy + memcpy( dst_buf, reply.reply.decrypt.plain.data.bytes.data.ptr, size ); + + //NFastApp_Free_Command( hsmHandle, NULL, NULL, &cmd ); // 何故かアボートする + NFastApp_Free_Reply( hsmHandle, NULL, NULL, &reply ); + + return CR_GENID_SUCCESS; +} // hsm_rsa_decrypt + +#endif // !ENCRYPT_AES + +int hsm_ecdsa_load_keypair( NFKM_KeyIdent privKeyident, M_KeyID *privKeyid, + NFKM_KeyIdent pubKeyident, M_KeyID *pubKeyid ) +{ + int ret_code = CR_GENID_SUCCESS; + NFKM_Key *keyinfo = NULL; + NFKM_ModuleInfo *moduleinfo = NULL; + M_ByteBlock *blobptr = NULL; + + // get usable Module + moduleinfo = hsmWorld->modules[0]; + ret_code = NFKM_getusablemodule( hsmWorld, HSM_MODULE_ID, &moduleinfo ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + + // priv + if ( &privKeyident != NULL ) + { + // find key + ret_code = NFKM_findkey( hsmHandle, privKeyident, &keyinfo, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + + // load key blob + blobptr = &(keyinfo->privblob); + ret_code = NFKM_cmd_loadblob( hsmHandle, hsmConnection, + moduleinfo->module, blobptr, + 0, privKeyid, + "loading priv key blob", NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + + NFKM_freekey( hsmHandle, keyinfo, NULL ); + keyinfo = NULL; + } + else + { + *privKeyid = 0; + } // priv + + // pub + if ( &pubKeyident != NULL ) + { + // find key + ret_code = NFKM_findkey( hsmHandle, pubKeyident, &keyinfo, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + + // load key blob + blobptr = &(keyinfo->pubblob); + ret_code = NFKM_cmd_loadblob( hsmHandle, hsmConnection, + moduleinfo->module, blobptr, + 0, pubKeyid, + "loading pub key blob", NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + } + else + { + *pubKeyid = 0; + } // pub + +end: + NFKM_freekey( hsmHandle, keyinfo, NULL ); + + return ret_code; +} // hsm_ecdsa_load_keypair + +int hsm_ecdsa_sign( unsigned char *sign_buf, unsigned char *data_buf, unsigned char bonding_option ) +{ + int ret_code = CR_GENID_SUCCESS; + + M_KeyID privKeyid, pubKeyid; + M_Command cmd; + M_Reply reply; + unsigned char *rPtr, *sPtr; + int rLen, sLen; + + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // key set + privKeyid = bonding_option ? hsmEcdsaPrivkeyidDev : hsmEcdsaPrivkeyidProd; + pubKeyid = bonding_option ? hsmEcdsaPubkeyidDev : hsmEcdsaPubkeyidProd; + + // sign command set + cmd.cmd = Cmd_Sign; + cmd.args.sign.flags = 0; // Cmd_Sign_Args_flags_given_iv_present; + cmd.args.sign.key = privKeyid; +#ifdef ECDSA_SHA256 + cmd.args.sign.mech = Mech_ECDSAhSHA256; + cmd.args.sign.plain.type = PlainTextType_Hash32; + cmd.args.sign.plain.data.hash32.data = *(M_Hash32*)data_buf; +#else // !ECDSA_SHA256 + cmd.args.sign.mech = Mech_ECDSA; + cmd.args.sign.plain.type = PlainTextType_Hash; + cmd.args.sign.plain.data.hash.data = *(M_Hash*)data_buf; +#endif // ECDSA_SHA256 + + // sign command issue + ret_code = NFastApp_Transact( hsmConnection, NULL, &cmd, &reply, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + ret_code = reply.status; + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // signature bignum -> bin + rLen = reply.reply.sign.sig.data.ecdsa.r->nbytes; + rPtr = (unsigned char*)cr_mem_malloc( rLen ); + my_bignum2bin ( rPtr, rLen, hsmHandle, reply.reply.sign.sig.data.ecdsa.r ); + sLen = reply.reply.sign.sig.data.ecdsa.s->nbytes; + sPtr = (unsigned char*)cr_mem_malloc( sLen ); + my_bignum2bin ( sPtr, sLen, hsmHandle, reply.reply.sign.sig.data.ecdsa.s ); + +#if 0 + DEBUG_PRINT_ARRAY( (char*)"sig r(HSM)", (const char *)rPtr, rLen ); + DEBUG_PRINT_ARRAY( (char*)"sig s(HSM)", (const char *)sPtr, sLen ); +#endif + +#if 1 + // verify + struct NFast_Bignum *rBn, *sBn; + my_bignumCopy( &rBn, reply.reply.sign.sig.data.ecdsa.r, hsmHandle ); + my_bignumCopy( &sBn, reply.reply.sign.sig.data.ecdsa.s, hsmHandle ); + + NFastApp_Free_Command( hsmHandle, NULL, NULL, &cmd ); + NFastApp_Free_Reply( hsmHandle, NULL, NULL, &reply ); + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + cmd.cmd = Cmd_Verify; + cmd.args.verify.flags = 0; + cmd.args.verify.key = pubKeyid; +#ifdef ECDSA_SHA256 + cmd.args.verify.mech = Mech_ECDSAhSHA256; + cmd.args.verify.plain.type = PlainTextType_Hash32; + cmd.args.verify.plain.data.hash32.data = *(M_Hash32*)data_buf; + cmd.args.verify.sig.mech = Mech_ECDSAhSHA256; +#else // !ECDSA_SHA256 + cmd.args.verify.mech = Mech_ECDSA; + cmd.args.verify.plain.type = PlainTextType_Hash; + cmd.args.verify.plain.data.hash.data = *(M_Hash*)data_buf; + cmd.args.verify.sig.mech = Mech_ECDSA; +#endif // ECDSA_SHA256 + cmd.args.verify.sig.data.ecdsa.r = rBn; + cmd.args.verify.sig.data.ecdsa.s = sBn; + ret_code = NFastApp_Transact( hsmConnection, NULL, &cmd, &reply, NULL ); + NFastApp_Free( hsmHandle, rBn, NULL, NULL ); + NFastApp_Free( hsmHandle, sBn, NULL, NULL ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } + ret_code = reply.status; + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + goto end; + } +#else // !verify + NFastApp_Free_Command( hsmHandle, NULL, NULL, &cmd ); +#endif // verify + NFastApp_Free_Reply( hsmHandle, NULL, NULL, &reply ); + + // copy sign + int i; + memset( sign_buf, 0, 60 ); + if ( rLen == 32 ) + memcpy( sign_buf, &rPtr[2], 0x1E ); + else + { + for ( i = 0; i < rLen; i++ ) + sign_buf[ 30 - i - 1 ] = rPtr[ rLen - i - 1 ]; + } + + if ( sLen == 32 ) + memcpy( &sign_buf[30], &sPtr[2], 0x1E ); + else + { + for ( i = 0; i < sLen; i++ ) + sign_buf[ 60 - i - 1 ] = sPtr[ sLen - i - 1 ]; + } + +end: + cr_mem_free( rPtr ); + cr_mem_free( sPtr ); + + return ret_code; +} // hsm_ecdsa_sign + +#endif // USE_HSM diff --git a/tags/20100201_Sharp_Release/cr_hsm_code.h b/tags/20100201_Sharp_Release/cr_hsm_code.h new file mode 100644 index 0000000..26c3114 --- /dev/null +++ b/tags/20100201_Sharp_Release/cr_hsm_code.h @@ -0,0 +1,141 @@ +/* ==================================================================== + * Copyright (c) 1998-2008 The OpenSSL 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 OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL 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 OpenSSL 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 product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * 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 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 acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS 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 AUTHOR OR 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. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#ifndef _CR_GENERATE_ID_HSM_CODE_H_ +#define _CR_GENERATE_ID_HSM_CODE_H_ + +#include "cr_hsm_bignum.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define HSM_MODULE_ID ( 1) + +// functions +int hsm_initialize( void ); +int hsm_finalize( void ); +int hsm_reset_module( void ); +int hsm_generate_random( unsigned char *buf, int bytes ); +int hsm_get_rtc( time_t *time ); +int hsm_aes_encrypt( unsigned char *dst_buf, unsigned char *org_buf, int size, unsigned char bonding_option, unsigned char *pIV ); +int hsm_aes_decrypt( unsigned char *dst_buf, unsigned char *org_buf, int size, unsigned char bonding_option, unsigned char *pIV ); +int hsm_rsa_encrypt( unsigned char *dst_buf, unsigned char *org_buf, int size, unsigned char bonding_option ); +int hsm_rsa_decrypt( unsigned char *dst_buf, unsigned char *org_buf, int size, unsigned char bonding_option ); +int hsm_ecdsa_sign( unsigned char *sign_buf, unsigned char *data_buf, unsigned char bonding_option ); + +#ifdef __cplusplus +} +#endif + + +#endif /* _CR_GENERATE_ID_HSM_CODE_H_ */ + diff --git a/tags/20100201_Sharp_Release/cr_id_util.c b/tags/20100201_Sharp_Release/cr_id_util.c new file mode 100644 index 0000000..c84c290 --- /dev/null +++ b/tags/20100201_Sharp_Release/cr_id_util.c @@ -0,0 +1,281 @@ +/* ==================================================================== + * Copyright (c) 1998-2008 The OpenSSL 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 OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL 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 OpenSSL 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 product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * 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 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 acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS 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 AUTHOR OR 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. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include +#include +#include +#include +#include +#include + +#ifdef USE_HSM +#include "cr_hsm_code.h" +#endif // USE_HSM + +#include "cr_generate_id.h" +#include "cr_generate_id_private.h" + +typedef struct +{ + u8 stop; + u8 position; + u8 emptySize; + u8 stack[ CALL_STACK_SIZE ]; +} +errorInfoStruct; + +static errorInfoStruct errorInfo; + +// タイムスタンプを取得してセット +int GetTimestamp( u8 *pYear, u8 *pMonth, u8 *pMday, u8 *pHour, u8 *pMin, u8 *pSec, time_t *pTime) +{ + int ret_code = CR_GENID_SUCCESS; + struct tm *tm_time; + struct timeval tv; + +#ifdef USE_HSM + ret_code = hsm_get_rtc( &tv.tv_sec ); + if( ret_code != CR_GENID_SUCCESS ) { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } +#else // !USE_HSM + gettimeofday( &tv, NULL ); +#endif // USE_HSM + + tm_time = gmtime( &tv.tv_sec ); + + *pYear = (u8)tm_time->tm_year; + *pMonth = (u8)tm_time->tm_mon + 1; + *pMday = (u8)tm_time->tm_mday; + *pHour = (u8)tm_time->tm_hour; + *pMin = (u8)tm_time->tm_min; + *pSec = (u8)tm_time->tm_sec; + *pTime = tv.tv_sec; + +#if 0 + { + struct tm tm2; + time_t t2; + memset( &tm2, 0, sizeof(tm2) ); + tm2.tm_year = *pYear; + tm2.tm_mon = *pMonth - 1; + tm2.tm_mday = *pMday; + tm2.tm_hour = *pHour; + tm2.tm_min = *pMin; + tm2.tm_sec = *pSec; + tm2.tm_isdst = 0; // 夏時間 ここでは0(無効)にする。 + t2 = gmt_mktime( &tm2 ); + printf( "time_t = %08x\n", (int)t ); + printf( "mktime = %08x\n", (int)t2 ); + } +#endif + +#ifdef DEBUG_PRINT + if( cr_print_flag ) { + printf("GMT:%d-%02d-%02d %02d:%02d:%02d\n", + *pYear+1900, + *pMonth, + *pMday, + *pHour, + *pMin, + *pSec + ); + } +#endif /* DEBUG_PRINT */ + + return ret_code; +} + +#if 0 +static time_t gmt_mktime( struct tm *tm_time ) +{ + time_t ret; + char *tz; + + tz = getenv("TZ"); + setenv("TZ", "", 1); // setenv, unsetenv はcygwinでは見つからない + tzset(); + ret = mktime(tm_time); // mktime は、localtimeでの変換になるため、timezoneの処理が必要 + if (tz) + setenv("TZ", tz, 1); + else + unsetenv("TZ"); + tzset(); + return ret; +} +#endif + + +// 乱数を生成してセット +int GenerateRandom( u8 *pDst, int length ) +{ + int ret_code = CR_GENID_SUCCESS; + +#ifdef USE_HSM + ret_code = hsm_generate_random( pDst, CR_RANDOM_LENGTH ); + if ( ret_code != CR_GENID_SUCCESS ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + } +#else // !USE_HSM + int i; + for( i = 0 ; i < length; i++ ) { + *pDst++ = (u8)rand(); + } +#endif // USE_HSM + + return ret_code; +} + +void InitErrorInfo( void ) +{ + memset( &errorInfo, 0, sizeof( errorInfo ) ); + errorInfo.emptySize = CALL_STACK_SIZE; +} // InitErrorInfo + +// エラー情報の記録 +void SetErrorInfo( const char *funcName, u32 line ) +{ + if ( !errorInfo.stop ) + { + int len; + char str[64]; + + snprintf( str, sizeof( str ), "%s:%d ", funcName, (int)line ); + len = strlen( str ); + + if ( len > errorInfo.emptySize ) + { + errorInfo.stop = 1; + len = errorInfo.emptySize; + } + + memcpy( &errorInfo.stack[ errorInfo.position ], str, len ); + errorInfo.position += len; + errorInfo.emptySize -= len; + } +#if 0 + else + { + printf( "Stack is full!\n" ); + } +#endif +} // StoreErrorInfo + +// エラー情報の取得 +void GetErrorInfo( char *stack, u8 *size ) +{ + memcpy( stack, errorInfo.stack, CALL_STACK_SIZE ); + *size = CALL_STACK_SIZE - errorInfo.emptySize; +} // GetErrorInfo + diff --git a/tags/20100201_Sharp_Release/cr_keyPair.c b/tags/20100201_Sharp_Release/cr_keyPair.c new file mode 100644 index 0000000..e64f110 --- /dev/null +++ b/tags/20100201_Sharp_Release/cr_keyPair.c @@ -0,0 +1,310 @@ +/* ==================================================================== + * Copyright (c) 1998-2008 The OpenSSL 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 OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL 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 OpenSSL 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 product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * 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 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 acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS 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 AUTHOR OR 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. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "cr_generate_id.h" +#include "cr_generate_id_private.h" + +static int generate_EC_private_key( EC_KEY *eckey, u8 *privKey ); +static int generate_EC_public_key( EC_KEY *eckey ); + + +// ECC繧ュ繝シ繝壹い縺ョ逕滓 +int GenarateECCKeyPair( EC_KEY **ppECkey, u8 *pECPrivkey ) +{ + int openssl_result = 0; + + // 讌募繧帝∈謚 ( NID_X9_62_prime256v1 -> 32bytes縺セ縺ァ縲 NID_sect571r1 -> 71bytes縺セ縺ァ 鄂イ蜷阪↓繝繝シ繧ソ繧貞性繧√i繧後k ) + *ppECkey = EC_KEY_new_by_curve_name( NID_sect233r1 ); + if( *ppECkey == NULL ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return CR_GENID_ERROR_ECC_KEY_NEW; + } + + // 遘伜ッ骰オ逕滓 + openssl_result = generate_EC_private_key( *ppECkey, pECPrivkey ); + if( openssl_result != 0 ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return CR_GENID_ERROR_ECC_GENERATE_PRIVATE_KEY; + } + + // 蜈ャ髢矩嵯逕滓 + openssl_result = generate_EC_public_key( *ppECkey ); + if ( openssl_result == 0 ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return CR_GENID_ERROR_ECC_GENERATE_PUBLIC_KEY; + } + + // ASN.1 蠖「蠑乗欠螳壹ヵ繝ゥ繧ー繧偵そ繝繝医☆繧 + // (縺薙l繧偵そ繝繝医@縺ェ縺縺ィ濶イ縲螟峨↑繝輔ぅ繝シ繝ォ繝峨′蜈・縺」縺ヲ縺励∪縺縺溘a) + EC_KEY_set_asn1_flag( *ppECkey, 1 ); + + return CR_GENID_SUCCESS; +} + + +// EC遘伜ッ骰オ繧堤函謌 +static int generate_EC_private_key( EC_KEY *eckey, u8 *privKey ) +{ + int ret_code = CR_GENID_SUCCESS; + BIGNUM *bn_privkey = NULL; + + // 荵ア謨ー繧貞叙蠕励@縺ヲ縲∫ァ伜ッ骰オ縺ォ縺吶k縲 + ret_code = GenerateRandom( privKey, EC_PRIVATE_KEY_LENGTH ); + if ( ret_code != CR_GENID_SUCCESS ) { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return ret_code; + } + + // ECC233 縺ァ30繝舌う繝医□縺大茜逕ィ縺吶k縺ョ縺ァ縲∝セ後m2繝舌う繝医ッ0縺ァ蝓九a繧 + // (DER(BER) 縺 big endian 縺ェ縺ョ縺ァ縲√%縺薙〒縺ッ蜈磯ュ2byte) + // 譛蠕後↓3繝舌う繝育岼縺ョ7繝薙ャ繝医r繧ッ繝ェ繧「縺吶k + privKey[ 0 ] = 0; + privKey[ 1 ] = 0; + privKey[ 2 ] &= 0x01; + + // 逕滓舌@縺溽ァ伜ッ骰オ繧達N縺ォ螟画鋤縺励※縲‘ckey縺ォ繧サ繝繝 + // 窶サbn_privkey縺ッ縲∫函謌舌↓謌仙粥縺励◆蝣エ蜷医√%縺薙〒縺ッBN_free縺輔l縺壹↓eckey隕∫エ縺ョ荳縺、縺ォ縺ェ縺」縺ヲ蠑輔″貂。縺輔l縺セ縺吶 + bn_privkey = BN_new(); + if( bn_privkey == NULL ) + { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return CR_GENID_ERROR_BN_NEW; + } + BN_init( bn_privkey ); /* memset(a,0,sizeof(BIGNUM)); */ + (void)BN_bin2bn( privKey, EC_PRIVATE_KEY_LENGTH, bn_privkey ); + eckey->priv_key = bn_privkey; + + DEBUG_PRINT_ARRAY( "ec private key:", (const char *)privKey, EC_PRIVATE_KEY_LENGTH ); + + return ret_code; +} // generate_EC_private_key + + +// EC蜈ャ髢矩嵯繧堤函謌 窶サopenssl繧ウ繝シ繝峨°繧画栢邊九@縲∽ク驛ィ謾ケ螟 +static int generate_EC_public_key( EC_KEY *eckey ) +{ + int ok = 0; + BN_CTX *ctx = NULL; + BIGNUM *priv_key = NULL, *order = NULL; + EC_POINT *pub_key = NULL; + + if (!eckey || !eckey->group) + { + ECerr(EC_F_EC_KEY_GENERATE_KEY, ERR_R_PASSED_NULL_PARAMETER); + return 0; + } + + if ((order = BN_new()) == NULL) goto err; + if ((ctx = BN_CTX_new()) == NULL) goto err; + + if (eckey->priv_key == NULL) + { + priv_key = BN_new(); + if (priv_key == NULL) { + goto err; + } + } + else { + priv_key = eckey->priv_key; + } + + if (!EC_GROUP_get_order(eckey->group, order, ctx)) { + goto err; + } + +#if 0 // 2009.09.25 縺薙l縺悟ョ溯。後&繧後k縺ィ縲∫ァ伜ッ骰オ縺御ケア謨ー蛹悶&繧後※縺励∪縺縲∵欠螳壹@縺溽ァ伜ッ骰オ縺ィ螟峨o縺」縺ヲ縺励∪縺縺溘a繧ウ繝。繝ウ繝医い繧ヲ繝医☆繧九 + do + if (!BN_rand_range(priv_key, order)) + goto err; + while (BN_is_zero(priv_key)); +#endif + + if (eckey->pub_key == NULL) + { + pub_key = EC_POINT_new(eckey->group); + if (pub_key == NULL) { + goto err; + } + } + else + pub_key = eckey->pub_key; + + if (!EC_POINT_mul(eckey->group, pub_key, priv_key, NULL, NULL, ctx)) { + goto err; + } + + eckey->priv_key = priv_key; + eckey->pub_key = pub_key; + + ok=1; + + err: + if (order) + BN_free(order); + if (pub_key != NULL && eckey->pub_key == NULL) + EC_POINT_free(pub_key); + if (priv_key != NULL && eckey->priv_key == NULL) + BN_free(priv_key); + if (ctx != NULL) + BN_CTX_free(ctx); + + return(ok); +} // generate_EC_public_key + + +// 骰オ繝壹い繧脱CDSA縺ァ讀懆ィシ +int TestECDSA( EC_KEY *pECkey ) +{ +#define CR_ECDSA_BUF_SIZE 29 +#define CR_ECDSA_SIGN_BUF_SIZE 256 + + unsigned char ecdsa_test_buf[CR_ECDSA_BUF_SIZE]; + unsigned char ecdsasig[CR_ECDSA_SIGN_BUF_SIZE]; + unsigned int ecdsasiglen = 0; + int openssl_result = 0; + int i; + + // 繝繝溘シ鄂イ蜷阪ョ繝シ繧ソ菴懈 + for( i = 0 ; i < CR_ECDSA_BUF_SIZE ; i++ ) { + ecdsa_test_buf[i] = (u8)(0xff & i ); + } + memset( ecdsasig, 0, CR_ECDSA_SIGN_BUF_SIZE ); + + openssl_result = ECDSA_sign( 0, ecdsa_test_buf, CR_ECDSA_BUF_SIZE, ecdsasig, + &ecdsasiglen, pECkey ); + if (openssl_result == 0) { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return CR_GENID_ERROR_ECDSA_SIGN; + } + + openssl_result = ECDSA_verify( 0, ecdsa_test_buf, CR_ECDSA_BUF_SIZE, ecdsasig, ecdsasiglen, pECkey ); + if( openssl_result != 1) { + SetErrorInfo( __FUNCTION__, __LINE__ ); + return CR_GENID_ERROR_ECDSA_VERIFY; + } + + return CR_GENID_SUCCESS; +} diff --git a/tags/20100201_Sharp_Release/dummyKey/dev/NCT2_priv.der b/tags/20100201_Sharp_Release/dummyKey/dev/NCT2_priv.der new file mode 100644 index 0000000..15926f8 Binary files /dev/null and b/tags/20100201_Sharp_Release/dummyKey/dev/NCT2_priv.der differ diff --git a/tags/20100201_Sharp_Release/dummyKey/dev/NCT2_pub.der b/tags/20100201_Sharp_Release/dummyKey/dev/NCT2_pub.der new file mode 100644 index 0000000..33399db Binary files /dev/null and b/tags/20100201_Sharp_Release/dummyKey/dev/NCT2_pub.der differ diff --git a/tags/20100201_Sharp_Release/dummyKey/dev/NCT2_pub.pem b/tags/20100201_Sharp_Release/dummyKey/dev/NCT2_pub.pem new file mode 100644 index 0000000..589f57f --- /dev/null +++ b/tags/20100201_Sharp_Release/dummyKey/dev/NCT2_pub.pem @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFIwEAYHKoZIzj0CAQYFK4EEABsDPgAEANkB/eVVYNkyMyWTUwq6Y6MUUJYtTHLy +muag+2u/Ab7Ww4xkEaJs06yqMZr1Z6SFZ9aTZwSL8KCeLSU1 +-----END PUBLIC KEY----- diff --git a/tags/20100201_Sharp_Release/dummyKey/dev/eFuse_aesKey.bin b/tags/20100201_Sharp_Release/dummyKey/dev/eFuse_aesKey.bin new file mode 100644 index 0000000..6fec377 --- /dev/null +++ b/tags/20100201_Sharp_Release/dummyKey/dev/eFuse_aesKey.bin @@ -0,0 +1 @@ +譽p)v$Fンク \ No newline at end of file diff --git a/tags/20100201_Sharp_Release/dummyKey/dev/eFuse_iv.bin b/tags/20100201_Sharp_Release/dummyKey/dev/eFuse_iv.bin new file mode 100644 index 0000000..4428674 --- /dev/null +++ b/tags/20100201_Sharp_Release/dummyKey/dev/eFuse_iv.bin @@ -0,0 +1 @@ +eMH{鰤:ーゥ \ No newline at end of file diff --git a/tags/20100201_Sharp_Release/dummyKey/dev/eFuse_privKey.der b/tags/20100201_Sharp_Release/dummyKey/dev/eFuse_privKey.der new file mode 100644 index 0000000..f2d0ba9 Binary files /dev/null and b/tags/20100201_Sharp_Release/dummyKey/dev/eFuse_privKey.der differ diff --git a/tags/20100201_Sharp_Release/dummyKey/dev/eFuse_pubKey.der b/tags/20100201_Sharp_Release/dummyKey/dev/eFuse_pubKey.der new file mode 100644 index 0000000..411cdf7 Binary files /dev/null and b/tags/20100201_Sharp_Release/dummyKey/dev/eFuse_pubKey.der differ diff --git a/tags/20100201_Sharp_Release/dummyKey/prod/NCT2_priv.der b/tags/20100201_Sharp_Release/dummyKey/prod/NCT2_priv.der new file mode 100644 index 0000000..32d6b24 Binary files /dev/null and b/tags/20100201_Sharp_Release/dummyKey/prod/NCT2_priv.der differ diff --git a/tags/20100201_Sharp_Release/dummyKey/prod/NCT2_priv.pem b/tags/20100201_Sharp_Release/dummyKey/prod/NCT2_priv.pem new file mode 100644 index 0000000..0dad0b4 --- /dev/null +++ b/tags/20100201_Sharp_Release/dummyKey/prod/NCT2_priv.pem @@ -0,0 +1,8 @@ +-----BEGIN EC PARAMETERS----- +BgUrgQQAGw== +-----END EC PARAMETERS----- +-----BEGIN EC PRIVATE KEY----- +MG0CAQEEHSzzSTwenLOaRVfl0j29t4tzFtMIOu4hzZC27rpnoAcGBSuBBAAboUAD +PgAEAGJ0KjqVxyg9Hp40gCb+CiP6LjmqBafdqrIZ4hw+AHBz9/5KU9VoehZfyyPk +2xCYrrrOlursxJwI8tUg +-----END EC PRIVATE KEY----- diff --git a/tags/20100201_Sharp_Release/dummyKey/prod/NCT2_pub.der b/tags/20100201_Sharp_Release/dummyKey/prod/NCT2_pub.der new file mode 100644 index 0000000..363d4ed Binary files /dev/null and b/tags/20100201_Sharp_Release/dummyKey/prod/NCT2_pub.der differ diff --git a/tags/20100201_Sharp_Release/dummyKey/prod/NCT2_pub.pem b/tags/20100201_Sharp_Release/dummyKey/prod/NCT2_pub.pem new file mode 100644 index 0000000..a2e9298 --- /dev/null +++ b/tags/20100201_Sharp_Release/dummyKey/prod/NCT2_pub.pem @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFIwEAYHKoZIzj0CAQYFK4EEABsDPgAEAGJ0KjqVxyg9Hp40gCb+CiP6LjmqBafd +qrIZ4hw+AHBz9/5KU9VoehZfyyPk2xCYrrrOlursxJwI8tUg +-----END PUBLIC KEY----- diff --git a/tags/20100201_Sharp_Release/dummyKey/prod/eFuse_aesKey.bin b/tags/20100201_Sharp_Release/dummyKey/prod/eFuse_aesKey.bin new file mode 100644 index 0000000..713649e --- /dev/null +++ b/tags/20100201_Sharp_Release/dummyKey/prod/eFuse_aesKey.bin @@ -0,0 +1 @@ +筑ケ゚」}Wp~n洌< \ No newline at end of file diff --git a/tags/20100201_Sharp_Release/dummyKey/prod/eFuse_iv.bin b/tags/20100201_Sharp_Release/dummyKey/prod/eFuse_iv.bin new file mode 100644 index 0000000..c5a400d --- /dev/null +++ b/tags/20100201_Sharp_Release/dummyKey/prod/eFuse_iv.bin @@ -0,0 +1 @@ +次リツLナCセk4mヲ \ No newline at end of file diff --git a/tags/20100201_Sharp_Release/dummyKey/prod/eFuse_privKey.der b/tags/20100201_Sharp_Release/dummyKey/prod/eFuse_privKey.der new file mode 100644 index 0000000..5f978ad Binary files /dev/null and b/tags/20100201_Sharp_Release/dummyKey/prod/eFuse_privKey.der differ diff --git a/tags/20100201_Sharp_Release/dummyKey/prod/eFuse_pubKey.der b/tags/20100201_Sharp_Release/dummyKey/prod/eFuse_pubKey.der new file mode 100644 index 0000000..6d8bc1a Binary files /dev/null and b/tags/20100201_Sharp_Release/dummyKey/prod/eFuse_pubKey.der differ diff --git a/tags/20100201_Sharp_Release/hsm_utils/Makefile b/tags/20100201_Sharp_Release/hsm_utils/Makefile new file mode 100644 index 0000000..7f23549 --- /dev/null +++ b/tags/20100201_Sharp_Release/hsm_utils/Makefile @@ -0,0 +1,128 @@ +# Simple makefile for example programs under gcc +# +# Build these with 'make -f Makefile-examples' +# +# Copyright 1997-2008 nCipher Corporation Limited. +# +# This file is example source code. It is provided for your +# information and assistance. See the file LICENCE.TXT for details and the +# terms and conditions of the licence which governs the use of the +# source code. By using such source code you will be accepting these +# terms and conditions. If you do not wish to accept these terms and +# conditions, DO NOT OPEN THE FILE OR USE THE SOURCE CODE. +# +# Note that there is NO WARRANTY. +# + +# ------------------------------- +# +# Set NFAST_PATH to installation directory of the headers and libraries +NFAST_PATH= /opt/nfast + +# Developer tools installation +NFAST_DEV_PATH= $(NFAST_PATH)/c/ctd/gcc +NFAST_EXAMPLES_PATH= $(NFAST_PATH)/c/ctd/examples + +# We now have a single library directory, not one per component, in an +# installation, but may be using different paths per component in +# testing. +LIBPATH_SWORLD= $(NFAST_DEV_PATH)/lib +LIBPATH_HILIBS= $(NFAST_DEV_PATH)/lib +LIBPATH_NFLOG= $(NFAST_DEV_PATH)/lib +LIBPATH_CUTILS= $(NFAST_DEV_PATH)/lib + +INC_SWORLD= $(NFAST_DEV_PATH)/include/sworld +INC_HILIBS= $(NFAST_DEV_PATH)/include/hilibs +INC_NFLOG= $(NFAST_DEV_PATH)/include/nflog +INC_CUTILS= $(NFAST_DEV_PATH)/include/cutils + +EXAMPLES_SWORLD= $(NFAST_EXAMPLES_PATH)/sworld +EXAMPLES_HILIBS= $(NFAST_EXAMPLES_PATH)/hilibs +EXAMPLES_NFLOG= $(NFAST_EXAMPLES_PATH)/nflog +EXAMPLES_CUTILS= $(NFAST_EXAMPLES_PATH)/cutils + +# openssl +OPENSSL_DIR = ../openssl-0.9.8k + + +# Where the source lives +SRCPATH = . +REFPATH = $(NFAST_PATH)/c/ctd/examples/nfuser/build-gcc-lib + +CC = gcc +CPPFLAGS= -I$(SRCPATH) \ + -I$(INC_SWORLD) \ + -I$(INC_HILIBS) \ + -I$(INC_NFLOG) \ + -I$(INC_CUTILS) \ + -I$(EXAMPLES_SWORLD) \ + -I$(EXAMPLES_HILIBS) \ + -I$(EXAMPLES_NFLOG) \ + -I$(EXAMPLES_CUTILS) \ + $(XCPPFLAGS) \ + -I$(OPENSSL_DIR)/include \ + -I$(OPENSSL_DIR)/crypto/ec \ + +CFLAGS= -g -O2 -Wall -Wwrite-strings -Wstrict-prototypes -Wmissing-prototypes -D_GNU_SOURCE -Wno-nonnull -O2 -fPIC -Wno-nonnull $(XCFLAGS) +# -Werror -> N/A + +LINK= gcc +LDFLAGS= $(XLDFLAGS) -L$(OPENSSL_DIR) +LDFLAGS_THREADED= $(LDFLAGS) $(XLDFLAGS_THREADED) +LDLIBS= $(XLDLIBS) -lcrypto -lssl -ldl -lnsl +LDLIBS_THREADED= $(XLDLIBS_THREADED) -lpthread $(LDLIBS) + +# Targets ------------------------ + +all: simple + +XLDLIBS= $(LIBPATH_SWORLD)/librqcard.a \ + $(LIBPATH_SWORLD)/libnfkm.a \ + $(LIBPATH_HILIBS)/libnfstub.a \ + $(LIBPATH_NFLOG)/libnflog.a \ + $(LIBPATH_CUTILS)/libcutils.a -lm + +COMMON_OBJECTS = $(REFPATH)/nfutil.o $(REFPATH)/nfopt.o $(REFPATH)/getdate.o $(REFPATH)/report.o $(REFPATH)/report-usage.o $(REFPATH)/nftypes.o $(REFPATH)/tokenise.o + +EXTRA_OBJECTS = my_hsm_bignum.o my_hsm_alloc.o + +COMMON_HEADERS= $(REFPATH)/nfutil.h $(REFPATH)/nfopt.h $(REFPATH)/nftypes.h $(REFPATH)/tokenise.h + +# We supply an up-to-date getdate.c in the cutils component. Prevent it +# from being automatically rebuilt in the case where getdate.y's mtime +# is (usually accidentally) newer; if you want to modify it, do so in +# cutils. +$(SRCPATH)/getdate.c: ; + +# Simple (non-threaded) programs ------------ + +my_hsm_bignum.o: my_hsm_bignum.c + $(CC) $(CFLAGS) $(CPPFLAGS) -o my_hsm_bignum.o -c my_hsm_bignum.c + +my_hsm_alloc.o: my_hsm_alloc.c + $(CC) $(CFLAGS) $(CPPFLAGS) -o my_hsm_alloc.o -c my_hsm_alloc.c + +import_aes_key: import_aes_key.c $(EXTRA_OBJECTS) + $(CC) $(CFLAGS) $(CPPFLAGS) -o import_aes_key import_aes_key.c $(COMMON_OBJECTS) $(EXTRA_OBJECTS) $(LDLIBS) + +import_rsa_keypair: import_rsa_keypair.c $(EXTRA_OBJECTS) + $(CC) $(CFLAGS) $(CPPFLAGS) -o import_rsa_keypair import_rsa_keypair.c $(COMMON_OBJECTS) $(EXTRA_OBJECTS) $(LDLIBS) + +import_ecdsa_keypair: import_ecdsa_keypair.c $(EXTRA_OBJECTS) + $(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) -o import_ecdsa_keypair import_ecdsa_keypair.c $(COMMON_OBJECTS) $(EXTRA_OBJECTS) $(LDLIBS) + +# All single-threaded targets + +TARGETS_SIMPLE= \ + import_aes_key \ + import_rsa_keypair \ + import_ecdsa_keypair \ + +simple: $(TARGETS_SIMPLE) + +# Secondary targets ------------------------ + +clean: + rm -f *.o + rm -f $(TARGETS_SIMPLE) + diff --git a/tags/20100201_Sharp_Release/hsm_utils/import_aes_key.c b/tags/20100201_Sharp_Release/hsm_utils/import_aes_key.c new file mode 100644 index 0000000..19db292 --- /dev/null +++ b/tags/20100201_Sharp_Release/hsm_utils/import_aes_key.c @@ -0,0 +1,468 @@ + +// import key (+ encrypt, decrypt) test for nShield + +#include +#include +#include +#include + +#include "nfastapp.h" +#include "nfkm.h" +#include "rqcard-applic.h" +#include "rqcard-fips.h" + +#include "my_hsm_bignum.h" +#include "my_hsm_alloc.h" + +#define MODULE_ID 1 +#define DATA_LEN 256 // bytes + +#define KEY_FILE "/opt/nfast/work/ctr_eFuse/hsm_utils/real_key/dev/eFuse_aesKey.bin" +const NFKM_KeyIdent keyident = { (char*)"simple", (char*)"efuse-aes-dev" }; + +//#define CARD_PROTECT +//#define EXPORT_KEY +//#define STRICT_FIPS + +unsigned char aes_key_data[32]; + +typedef struct _NFast_Call_Context +{ + int notused; +} +NFast_Call_Context; +NFast_Call_Context context; + +typedef struct NFast_Transaction_Context +{ + M_Command cmd; + M_Reply reply; +} +NFast_Transaction_Context; +NFast_Transaction_Context tc; + +int main( int argc, char *argv[] ) +{ + int i; + int result = 0; + + NFast_AppHandle handle; + NFastApp_Connection nc; + NFKM_WorldInfo *world = NULL; + RQCard card; + RQCard_FIPS fips; + M_KeyID ltid = 0; // the cardset loaded into the module + M_KeyID keyid; + NFKM_Key *keyinfo; + NFKM_CardSet *cardset = NULL; + FILE *fp; + unsigned char aesData[16]; + + // key data open & read + printf( "filename : %s\n", KEY_FILE ); + fp = fopen( KEY_FILE, "rb" ); + if ( !fp ) + { + printf( "error : fopen\n" ); + return 0; + } + fread( aesData, 16, 1, fp ); + for( i = 0; i < 16; i++ ) + printf( "%02X ", aesData[i] ); + printf( "\n" ); + + // init nFast + result = NFastApp_InitEx( &handle, NULL, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFastApp_InitEx\n", result ); + return 0; + } + + // connecting to hardserver + result = NFastApp_Connect( handle, &nc, 0, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFastApp_Connect\n", result ); + return 0; + } + + // set bignum upcalls setting + result = NFastApp_SetBignumUpcalls( + handle, + my_bignumreceiveupcall, + my_bignumsendlenupcall, + my_bignumsendupcall, + my_bignumfreeupcall, + my_bignumformatupcall, + NULL ); + + // NFKM getinfo + result = NFKM_getinfo( handle, &world, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_getinfo\n", result ); + return 0; + } + + // init card-loading lib + result = RQCard_init( &card, handle, nc, world, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : RQCard_init\n", result ); + return 0; + } + + // init FIPS state + result = RQCard_fips_init( &card, &fips ); + if ( result != Status_OK ) + { + printf( "error(%d) : RQCard_fips_init\n", result ); + return 0; + } + + // ui select + //result = RQCard_ui_default( &card ); + result = RQCard_ui_scroll( &card ); + if ( result != Status_OK ) + { + printf( "error(%d) : RQCard_ui_xxx\n", result ); + return 0; + } + + // get strict-FIPS authorization +#ifdef STRICT_FIPS + NFKM_FIPS140AuthHandle fipsHandle; + M_SlotID slotId; + result = RQCard_fips_get( &fips, 1, &fipsHandle, &slotId ); + if ( result != Status_OK ) + { + printf( "error(%d) : RQCard_fips_get\n", result ); + return 0; + } + if ( fipsHandle == NULL ) + { + printf( "this sworld isn't strict-FIPS.\n" ); + } +#endif + +#ifdef CARD_PROTECT + // list cardsets + int card_num; + NFKM_CardSetIdent *cardident = NULL; + result = NFKM_listcardsets( handle, &card_num, &cardident, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_listcardsets\n", result ); + return 0; + } + + // find cardsets + result = NFKM_findcardset( handle, cardident, &cardset, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_findcardset\n", result ); + return 0; + } + + // load cardset + result = RQCard_logic_ocs_specific( &card, &(cardset->hkltu), "Load Cardset" ); + if ( result != Status_OK ) + { + printf( "error(%d) : RQCard_logic_ocs_specific\n", result ); + return 0; + } + + // use specific module : #1 + // important!! : if you set resultplace=NULL, abort. (possibility is 100%) + result = RQCard_whichmodule_specific( &card, world->modules[0]->module, <id ); + if ( result != Status_OK ) + { + printf( "error(%d) : RQCard_whichmodule_specific\n", result ); + return 0; + } + + // wait event loop + result = card.uf->eventloop( &card ); + if ( result != Status_OK ) + { + printf( "error(%d) : card module event loop\n", result ); + return 0; + } +#endif + + // get usable module + NFKM_ModuleInfo *moduleinfo = world->modules[0]; + result = NFKM_getusablemodule( world, MODULE_ID, &moduleinfo ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_getusablemodule\n", result ); + return 0; + } + + // make ACL + NFKM_MakeACLParams map; + NFKM_MakeBlobsParams mbp; + memset( &map, 0, sizeof( map ) ); + if ( cardset != NULL ) + map.f = NFKM_NKF_RecoveryEnabled | NFKM_NKF_ProtectionCardSet; + else + map.f = NFKM_NKF_RecoveryEnabled | NFKM_NKF_ProtectionModule; + map.op_base = ( NFKM_DEFOPPERMS_ENCRYPT | NFKM_DEFOPPERMS_DECRYPT ); + map.cs = cardset; + result = NFKM_newkey_makeaclx( handle, nc, world, &map, + &(tc.cmd.args.import.acl), NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_newkey_makeaclx\n", result ); + return 0; + } + + // import key + tc.cmd.cmd = Cmd_Import; + tc.cmd.args.import.module = MODULE_ID; + tc.cmd.args.import.data.type = KeyType_Rijndael; + tc.cmd.args.import.data.data.random.k.len = 16; + tc.cmd.args.import.data.data.random.k.ptr = aesData; + result = NFastApp_Transact( nc, NULL, &(tc.cmd), &(tc.reply), NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_newkey_makeaclx\n", result ); + return 0; + } + + // make blobs + NFKM_Key reg_key; + memset( &mbp, 0, sizeof( mbp ) ); + memset( ®_key, 0, sizeof( reg_key ) ); + mbp.f = map.f; + mbp.kpriv = tc.reply.reply.import.key; + mbp.lt = ltid; + mbp.cs = cardset; + reg_key.v = Key__maxversion; // TORIAEZU Version Max (8) + reg_key.name = keyident.ident; + reg_key.appname = keyident.appname; + reg_key.ident = keyident.ident; + time( &(reg_key.gentime) ); + result = NFKM_newkey_makeblobsx( handle, nc, world, &mbp, ®_key, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_newkey_makeblobsx\n", result ); + return 0; + } + + // record key to disk + result = NFKM_recordkey( handle, ®_key, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_recordkey\n", result ); + return 0; + } + + printf( "record key success : appname=%s, ident=%s\n", + keyident.appname, keyident.ident ); + + // destroy key + result = NFKM_cmd_destroy( handle, nc, 0, tc.reply.reply.import.key, + "import.key", NULL ); + + // list key +#if 0 + int key_num; + NFKM_KeyIdent *keylist = NULL; + result = NFKM_listkeys( handle, &key_num, &keylist, "simple", NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_listkeys\n", result ); + return 0; + } + NFKM_KeyIdent **tkp = &keylist; + for ( i = 0; i < key_num; i++ ) + { + printf( "appname : %s, ident : %s\n", tkp[i]->appname, tkp[i]->ident ); + } +#endif + + // find key + result = NFKM_findkey( handle, keyident, &keyinfo, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_findkey\n", result ); + } + + // load blob + M_ByteBlock *blobptr; + if ( keyinfo->pubblob.len) + blobptr = &keyinfo->pubblob; + else + { + printf( "aes is symmetric key!\n" ); + blobptr = &keyinfo->privblob; + } + + result = NFKM_cmd_loadblob( handle, nc, + moduleinfo->module, blobptr, ltid, &keyid, "loading key blob", NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_cmd_loadblob\n", result ); + return 0; + } + +#if 0 + // get key info + tc.cmd.cmd = Cmd_GetKeyInfo; + tc.cmd.args.getkeyinfo.key = keyid; + result = NFastApp_Transact( nc, NULL, &(tc.cmd), &(tc.reply), NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : FastApp_Transact(Cmd_GetKeyInfo)\n", result ); + } + // if type == 30 then Rijndael(AES) + printf( "keytype : %d\n", tc.reply.reply.getkeyinfo.type ); +#endif + + // encrypt & dectypt test + { + M_ByteBlock enc_input, dec_input; + M_ByteBlock enc_output, dec_output; + M_IV base_iv, enc_iv, dec_iv; + + // data setting + enc_input.len = DATA_LEN; + enc_input.ptr = (unsigned char*)malloc( DATA_LEN ); + for ( i = 0; i < enc_input.len; i++ ) + enc_input.ptr[i] = i; + + base_iv.mech = Mech_RijndaelmCBCpNONE; + for ( i = 0; i < 16; i++ ) + base_iv.iv.generic128.iv.bytes[i] = i; + enc_iv = base_iv; + dec_iv = base_iv; + + // encrypt : my ver + tc.cmd.cmd = Cmd_Encrypt; + tc.cmd.args.encrypt.key = keyid; + tc.cmd.args.encrypt.mech = Mech_RijndaelmCBCpNONE; + tc.cmd.args.encrypt.plain.type = PlainTextType_Bytes; + tc.cmd.args.encrypt.plain.data.bytes.data = enc_input; + tc.cmd.args.encrypt.flags = Cmd_Encrypt_Args_flags_given_iv_present; + tc.cmd.args.encrypt.given_iv = &enc_iv; + result = NFastApp_Transact( nc, NULL, &(tc.cmd), &(tc.reply), NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : FastApp_Transact(Cmd_Encrypt)\n", result ); + return 0; + } + result = tc.reply.status; + if ( result != Status_OK ) + { + printf( "error(%d) : reply.status(Cmd_Encrypt)\n", result ); + return 0; + } + enc_output.len = tc.reply.reply.encrypt.cipher.data.generic128.cipher.len; + if ( enc_output.len != DATA_LEN ) + { + printf( "error : output data size isn't %d bytes(Cmd_Encrypt)\n", (int)enc_output.len ); + return 0; + } + enc_output.ptr = (unsigned char*)malloc( enc_output.len ); + memcpy( enc_output.ptr, + tc.reply.reply.encrypt.cipher.data.generic128.cipher.ptr, + enc_output.len ); + + printf( "encrypt ok.\n" ); + + dec_input.len = enc_output.len; + dec_input.ptr = (unsigned char*)malloc( dec_input.len ); + memcpy( dec_input.ptr, enc_output.ptr, DATA_LEN ); + + NFastApp_Free_Reply( handle, NULL, NULL, &(tc.reply) ); + + // decrypt : my ver + tc.cmd.cmd = Cmd_Decrypt; + tc.cmd.args.decrypt.flags = 0; + tc.cmd.args.decrypt.key = keyid; + tc.cmd.args.decrypt.mech = Mech_RijndaelmCBCpNONE; + tc.cmd.args.decrypt.cipher.mech = Mech_RijndaelmCBCpNONE; + tc.cmd.args.decrypt.cipher.data.generic128.cipher = dec_input; + tc.cmd.args.decrypt.cipher.iv = dec_iv.iv; + tc.cmd.args.decrypt.reply_type = PlainTextType_Bytes; + result = NFastApp_Transact( nc, NULL, &(tc.cmd), &(tc.reply), NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : FastApp_Transact(Cmd_Decrypt)\n", result ); + return 0; + } + result = tc.reply.status; + if ( result != Status_OK ) + { + printf( "error(%d) : reply.status(Cmd_Decrypt)\n", result ); + return 0; + } + dec_output.len = tc.reply.reply.decrypt.plain.data.bytes.data.len; + if ( dec_output.len != DATA_LEN ) + { + printf( "error : output size isn't %d bytes(Cmd_Decrypt)\n", (int)enc_output.len ); + return 0; + } + dec_output.ptr = (unsigned char*)malloc( dec_output.len ); + memcpy( dec_output.ptr, + tc.reply.reply.decrypt.plain.data.bytes.data.ptr, + dec_output.len ); + + printf( "decrypt ok.\n" ); + + NFastApp_Free_Reply( handle, NULL, NULL, &(tc.reply) ); + + // key destroy + memset( &(tc.cmd), 0, sizeof( tc.cmd ) ); // fail if NFastApp_Free_Command + tc.cmd.cmd = Cmd_Destroy; + tc.cmd.args.destroy.key = keyid; + result = NFastApp_Transact( nc, NULL, &(tc.cmd), &(tc.reply), NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFastApp_Transact(Cmd_Destroy)\n", result ); + return 0; + } + NFastApp_Free_Reply( handle, NULL, NULL, &(tc.reply) ); + + // data show + printf( "enc_input : (%d bytes)", (int)enc_input.len ); + for ( i = 0; i < enc_input.len; i++ ) + { + if ( i % 16 == 0 ) + printf( "\n" ); + printf( "%02X ", enc_input.ptr[i] ); + } + printf( "\n" ); + + printf( "\nenc_output : (%d bytes)", (int)enc_output.len ); + for ( i = 0; i < enc_output.len; i++ ) + { + if ( i % 16 == 0 ) + printf( "\n" ); + printf( "%02X ", enc_output.ptr[i] ); + } + printf( "\n" ); + + printf( "\ndec_output : (%d bytes)", (int)dec_output.len ); + for ( i = 0; i < dec_output.len; i++ ) + { + if ( i % 16 == 0 ) + printf( "\n" ); + printf( "%02X ", dec_output.ptr[i] ); + } + printf( "\n" ); + } // encrypt & decrypt + + // end processing + RQCard_fips_free( &card, &fips ); + RQCard_destroy( &card ); + NFKM_freekey( handle, keyinfo, NULL ); + NFKM_freeinfo( handle, &world, NULL ); + NFastApp_Disconnect( nc, NULL ); + NFastApp_Finish( handle, NULL ); + + return 0; + +} // main diff --git a/tags/20100201_Sharp_Release/hsm_utils/import_ecdsa_keypair.c b/tags/20100201_Sharp_Release/hsm_utils/import_ecdsa_keypair.c new file mode 100644 index 0000000..993bb96 --- /dev/null +++ b/tags/20100201_Sharp_Release/hsm_utils/import_ecdsa_keypair.c @@ -0,0 +1,968 @@ + +// import key (+ encrypt, decrypt) test for nShield + +#include +#include +#include +#include + +// openssl +#include +#include +#include +#include +#include "ec_lcl.h" +#include +#include +#include + +#include "nfastapp.h" +#include "nfkm.h" +#include "rqcard-applic.h" +#include "rqcard-fips.h" + +#include "my_hsm_bignum.h" +#include "my_hsm_alloc.h" + +#define PRIV_KEY_FILE "/opt/nfast/work/ctr_eFuse/hsm_utils/real_key/hoge/NintendoCTR2_privkey_prod.der" +#define PUB_KEY_FILE "/opt/nfast/work/ctr_eFuse/hsm_utils/real_key/hoge/NintendoCTR2_pubkey_prod.der" + +#define MODULE_ID 1 +#define DATA_LEN 256 // bytes + +#define SIGN_MECH Mech_ECDSA + +#define CROSS_VERIFY +//#define CARD_PROTECT +//#define EXPORT_KEY +//#define STRICT_FIPS + +// ECDSA private key data +typedef struct +{ + struct NFast_Bignum *d; +} +ECDSAPrivateKeyDataBn; + +// ECDSA public key data +typedef struct +{ + struct NFast_Bignum *qx; + struct NFast_Bignum *qy; +} +ECDSAPublicKeyDataBn; + +// global variable +NFast_AppHandle handle; +NFastApp_Connection nc; +NFKM_WorldInfo *world = NULL; +RQCard card; +RQCard_FIPS fips; +M_KeyID ltid = 0; // the cardset loaded into the module +NFKM_CardSet *cardset = NULL; +NFKM_ModuleInfo *moduleinfo = NULL; +const NFKM_KeyIdent priv_keyident = { (char*)"simple", (char*)"nct2-priv-hoge" }; +const NFKM_KeyIdent pub_keyident = { (char*)"simple", (char*)"nct2-pub-hoge" }; + +unsigned char save_enc[DATA_LEN]; + +// global var +EC_KEY *ecPriv = NULL; +EC_KEY *ecPub = NULL; + +// function +int importECDSAPrivate( NFKM_KeyIdent keyident ); +int importECDSAPublic( NFKM_KeyIdent keyident ); +int verifyECDSAKeyPair( NFKM_KeyIdent priv_keyident, NFKM_KeyIdent pub_keyident ); +void PrintArray( char *pStr, const unsigned char *pData, int length ); + +int importECDSAPrivate( NFKM_KeyIdent keyident ) +{ + int result = Status_OK; + + FILE *fp; + + unsigned char *dPtr = NULL; + int dLen = 0; + + M_Command cmd; + M_Reply reply; + NFKM_MakeACLParams map; + NFKM_MakeBlobsParams mbp; + NFKM_Key reg_key; + ECDSAPrivateKeyDataBn privBn; + + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + memset( &map, 0, sizeof( map ) ); + memset( &mbp, 0, sizeof( mbp ) ); + memset( ®_key, 0, sizeof( reg_key ) ); + memset( &privBn, 0, sizeof( privBn ) ); + + // key data open + printf( "priv key file : %s\n", PRIV_KEY_FILE ); + fp = fopen( PRIV_KEY_FILE, "rb" ); + if ( !fp ) + { + printf( "error : open %s file\n", PRIV_KEY_FILE ); + return 1; + } + ecPriv = d2i_ECPrivateKey_fp( fp, NULL ); + if ( !ecPriv ) + { + printf( "error : d2i_ECPrivateKey_fp\n" ); + return 1; + } + fclose( fp ); + +#if 1 + printf( "\nEC(d) = " ); + BN_print_fp( stdout, ecPriv->priv_key ); + printf( "\n" ); +#endif + +#if 0 + printf( "EC bignum(Openssl) size\n" ); + printf( "EC(d) : %d bytes\n", BN_num_bytes( privkey->priv_key ) ); +#endif + + // ECDSA priv key の構成要素をバイナリに変換 + { + // d + dLen = BN_num_bytes( ecPriv->priv_key ); + dPtr = (unsigned char *)malloc( dLen ); + if ( dLen != BN_bn2bin( ecPriv->priv_key, dPtr ) ) + { + printf( "BN_bn2bin failed!(d)\n" ); + return 1; + } + } // ec bignum(openssl) -> bin + +#if 0 + printf( "EC bin addr\n" ); + printf( "EC(d) : 0x%08X\n", (unsigned int)dPtr ); +#endif + + // バイナリをHSMのBignumに変換 + { + my_bin2bignum( &(privBn.d), handle, dPtr, dLen ); + free( dPtr ); + } + +#if 0 + my_printbignum ( stdout, "EC(d)", privBn.d ); +#endif + +#if 0 + printf( "EC bn addr\n" ); + printf( "EC(d) : 0x%08X\n", (unsigned int)privBn.d ); +#endif + + // make ACL + if ( cardset != NULL ) + map.f = NFKM_NKF_RecoveryEnabled | NFKM_NKF_ProtectionCardSet; + else + map.f = NFKM_NKF_RecoveryEnabled | NFKM_NKF_ProtectionModule; + // 秘密鍵には DECRYPT と SIGN + // 公開鍵には ENCRYPT と VERIFY しかセットできない?? +#ifdef EXPORT_KEY + map.op_base = NFKM_DEFOPPERMS_SIGN | Act_OpPermissions_Details_perms_ExportAsPlain; // for debug +#else + map.op_base = NFKM_DEFOPPERMS_SIGN; // ECDSA priv key : sign only +#endif // EXPORT_KEY + map.cs = cardset; + result = NFKM_newkey_makeaclx( handle, nc, world, &map, &(cmd.args.import.acl), NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_newkey_makeaclx\n", result ); + return result; + } + + // import key + cmd.cmd = Cmd_Import; + cmd.args.import.module = MODULE_ID; + cmd.args.import.data.type = KeyType_ECDSAPrivate; + cmd.args.import.data.data.ecprivate.curve.name = ECName_NISTB233; // 名前を指定することで + cmd.args.import.data.data.ecprivate.d = privBn.d; // d だけ設定すれば良い + result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : Cmd_Import\n", result ); + return 1; + } + result = reply.status; + if ( result != Status_OK ) + { + printf( "error(%d) : Cmd_Import(reply)\n", result ); + return 1; + } + + // make blobs + //reg_key.v = Key__maxversion; // TORIAEZU : Key__maxversion = 8 + reg_key.name = keyident.ident; + reg_key.appname = keyident.appname; + reg_key.ident = keyident.ident; + time( &(reg_key.gentime) ); + mbp.f = map.f; + mbp.kpriv = reply.reply.import.key; + mbp.lt = ltid; + mbp.cs = cardset; + result = NFKM_newkey_makeblobsx( handle, nc, world, &mbp, ®_key, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_newkey_makeblobsx\n", result ); + return 1; + } + + // record key to disk + result = NFKM_recordkey( handle, ®_key, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_recordkey\n", result ); + return 1; + } + + // destroy key + result = NFKM_cmd_destroy( handle, nc, 0, reply.reply.import.key, "destroy import key", NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_cmd_destroy\n", result ); + return 1; + } + + printf( "priv key record success : appname=%s, ident=%s\n", + priv_keyident.appname, priv_keyident.ident ); + + return result; +} // importECDSAPrivate + +int importECDSAPublic( NFKM_KeyIdent keyident ) +{ + int result = Status_OK; + + FILE *fp; + + unsigned char *qxPtr, *qyPtr; + int qxLen, qyLen; + + M_Command cmd; + M_Reply reply; + NFKM_MakeACLParams map; + NFKM_MakeBlobsParams mbp; + NFKM_Key reg_key; + ECDSAPublicKeyDataBn pubBn; + + qxPtr = qyPtr = NULL; + qxLen = qyLen = 0; + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + memset( &map, 0, sizeof( map ) ); + memset( &mbp, 0, sizeof( mbp ) ); + memset( ®_key, 0, sizeof( reg_key ) ); + memset( &pubBn, 0, sizeof( pubBn ) ); + + // key data open + printf( "pub key file : %s\n", PUB_KEY_FILE ); + fp = fopen( PUB_KEY_FILE, "rb" ); + if ( !fp ) + { + printf( "error : open %s file\n", PUB_KEY_FILE ); + return 1; + } + ecPub = d2i_EC_PUBKEY_fp( fp, NULL ); + if ( !ecPub ) + { + printf( "error : d2i_EC_PUBKEY_fp\n" ); + return 1; + } + fclose( fp ); + +#if 1 + printf( "\nEC(Q->x) = " ); + BN_print_fp( stdout, &(ecPub->pub_key->X) ); + printf( "\nEC(Q->y) = " ); + BN_print_fp( stdout, &(ecPub->pub_key->Y) ); + printf( "\n" ); +#endif + +#if 0 + printf( "EC bignum(Openssl) size\n" ); + printf( "EC(qx) : %d bytes\n", BN_num_bytes( &pubkey->pub_key->X ) ); + + printf( "EC(qy) : %d bytes\n", BN_num_bytes( &pubkey->pub_key->Y ) ); +#endif + + // ECDSA public key の構成要素をそれぞれバイナリに変換 + { + // qx + qxLen = BN_num_bytes( &ecPub->pub_key->X ); + qxPtr = (unsigned char *)malloc( qxLen ); + if ( qxLen != BN_bn2bin( &ecPub->pub_key->X, qxPtr ) ) + { + printf( "BN_bn2bin failed!(qx)\n" ); + return 1; + } + // qy + qyLen = BN_num_bytes( &ecPub->pub_key->Y ); + qyPtr = (unsigned char *)malloc( qyLen ); + if ( qyLen != BN_bn2bin( &ecPub->pub_key->Y, qyPtr ) ) + { + printf( "BN_bn2bin failed!(qy)\n" ); + return 1; + } + } // ECDSA bignum(openssl) -> bin + +#if 0 + printf( "EC bin addr\n" ); + printf( "EC(qx) : 0x%08X\n", (unsigned int)qxPtr ); + printf( "EC(qy) : 0x%08X\n", (unsigned int)qyPtr ); +#endif + + // バイナリをHSMのBignumに変換 + { + my_bin2bignum( &(pubBn.qx), handle, qxPtr, qxLen ); + my_bin2bignum( &(pubBn.qy), handle, qyPtr, qyLen ); + free( qxPtr ); + free( qyPtr ); + } + +#if 0 + printf( "EC bn addr\n" ); + printf( "EC(qx) : 0x%08X\n", (unsigned int)pubBn.qx ); + printf( "EC(qy) : 0x%08X\n", (unsigned int)pubBn.qy ); +#endif + + // make ACL + if ( cardset != NULL ) + map.f = NFKM_NKF_RecoveryEnabled | NFKM_NKF_ProtectionCardSet | NFKM_NKF_PublicKey; + else + map.f = NFKM_NKF_RecoveryEnabled | NFKM_NKF_ProtectionModule | NFKM_NKF_PublicKey; + // 秘密鍵には DECRYPT と SIGN + // 公開鍵には ENCRYPT と VERIFY しかセットできない?? +#ifdef EXPORT_KEY + map.op_base = NFKM_DEFOPPERMS_VERIFY | Act_OpPermissions_Details_perms_ExportAsPlain; // for debug (maybe, pub key has an export permission as default.) +#else + map.op_base = NFKM_DEFOPPERMS_VERIFY; // ECDSA public key : verify only +#endif // EXPORT_KEY + map.cs = cardset; + result = NFKM_newkey_makeaclx( handle, nc, world, &map, &(cmd.args.import.acl), NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_newkey_makeaclx\n", result ); + return result; + } + + // import key + cmd.cmd = Cmd_Import; + cmd.args.import.module = MODULE_ID; + cmd.args.import.data.type = KeyType_ECDSAPublic; + cmd.args.import.data.data.ecpublic.curve.name = ECName_NISTB233; // 名前を指定することで + cmd.args.import.data.data.ecpublic.Q.x = pubBn.qx; // qx + cmd.args.import.data.data.ecpublic.Q.y = pubBn.qy; // qy だけを指定すればよい? + result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : Cmd_Import\n", result ); + return 1; + } + result = reply.status; + if ( result != Status_OK ) + { + printf( "error(%d) : Cmd_Import(reply)\n", result ); + return 1; + } + + // make blobs + //reg_key.v = Key__maxversion; // TORIAEZU : Key__maxversion = 8 + reg_key.name = keyident.ident; + reg_key.appname = keyident.appname; + reg_key.ident = keyident.ident; + time( &(reg_key.gentime) ); + mbp.f = map.f; + mbp.kpub = reply.reply.import.key; + mbp.lt = ltid; + mbp.cs = cardset; + result = NFKM_newkey_makeblobsx( handle, nc, world, &mbp, ®_key, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_newkey_makeblobsx\n", result ); + return 1; + } + + // record key to disk + result = NFKM_recordkey( handle, ®_key, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_recordkey\n", result ); + return 1; + } + + // destroy key + result = NFKM_cmd_destroy( handle, nc, 0, reply.reply.import.key, "destroy import key", NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_cmd_destroy\n", result ); + return 1; + } + + printf( "pub key record success : appname=%s, ident=%s\n", + pub_keyident.appname, pub_keyident.ident ); + + return result; +} // importECDSAPublic + +int verifyECDSAKeyPair( NFKM_KeyIdent priv_ident, NFKM_KeyIdent pub_ident ) +{ + int i; + int result = Status_OK; + M_ByteBlock *blobptr = NULL; + M_KeyID priv_keyid, pub_keyid; + NFKM_Key *keyinfo = NULL; + M_Command cmd; + M_Reply reply; + + priv_keyid = pub_keyid = 0; + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // find priv key + result = NFKM_findkey( handle, priv_ident, &keyinfo, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_findkey(priv)\n", result ); + return result; + } + + // load priv key blob + blobptr = &(keyinfo->privblob); + result = NFKM_cmd_loadblob( handle, nc, + moduleinfo->module, blobptr, ltid, &priv_keyid, "loading priv key blob", NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_cmd_loadblob(priv)\n", result ); + return result; + } + NFKM_freekey( handle, keyinfo, NULL ); + keyinfo = NULL; + +#if 0 + // get priv key info + cmd.cmd = Cmd_GetKeyInfo; + cmd.args.getkeyinfo.key = priv_keyid; + result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : FastApp_Transact(Cmd_GetKeyInfo)\n", result ); + return result; + } + printf( "priv key ID : %08X\n", (unsigned int)priv_keyid ); + printf( "priv keytype : %d\n", reply.reply.getkeyinfo.type ); + NFastApp_Free_Command( handle, NULL, NULL, &cmd ); + NFastApp_Free_Reply( handle, NULL, NULL, &reply ); + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); +#endif + + // find pub key + result = NFKM_findkey( handle, pub_ident, &keyinfo, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_findkey(pub)\n", result ); + return result; + } + + // load pub key blob + blobptr = &(keyinfo->pubblob); // pub dakedo privblob + result = NFKM_cmd_loadblob( handle, nc, + moduleinfo->module, blobptr, ltid, &pub_keyid, "loading pub key blob", NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_cmd_loadblob(pub)\n", result ); + return result; + } + NFKM_freekey( handle, keyinfo, NULL ); + keyinfo = NULL; + +#if 0 + // get priv key info + cmd.cmd = Cmd_GetKeyInfo; + cmd.args.getkeyinfo.key = pub_keyid; + result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : FastApp_Transact(Cmd_GetKeyInfo)\n", result ); + return result; + } + printf( "pub key ID : %08X\n", (unsigned int)pub_keyid ); + printf( "pub keytype : %d\n", reply.reply.getkeyinfo.type ); + NFastApp_Free_Command( handle, NULL, NULL, &cmd ); + NFastApp_Free_Reply( handle, NULL, NULL, &reply ); + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + keyinfo = NULL; +#endif + + // export key pair +#ifdef EXPORT_KEY + // priv key export + cmd.cmd = Cmd_Export; + cmd.args.export.key = priv_keyid; + result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : FastApp_Transact(Cmd_Export)\n", result ); + return 1; + } + result = reply.status; + if ( result != Status_OK ) + { + printf( "error(%d) : reply.status(Cmd_Export)\n", result ); + return 1; + } + + printf( "----- export : priv key -----\n" ); + printf( "key type : %d\n", reply.reply.export.data.type ); + printf( "curve namee : %d\n", reply.reply.export.data.data.ecprivate.curve.name ); + my_printbignum( stdout, "d", reply.reply.export.data.data.ecprivate.d ); + printf( "-----------------------------\n" ); + + NFastApp_Free_Reply( handle, NULL, NULL, &reply ); + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // pub key export + cmd.cmd = Cmd_Export; + cmd.args.export.key = pub_keyid; + result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : FastApp_Transact(Cmd_Export)\n", result ); + return 1; + } + result = reply.status; + if ( result != Status_OK ) + { + printf( "error(%d) : reply.status(Cmd_Export)\n", result ); + return 1; + } + + printf( "----- export : priv key -----\n" ); + printf( "key type : %d\n", reply.reply.export.data.type ); + printf( "curve namee : %d\n", reply.reply.export.data.data.ecpublic.curve.name ); + my_printbignum( stdout, "Q->x", reply.reply.export.data.data.ecpublic.Q.x ); + my_printbignum( stdout, "Q->y", reply.reply.export.data.data.ecpublic.Q.y ); + printf( "-----------------------------\n" ); + + NFastApp_Free_Reply( handle, NULL, NULL, &reply ); + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); +#endif // EXPORT_KEY + + // sign & verify test + { + M_Hash hash; + + struct NFast_Bignum *rBn, *sBn; + unsigned char *rPtr, *sPtr; + int rLen, sLen; + + rBn = sBn = NULL; + rPtr = sPtr = NULL; + rLen = sLen = 0; + + // hash data + for ( i = 0; i < 20; i++ ) + hash.bytes[i] = i+1; +#if 1 + PrintArray( (char*)"hash", hash.bytes, 20 ); +#endif + + // sign transact + cmd.cmd = Cmd_Sign; + cmd.args.sign.flags = 0; // Cmd_Sign_Args_flags_given_iv_present; + cmd.args.sign.key = priv_keyid; + cmd.args.sign.mech = SIGN_MECH; + cmd.args.sign.plain.type = PlainTextType_Hash; + cmd.args.sign.plain.data.hash.data = hash; + + result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : FastApp_Transact(Cmd_Sign)\n", result ); + return 1; + } + result = reply.status; + if ( result != Status_OK ) + { + printf( "error(%d) : reply.status(Cmd_Sign)\n", result ); + return 1; + } + if ( SIGN_MECH != reply.reply.sign.sig.mech ) + { + printf( "error : reply mech isn't match %d!\n", SIGN_MECH ); + return 1; + } + printf( "ECDSA sign ok\n" ); + + // signature bignum -> bin + printf ( "sig mech : %d\n", reply.reply.sign.sig.mech ); + rLen = reply.reply.sign.sig.data.ecdsa.r->nbytes; + rPtr = (unsigned char*)malloc( rLen ); + my_bignum2bin ( rPtr, rLen, handle, reply.reply.sign.sig.data.ecdsa.r ); + sLen = reply.reply.sign.sig.data.ecdsa.s->nbytes; + sPtr = (unsigned char*)malloc( sLen ); + my_bignum2bin ( sPtr, sLen, handle, reply.reply.sign.sig.data.ecdsa.s ); + my_bignumCopy( &rBn, reply.reply.sign.sig.data.ecdsa.r, handle ); + my_bignumCopy( &sBn, reply.reply.sign.sig.data.ecdsa.s, handle ); +#if 1 + PrintArray( (char*)"sig r", rPtr, rLen ); + PrintArray( (char*)"sig s", sPtr, sLen ); +#endif + + //NFastApp_Free_Command( handle, NULL, NULL, &cmd ); + NFastApp_Free_Reply( handle, NULL, NULL, &reply ); + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // verify transact + cmd.cmd = Cmd_Verify; + cmd.args.verify.flags = 0; + cmd.args.verify.key = pub_keyid; + cmd.args.verify.mech = SIGN_MECH; + cmd.args.verify.plain.type = PlainTextType_Hash; + cmd.args.verify.plain.data.hash.data = hash; + cmd.args.verify.sig.mech = SIGN_MECH; + cmd.args.verify.sig.data.ecdsa.r = rBn; + cmd.args.verify.sig.data.ecdsa.s = sBn; + result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : FastApp_Transact(Cmd_Decrypt)\n", result ); + return 1; + } + result = reply.status; + if ( result != Status_OK ) + { + printf( "error(%d) : reply.status(Cmd_Decrypt)\n", result ); + return 1; + } + + printf( "ECDSA verify ok!\n" ); + + NFastApp_Free_Command( handle, NULL, NULL, &cmd ); + NFastApp_Free_Reply( handle, NULL, NULL, &reply ); + +#ifdef CROSS_VERIFY + unsigned char compareBuf[0x80]; + int sigLen = 0; + const unsigned char *pECDSAsig = compareBuf; + ECDSA_SIG *sig = NULL; + + unsigned char *rOPtr, *sOPtr; + int rOLen, sOLen; + struct NFast_Bignum *rBnO, *sBnO; + + memset( compareBuf, 0, sizeof( compareBuf ) ); + + result = ECDSA_sign( 0, hash.bytes, 20, compareBuf, &sigLen, ecPriv ); + if ( result == 0) + { + printf( "error : ECDSA_sign(by OpenSSL)!\n" ); + return 1; + } + + sig = d2i_ECDSA_SIG( NULL, &pECDSAsig, sigLen ); + if( sig == NULL ) + { + printf( "error : d2i_ECDSA_SIG(by OpenSSL)!\n" ); + return 1; + } +#if 0 + PrintArray( (char*)"OpenSSL:sig r", (const char*)sig->r->d, sig->r->dmax*4 ); + PrintArray( (char*)"OpenSSL:sig s", (const char*)sig->s->d, sig->s->dmax*4 ); +#endif + + // OpenSSL r&S -> bin -> HSM r&s + rOLen = BN_num_bytes( sig->r ); + rOPtr = (unsigned char *)malloc( rOLen ); + if ( rOLen != BN_bn2bin( sig->r, rOPtr ) ) + { + printf( "BN_bn2bin failed!(sig->r)\n" ); + return 1; + } + sOLen = BN_num_bytes( sig->s ); + sOPtr = (unsigned char *)malloc( sOLen ); + if ( sOLen != BN_bn2bin( sig->s, sOPtr ) ) + { + printf( "BN_bn2bin failed!(sig->s)\n" ); + return 1; + } + my_bin2bignum( &rBnO, handle, rOPtr, rOLen ); + my_bin2bignum( &sBnO, handle, sOPtr, sOLen ); + + // verify sign for HSM hash + //NFastApp_Free_Command( handle, NULL, NULL, &cmd ); + NFastApp_Free_Reply( handle, NULL, NULL, &reply ); + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // verify transact + cmd.cmd = Cmd_Verify; + cmd.args.verify.flags = 0; + cmd.args.verify.key = pub_keyid; + cmd.args.verify.mech = SIGN_MECH; + cmd.args.verify.plain.type = PlainTextType_Hash; + cmd.args.verify.plain.data.hash.data = hash; + cmd.args.verify.sig.mech = SIGN_MECH; + cmd.args.verify.sig.data.ecdsa.r = rBnO; + cmd.args.verify.sig.data.ecdsa.s = sBnO; + result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : FastApp_Transact(Cmd_Decrypt)\n", result ); + return 1; + } + result = reply.status; + if ( result != Status_OK ) + { + printf( "error(%d) : reply.status(Cmd_Decrypt)\n", result ); + return 1; + } + + printf( "OpenSSL sign(r&s) verified by HSM!\n" ); + + // verify HSM signature by OpenSSL + { + unsigned char tempSign[70]; + tempSign[0] = 0x30; + tempSign[1] = 0x3E; + tempSign[2] = 0x02; + tempSign[3] = 0x1D; + memcpy( &tempSign[4], &rPtr[3], 0x1D ); + tempSign[0x21] = 0x02; + tempSign[0x22] = 0x1D; + memcpy( &tempSign[0x23], &sPtr[3], 0x1D ); + PrintArray( (char*)"tempSign(HSM)", (const char *)tempSign, 0x3E + 2 ); + + result = ECDSA_verify( 0, hash.bytes, 20, tempSign, 0x3E + 2, ecPub ); + if( result != 1) + { + printf( "error : ECDSA_verify(by OpenSSL)!\n" ); + return 1; + } + } + + printf( "HSM sign(r&s) verified by OpenSSL!\n" ); + result = 0; +#endif // CROSS_VERIFY + } // encrypt & decrypt + + return result; +} // verifyECDSAkeypair + +void PrintArray( char *pStr, const unsigned char *pData, int length ) +{ + int i; + printf( "%s(%d bytes)", pStr, length ); + for ( i = 0; i < length; i++ ) + { + if ( (i % 16) == 0 ) printf( "\n" ); + printf( "%02X ", pData[ i ] ); + } + printf( "\n" ); +} // PrintArray + +int main( int argc, char *argv[] ) +{ + int result = Status_OK; + + M_Command cmd; + M_Reply reply; + + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // init nFast + result = NFastApp_InitEx( &handle, NULL, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFastApp_InitEx\n", result ); + return 1; + } + + // connecting to hardserver + result = NFastApp_Connect( handle, &nc, 0, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFastApp_Connect\n", result ); + return 1; + } + + // set bignum upcalls setting + result = NFastApp_SetBignumUpcalls( + handle, + my_bignumreceiveupcall, + my_bignumsendlenupcall, + my_bignumsendupcall, + my_bignumfreeupcall, + my_bignumformatupcall, + NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFastApp_SetBignumUpcalls\n", result ); + return 1; + } + + // NFKM getinfo + result = NFKM_getinfo( handle, &world, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_getinfo\n", result ); + return 1; + } + + // init card-loading lib + result = RQCard_init( &card, handle, nc, world, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : RQCard_init\n", result ); + return 1; + } + + // init FIPS state + result = RQCard_fips_init( &card, &fips ); + if ( result != Status_OK ) + { + printf( "error(%d) : RQCard_fips_init\n", result ); + return 1; + } + + // ui select + result = RQCard_ui_default( &card ); + if ( result != Status_OK ) + { + printf( "error(%d) : RQCard_ui_default\n", result ); + return 1; + } + + // get strict-FIPS authorization +#ifdef STRICT_FIPS + NFKM_FIPS140AuthHandle fipsHandle; + M_SlotID slotId; + result = RQCard_fips_get( &fips, 1, &fipsHandle, &slotId ); + if ( result != Status_OK ) + { + printf( "error(%d) : RQCard_fips_get\n", result ); + return 0; + } + if ( fipsHandle == NULL ) + { + printf( "this sworld isn't strict-FIPS.\n" ); + } +#endif + +#ifdef CARD_PROTECT + // list cardsets + int card_num; + NFKM_CardSetIdent *cardident = NULL; + result = NFKM_listcardsets( handle, &card_num, &cardident, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_listcardsets\n", result ); + return 0; + } + + // find cardsets + result = NFKM_findcardset( handle, cardident, &cardset, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_findcardset\n", result ); + return 0; + } + + // load cardset + result = RQCard_logic_ocs_specific( &card, &(cardset->hkltu), "Load Cardset" ); + if ( result != Status_OK ) + { + printf( "error(%d) : RQCard_logic_ocs_specific\n", result ); + return 0; + } + + // use specific module : #1 + // important!! : if you set resultplace=NULL, abort. (possibility is 100%) + result = RQCard_whichmodule_specific( &card, world->modules[0]->module, <id ); + if ( result != Status_OK ) + { + printf( "error(%d) : RQCard_whichmodule_specific\n", result ); + } + + // wait event loop + result = card.uf->eventloop( &card ); + if ( result != Status_OK ) + { + printf( "error(%d) : card module event loop\n", result ); + } +#endif // CARD_PROTECT + + // get usable module + moduleinfo = world->modules[0]; + result = NFKM_getusablemodule( world, MODULE_ID, &moduleinfo ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_getusablemodule\n", result ); + return 1; + } + + // ECDSA privkey のインポート + result = importECDSAPrivate( priv_keyident ); + if ( result != Status_OK ) + { + printf( "error : importECDSAPrivate\n" ); + return 1; + } + printf( "ECDSA privkey import success.\n" ); + + // ECDSA pubkey + result = importECDSAPublic( pub_keyident ); + if ( result != Status_OK ) + { + printf( "error : importECDSAPublic\n" ); + return 1; + } + printf( "ECDSA pubkey import success.\n" ); + + // list key +#if 0 + int key_num; + NFKM_KeyIdent *keylist = NULL; + result = NFKM_listkeys( handle, &key_num, &keylist, "simple", NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_listkeys\n", result ); + } + NFKM_KeyIdent **tkp = &keylist; + for ( i = 0; i < key_num; i++ ) + { + printf( "appname : %s, ident : %s\n", tkp[i]->appname, tkp[i]->ident ); + } +#endif + + // verify key pair + result = verifyECDSAKeyPair( priv_keyident, pub_keyident ); + if ( result != Status_OK ) + { + printf( "error : verifyECDSAKeyPair\n" ); + return 1; + } + printf( "ECDSA keypair verify success.\n" ); + + // end processing + RQCard_fips_free( &card, &fips ); + RQCard_destroy( &card ); + NFKM_freeinfo( handle, &world, NULL ); + NFastApp_Disconnect( nc, NULL ); + NFastApp_Finish( handle, NULL ); + + return 0; + +} // main diff --git a/tags/20100201_Sharp_Release/hsm_utils/import_rsa_keypair.c b/tags/20100201_Sharp_Release/hsm_utils/import_rsa_keypair.c new file mode 100644 index 0000000..b3f0a26 --- /dev/null +++ b/tags/20100201_Sharp_Release/hsm_utils/import_rsa_keypair.c @@ -0,0 +1,1007 @@ + +// import key (+ encrypt, decrypt) test for nShield + +#include +#include +#include +#include + +// openssl +#include +#include +#include +#include +#include +#include +#include + +#include "nfastapp.h" +#include "nfkm.h" +#include "rqcard-applic.h" +#include "rqcard-fips.h" + +//#include "picky-upcalls.h" + +#include "my_hsm_bignum.h" +#include "my_hsm_alloc.h" + +#define PRIV_KEY_FILE "/opt/nfast/work/rsa-priv-key2048.der" +#define PUB_KEY_FILE "/opt/nfast/work/rsa-pub-key2048.der" + +#define MODULE_ID 1 +#define DATA_LEN 256 // bytes + +// RSA private key data +typedef struct +{ + struct NFast_Bignum *p; + struct NFast_Bignum *q; + struct NFast_Bignum *dmp1; + struct NFast_Bignum *dmq1; + struct NFast_Bignum *iqmp; + struct NFast_Bignum *e; +} +RSAPrivateKeyDataBn; + +// RSA public key data +typedef struct +{ + struct NFast_Bignum *e; + struct NFast_Bignum *n; +} +RSAPublicKeyDataBn; + +// global variable +NFast_AppHandle handle; +NFastApp_Connection nc; +NFKM_WorldInfo *world = NULL; +RQCard card; +RQCard_FIPS fips; +M_KeyID ltid = 0; // the cardset loaded into the module +NFKM_CardSet *cardset = NULL; +NFKM_ModuleInfo *moduleinfo = NULL; +const NFKM_KeyIdent priv_keyident = { (char*)"simple", (char*)"rsa-import-privkey" }; +const NFKM_KeyIdent pub_keyident = { (char*)"simple", (char*)"rsa-import-pubkey" }; + +unsigned char save_enc[DATA_LEN]; + +// function +int importRSAPrivate( NFKM_KeyIdent keyident ); +int importRSAPublic( NFKM_KeyIdent keyident ); +int verifyRSAKeyPair( NFKM_KeyIdent priv_keyident, NFKM_KeyIdent pub_keyident ); +void PrintArray( char *pStr, const unsigned char *pData, int length ); + +int importRSAPrivate( NFKM_KeyIdent keyident ) +{ + int result = Status_OK; + + RSA *privkey = NULL; + FILE *fp; + + unsigned char *pPtr, *qPtr, *dmp1Ptr, *dmq1Ptr, *iqmpPtr, *ePtr; + int pLen, qLen, dmp1Len, dmq1Len, iqmpLen, eLen; + + M_Command cmd; + M_Reply reply; + NFKM_MakeACLParams map; + NFKM_MakeBlobsParams mbp; + NFKM_Key reg_key; + RSAPrivateKeyDataBn privBn; + + pPtr = qPtr = dmp1Ptr = dmq1Ptr = iqmpPtr = ePtr = NULL; + pLen = qLen = dmp1Len = dmq1Len = iqmpLen = eLen = 0; + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + memset( &map, 0, sizeof( map ) ); + memset( &mbp, 0, sizeof( mbp ) ); + memset( ®_key, 0, sizeof( reg_key ) ); + memset( &privBn, 0, sizeof( privBn ) ); + + // key data open + fp = fopen( PRIV_KEY_FILE, "rb" ); + if ( !fp ) + { + printf( "error : open %s file\n", PRIV_KEY_FILE ); + return 1; + } + privkey = d2i_RSAPrivateKey_fp( fp, NULL ); + if ( !privkey ) + { + printf( "error : d2i_RSAPrivateKey_fp\n" ); + return 1; + } + fclose( fp ); + +#if 0 + printf( "\nRSA(p) = " ); + BN_print_fp( stdout, privkey->p ); + printf( "\nRSA(q) = " ); + BN_print_fp( stdout, privkey->q ); + printf( "\nRSA(dmp1) = " ); + BN_print_fp( stdout, privkey->dmp1 ); + printf( "\nRSA(dmq1) = " ); + BN_print_fp( stdout, privkey->dmq1 ); + printf( "\nRSA(iqmp) = " ); + BN_print_fp( stdout, privkey->iqmp ); + printf( "\nRSA(e) = " ); + BN_print_fp( stdout, privkey->e ); + printf( "\n" ); +#endif + +#if 0 + printf( "RSA bignum(Openssl) size\n" ); + printf( "RSA(p) : %d bytes\n", BN_num_bytes( privkey->p ) ); + printf( "RSA(q) : %d bytes\n", BN_num_bytes( privkey->q ) ); + printf( "RSA(dmp1) : %d bytes\n", BN_num_bytes( privkey->dmp1 ) ); + printf( "RSA(dmq1) : %d bytes\n", BN_num_bytes( privkey->dmq1 ) ); + printf( "RSA(iqmp) : %d bytes\n", BN_num_bytes( privkey->iqmp ) ); + printf( "RSA(e) : %d bytes\n", BN_num_bytes( privkey->e ) ); +#endif + + // RSA priv key の構成要素をそれぞれバイナリに変換 + { + // p + pLen = BN_num_bytes( privkey->p ); + pPtr = (unsigned char *)malloc( pLen ); + if ( pLen != BN_bn2bin( privkey->p, pPtr ) ) + { + printf( "BN_bn2bin failed!(p)\n" ); + return 1; + } + // q + qLen = BN_num_bytes( privkey->q ); + qPtr = (unsigned char *)malloc( qLen ); + if ( qLen != BN_bn2bin( privkey->q, qPtr ) ) + { + printf( "BN_bn2bin failed!(q)\n" ); + return 1; + } + // dmp1 + dmp1Len = BN_num_bytes( privkey->dmp1 ); + dmp1Ptr = (unsigned char *)malloc( dmp1Len ); + if ( dmp1Len != BN_bn2bin( privkey->dmp1, dmp1Ptr ) ) + { + printf( "BN_bn2bin failed!(dmp1)\n" ); + return 1; + } + + // dmq1 + dmq1Len = BN_num_bytes( privkey->dmq1 ); + dmq1Ptr = (unsigned char *)malloc( dmq1Len ); + if ( dmq1Len != BN_bn2bin( privkey->dmq1, dmq1Ptr ) ) + { + printf( "BN_bn2bin failed!(dmq1)\n" ); + return 1; + } + // iqmp + iqmpLen = BN_num_bytes( privkey->iqmp ); + iqmpPtr = (unsigned char *)malloc( iqmpLen ); + if ( iqmpLen != BN_bn2bin( privkey->iqmp, iqmpPtr ) ) + { + printf( "BN_bn2bin failed!(dmq1)\n" ); + return 1; + } + // e + eLen = BN_num_bytes( privkey->e ); + ePtr = (unsigned char *)malloc( eLen ); + if ( eLen != BN_bn2bin( privkey->e, ePtr ) ) + { + printf( "BN_bn2bin failed!(e)\n" ); + return 1; + } + } // rsa bignum(openssl) -> bin + +#if 0 + printf( "RSA bin addr\n" ); + printf( "RSA(p) : 0x%08X\n", (unsigned int)pPtr ); + printf( "RSA(q) : 0x%08X\n", (unsigned int)qPtr ); + printf( "RSA(dmp1) : 0x%08X\n", (unsigned int)dmp1Ptr ); + printf( "RSA(dmq1) : 0x%08X\n", (unsigned int)dmq1Ptr ); + printf( "RSA(iqmp) : 0x%08X\n", (unsigned int)iqmpPtr ); + printf( "RSA(e) : 0x%08X\n", (unsigned int)ePtr ); +#endif + + // バイナリをHSMのBignumに変換 + { + my_bin2bignum( &(privBn.p), handle, pPtr, pLen ); + my_bin2bignum( &(privBn.q), handle, qPtr, qLen ); + my_bin2bignum( &(privBn.dmp1), handle, dmp1Ptr, dmp1Len ); + my_bin2bignum( &(privBn.dmq1), handle, dmq1Ptr, dmq1Len ); + my_bin2bignum( &(privBn.iqmp), handle, iqmpPtr, iqmpLen ); + my_bin2bignum( &(privBn.e), handle, ePtr, eLen ); + free( pPtr ); + free( qPtr ); + free( dmp1Ptr ); + free( dmq1Ptr ); + free( iqmpPtr ); + free( ePtr ); + } + +#if 0 + my_printbignum ( stdout, "RSA(p)", privBn.p ); + my_printbignum ( stdout, "RSA(q)", privBn.q ); + my_printbignum ( stdout, "RSA(dmp1)", privBn.dmp1 ); + my_printbignum ( stdout, "RSA(dmq1)", privBn.dmq1 ); + my_printbignum ( stdout, "RSA(iqmp)", privBn.iqmp ); + my_printbignum ( stdout, "RSA(e)", privBn.e ); +#endif + + +#if 0 + printf( "RSA bn addr\n" ); + printf( "RSA(p) : 0x%08X\n", (unsigned int)privBn.p ); + printf( "RSA(q) : 0x%08X\n", (unsigned int)privBn.q ); + printf( "RSA(dmp1) : 0x%08X\n", (unsigned int)privBn.dmp1 ); + printf( "RSA(dmq1) : 0x%08X\n", (unsigned int)privBn.dmq1 ); + printf( "RSA(iqmp) : 0x%08X\n", (unsigned int)privBn.iqmp ); + printf( "RSA(e) : 0x%08X\n", (unsigned int)privBn.e ); +#endif + +#if 0 + // imm dec + { + struct NFast_Bignum *dec_bn = NULL; + unsigned char *out = (unsigned char*)malloc( DATA_LEN ); + my_bin2bignum( &(dec_bn), handle, save_enc, DATA_LEN ); + + M_Command cmd; + M_Reply reply; + cmd.cmd = Cmd_RSAImmedSignDecrypt; + cmd.args.rsaimmedsigndecrypt.m = dec_bn; + cmd.args.rsaimmedsigndecrypt.k_p = privBn.p; + cmd.args.rsaimmedsigndecrypt.k_q = privBn.q; + cmd.args.rsaimmedsigndecrypt.k_dmp1 = privBn.dmp1; + cmd.args.rsaimmedsigndecrypt.k_dmq1 = privBn.dmq1; + cmd.args.rsaimmedsigndecrypt.k_iqmp = privBn.iqmp; + result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : imm dec\n", result ); + return 1; + } + result = reply.status; + if ( result != Status_OK ) + { + printf( "error(%d) : imm dec(reply)\n", result ); + return 1; + } + my_bignum2bin( out, DATA_LEN, handle, reply.reply.rsaimmedsigndecrypt.r ); + PrintArray( (char*)"imm dec before", save_enc, DATA_LEN ); + PrintArray( (char*)"imm dec after", out, reply.reply.rsaimmedsigndecrypt.r->nbytes ); + } // imm dec +#endif + + // make ACL + if ( cardset != NULL ) + map.f = NFKM_NKF_RecoveryEnabled | NFKM_NKF_ProtectionCardSet; + else + map.f = NFKM_NKF_RecoveryEnabled | NFKM_NKF_ProtectionModule; + // 秘密鍵には DECRYPT と SIGN + // 公開鍵には ENCRYPT と VERIFY しかセットできない?? + map.op_base = NFKM_DEFOPPERMS_DECRYPT | NFKM_DEFOPPERMS_SIGN; + map.cs = cardset; + result = NFKM_newkey_makeaclx( handle, nc, world, &map, &(cmd.args.import.acl), NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_newkey_makeaclx\n", result ); + return result; + } + + // import key + cmd.cmd = Cmd_Import; + cmd.args.import.module = MODULE_ID; + cmd.args.import.data.type = KeyType_RSAPrivate; + cmd.args.import.data.data.rsaprivate.p = privBn.p; + cmd.args.import.data.data.rsaprivate.q = privBn.q; + cmd.args.import.data.data.rsaprivate.dmp1 = privBn.dmp1; + cmd.args.import.data.data.rsaprivate.dmq1 = privBn.dmq1; + cmd.args.import.data.data.rsaprivate.iqmp = privBn.iqmp; + cmd.args.import.data.data.rsaprivate.e = privBn.e; + result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : Cmd_Import\n", result ); + return 1; + } + result = reply.status; + if ( result != Status_OK ) + { + printf( "error(%d) : Cmd_Import(reply)\n", result ); + return 1; + } + +#if 0 + // decrypt test kokode + { + struct NFast_Bignum *dec_bn = NULL; + unsigned char *out = (unsigned char*)malloc( DATA_LEN ); + my_bin2bignum( &(dec_bn), handle, save_enc, DATA_LEN ); + M_KeyID tempKey = reply.reply.import.key; + NFastApp_Free_Reply( handle, NULL, NULL, &reply ); + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + cmd.cmd = Cmd_Decrypt; + cmd.args.decrypt.flags = 0; + cmd.args.decrypt.key = tempKey; + cmd.args.decrypt.mech = Mech_RSApPKCS1; + cmd.args.decrypt.cipher.mech = Mech_RSApPKCS1; + cmd.args.decrypt.cipher.data.rsappkcs1.m = dec_bn; + cmd.args.decrypt.reply_type = PlainTextType_Bignum; + result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : FastApp_Transact(Cmd_Decrypt)\n", result ); + return 1; + } + result = reply.status; + if ( result != Status_OK ) + { + printf( "error(%d) : reply.status(Cmd_Decrypt)\n", result ); + return 1; + } + + my_bignum2bin( out, reply.reply.decrypt.plain.data.bignum.m->nbytes, handle, reply.reply.decrypt.plain.data.bignum.m ); + PrintArray( (char*)"foo dec before", save_enc, DATA_LEN ); + PrintArray( (char*)"foo dec after", out, reply.reply.decrypt.plain.data.bignum.m->nbytes ); + } // decrypt test +#endif + + // make blobs + //reg_key.v = Key__maxversion; // TORIAEZU : Key__maxversion = 8 + //reg_key.name = keyident.ident; + reg_key.appname = keyident.appname; + reg_key.ident = keyident.ident; + //time( &(reg_key.gentime) ); + mbp.f = map.f; + mbp.kpriv = reply.reply.import.key; + mbp.lt = ltid; + mbp.cs = cardset; + result = NFKM_newkey_makeblobsx( handle, nc, world, &mbp, ®_key, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_newkey_makeblobsx\n", result ); + return 1; + } + + // record key to disk + result = NFKM_recordkey( handle, ®_key, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_recordkey\n", result ); + return 1; + } + + // destroy key + result = NFKM_cmd_destroy( handle, nc, 0, reply.reply.import.key, "destroy import key", NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_cmd_destroy\n", result ); + return 1; + } + + return result; +} // import_rsa_private + +int importRSAPublic( NFKM_KeyIdent keyident ) +{ + int result = Status_OK; + + RSA *pubkey = NULL; + FILE *fp; + + unsigned char *ePtr, *nPtr; + int eLen, nLen; + + M_Command cmd; + M_Reply reply; + NFKM_MakeACLParams map; + NFKM_MakeBlobsParams mbp; + NFKM_Key reg_key; + RSAPublicKeyDataBn pubBn; + + ePtr = nPtr = NULL; + eLen = nLen = 0; + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + memset( &map, 0, sizeof( map ) ); + memset( &mbp, 0, sizeof( mbp ) ); + memset( ®_key, 0, sizeof( reg_key ) ); + memset( &pubBn, 0, sizeof( pubBn ) ); + + // key data open + fp = fopen( PUB_KEY_FILE, "rb" ); + if ( !fp ) + { + printf( "error : open %s file\n", PUB_KEY_FILE ); + return 1; + } + pubkey = d2i_RSA_PUBKEY_fp( fp, NULL ); + if ( !pubkey ) + { + printf( "error : d2i_RSA_PUBKEY_fp\n" ); + return 1; + } + fclose( fp ); + +#if 0 + printf( "RSA bignum(Openssl) size\n" ); + printf( "RSA(e) : %d bytes\n", BN_num_bytes( pubkey->e ) ); + + printf( "RSA(n) : %d bytes\n", BN_num_bytes( pubkey->n ) ); +#endif + + // RSA public key の構成要素をそれぞれバイナリに変換 + { + // e + eLen = BN_num_bytes( pubkey->e ); + ePtr = (unsigned char *)malloc( eLen ); + if ( eLen != BN_bn2bin( pubkey->e, ePtr ) ) + { + printf( "BN_bn2bin failed!(e)\n" ); + return 1; + } + // n + nLen = BN_num_bytes( pubkey->n ); + nPtr = (unsigned char *)malloc( nLen ); + if ( nLen != BN_bn2bin( pubkey->n, nPtr ) ) + { + printf( "BN_bn2bin failed!(n)\n" ); + return 1; + } + } // rsa bignum(openssl) -> bin + +#if 0 + printf( "RSA bin addr\n" ); + printf( "RSA(e) : 0x%08X\n", (unsigned int)ePtr ); + printf( "RSA(n) : 0x%08X\n", (unsigned int)nPtr ); +#endif + + // バイナリをHSMのBignumに変換 + { + my_bin2bignum( &(pubBn.e), handle, ePtr, eLen ); + my_bin2bignum( &(pubBn.n), handle, nPtr, nLen ); + free( ePtr ); + free( nPtr ); + } + +#if 0 + printf( "RSA bn addr\n" ); + printf( "RSA(e) : 0x%08X\n", (unsigned int)pubBn.e ); + printf( "RSA(n) : 0x%08X\n", (unsigned int)pubBn.n ); +#endif + +#if 0 + // imm enc + { + int i; + struct NFast_Bignum *enc_bn = NULL; + unsigned char *ptr = (unsigned char*)malloc( DATA_LEN - 11 ); + unsigned char *out = (unsigned char*)malloc( DATA_LEN ); + for ( i = 0; i < DATA_LEN - 11; i++ ) + ptr[i] = ~i; + my_bin2bignum( &(enc_bn), handle, ptr, DATA_LEN - 11 ); + + M_Command cmd; + M_Reply reply; + cmd.cmd = Cmd_RSAImmedVerifyEncrypt; + cmd.args.rsaimmedverifyencrypt.m = enc_bn; + cmd.args.rsaimmedverifyencrypt.k_e = pubBn.e; + cmd.args.rsaimmedverifyencrypt.k_n = pubBn.n; + result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : imm enc\n", result ); + return 1; + } + result = reply.status; + if ( result != Status_OK ) + { + printf( "error(%d) : imm enc(reply)\n", result ); + return 1; + } + my_bignum2bin( out, DATA_LEN, handle, reply.reply.rsaimmedsigndecrypt.r ); + PrintArray( (char*)"imm enc before", ptr, DATA_LEN - 11 ); + PrintArray( (char*)"imm enc after", out, reply.reply.rsaimmedsigndecrypt.r->nbytes ); + memcpy( save_enc, out, DATA_LEN ); + } // imm enc +#endif + + // make ACL + if ( cardset != NULL ) + map.f = NFKM_NKF_RecoveryEnabled | NFKM_NKF_ProtectionCardSet | NFKM_NKF_PublicKey; + else + map.f = NFKM_NKF_RecoveryEnabled | NFKM_NKF_ProtectionModule | NFKM_NKF_PublicKey; + // 秘密鍵には DECRYPT と SIGN + // 公開鍵には ENCRYPT と VERIFY しかセットできない?? + map.op_base = NFKM_DEFOPPERMS_ENCRYPT | NFKM_DEFOPPERMS_VERIFY; + map.cs = cardset; + result = NFKM_newkey_makeaclx( handle, nc, world, &map, &(cmd.args.import.acl), NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_newkey_makeaclx\n", result ); + return result; + } + + // import key + cmd.cmd = Cmd_Import; + cmd.args.import.module = MODULE_ID; + cmd.args.import.data.type = KeyType_RSAPublic; + cmd.args.import.data.data.rsapublic.e = pubBn.e; + cmd.args.import.data.data.rsapublic.n = pubBn.n; + result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : Cmd_Import\n", result ); + return 1; + } + result = reply.status; + if ( result != Status_OK ) + { + printf( "error(%d) : Cmd_Import(reply)\n", result ); + return 1; + } + + // make blobs + reg_key.v = Key__maxversion; // TORIAEZU : Key__maxversion = 8 + reg_key.name = keyident.ident; + reg_key.appname = keyident.appname; + reg_key.ident = keyident.ident; + time( &(reg_key.gentime) ); + mbp.f = map.f; + mbp.kpub = reply.reply.import.key; + mbp.lt = ltid; + mbp.cs = cardset; + result = NFKM_newkey_makeblobsx( handle, nc, world, &mbp, ®_key, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_newkey_makeblobsx\n", result ); + return 1; + } + + // record key to disk + result = NFKM_recordkey( handle, ®_key, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_recordkey\n", result ); + return 1; + } + + // destroy key + result = NFKM_cmd_destroy( handle, nc, 0, reply.reply.import.key, "destroy import key", NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_cmd_destroy\n", result ); + return 1; + } + + return result; +} // import_rsa_public + +int verifyRSAKeyPair( NFKM_KeyIdent priv_ident, NFKM_KeyIdent pub_ident ) +{ + int i; + int result = Status_OK; + M_ByteBlock *blobptr = NULL; + M_KeyID priv_keyid, pub_keyid; + NFKM_Key *keyinfo = NULL; + M_Command cmd; + M_Reply reply; + + priv_keyid = pub_keyid = 0; + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // find priv key + result = NFKM_findkey( handle, priv_ident, &keyinfo, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_findkey(priv)\n", result ); + return result; + } + + // load priv key blob + blobptr = &(keyinfo->privblob); + result = NFKM_cmd_loadblob( handle, nc, + moduleinfo->module, blobptr, ltid, &priv_keyid, "loading priv key blob", NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_cmd_loadblob(priv)\n", result ); + return result; + } + NFKM_freekey( handle, keyinfo, NULL ); + keyinfo = NULL; + +#if 0 + // get priv key info + cmd.cmd = Cmd_GetKeyInfo; + cmd.args.getkeyinfo.key = priv_keyid; + result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : FastApp_Transact(Cmd_GetKeyInfo)\n", result ); + return result; + } + printf( "priv key ID : %08X\n", (unsigned int)priv_keyid ); + printf( "priv keytype : %d\n", reply.reply.getkeyinfo.type ); + NFastApp_Free_Command( handle, NULL, NULL, &cmd ); + NFastApp_Free_Reply( handle, NULL, NULL, &reply ); + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); +#endif + + // find pub key + result = NFKM_findkey( handle, pub_ident, &keyinfo, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_findkey(pub)\n", result ); + return result; + } + + // load pub key blob + blobptr = &(keyinfo->pubblob); // pub dakedo privblob + result = NFKM_cmd_loadblob( handle, nc, + moduleinfo->module, blobptr, ltid, &pub_keyid, "loading pub key blob", NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_cmd_loadblob(pub)\n", result ); + return result; + } + NFKM_freekey( handle, keyinfo, NULL ); + keyinfo = NULL; + +#if 0 + // get priv key info + cmd.cmd = Cmd_GetKeyInfo; + cmd.args.getkeyinfo.key = pub_keyid; + result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : FastApp_Transact(Cmd_GetKeyInfo)\n", result ); + return result; + } + printf( "pub key ID : %08X\n", (unsigned int)pub_keyid ); + printf( "pub keytype : %d\n", reply.reply.getkeyinfo.type ); + NFastApp_Free_Command( handle, NULL, NULL, &cmd ); + NFastApp_Free_Reply( handle, NULL, NULL, &reply ); + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + keyinfo = NULL; +#endif + + // encrypt & dectypt test + { + unsigned char *beforePtr, *middlePtr, *afterPtr; + int beforeLen, middleLen, afterLen; + unsigned char *encPtr, *decPtr; + struct NFast_Bignum *enc_bn, *dec_bn; + M_Mech dec_mech; + + beforePtr = middlePtr = afterPtr = NULL; + beforeLen = middleLen = afterLen = 0; + encPtr = decPtr = NULL; + enc_bn = dec_bn = NULL; + + // encrypt data setting + beforeLen = DATA_LEN - 11; + beforePtr = (unsigned char*)malloc( beforeLen ); + for ( i = 0; i < beforeLen; i++ ) + beforePtr[i] = ~i; + my_bin2bignum( &(enc_bn), handle, beforePtr, beforeLen ); + +#if 0 + // my_bignum2bin test + unsigned char debug_buf[ DATA_LEN ]; + PrintArray( (char*)"beforePtr", beforePtr, DATA_LEN ); + printf( "beforePtr -> bin2bignum -> bignum2bin -> debug_buf\n" ); + my_bignum2bin( debug_buf, DATA_LEN, handle, enc_bn ); + PrintArray( (char*)"debug_buf", debug_buf, DATA_LEN ); +#endif + + // encrypt transact + cmd.cmd = Cmd_Encrypt; + cmd.args.encrypt.flags = 0; // Cmd_Encrypt_Args_flags_given_iv_present; + cmd.args.encrypt.key = pub_keyid; + cmd.args.encrypt.mech = Mech_RSApPKCS1; + cmd.args.encrypt.plain.type = PlainTextType_Bignum; + cmd.args.encrypt.plain.data.bignum.m = enc_bn; + //cmd.args.encrypt.given_iv = NULL; + result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : FastApp_Transact(Cmd_Encrypt)\n", result ); + return 1; + } + result = reply.status; + if ( result != Status_OK ) + { + printf( "error(%d) : reply.status(Cmd_Encrypt)\n", result ); + return 1; + } +#if 0 + if ( DATA_LEN != reply.reply.encrypt.cipher.data.rsappkcs1.m->nbytes ) + { + printf( "error : output size isn't %d bytes!\n", DATA_LEN ); + return 1; + } +#endif + + printf( "RSA data encrypt ok\n" ); + + // decrypt data setting + middleLen = reply.reply.encrypt.cipher.data.rsappkcs1.m->nbytes; + middlePtr = (unsigned char*)malloc( middleLen ); + my_bignum2bin( middlePtr, middleLen, handle, + reply.reply.encrypt.cipher.data.rsappkcs1.m ); + my_bin2bignum( &dec_bn, handle, middlePtr, middleLen ); + dec_mech = reply.reply.encrypt.cipher.mech; + + NFastApp_Free_Command( handle, NULL, NULL, &cmd ); + NFastApp_Free_Reply( handle, NULL, NULL, &reply ); + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // decrypt transact + cmd.cmd = Cmd_Decrypt; + cmd.args.decrypt.flags = 0; + cmd.args.decrypt.key = priv_keyid; + cmd.args.decrypt.mech = Mech_RSApPKCS1; + cmd.args.decrypt.cipher.mech = dec_mech; + cmd.args.decrypt.cipher.data.rsappkcs1.m = dec_bn; + cmd.args.decrypt.reply_type = PlainTextType_Bignum; + result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : FastApp_Transact(Cmd_Decrypt)\n", result ); + return 1; + } + result = reply.status; + if ( result != Status_OK ) + { + printf( "error(%d) : reply.status(Cmd_Decrypt)\n", result ); + return 1; + } +#if 0 + if ( DATA_LEN != reply.reply.decrypt.plain.data.bignum.m->nbytes ) + { + printf( "error : output size isn't %d bytes!\n", DATA_LEN ); + return 1; + } +#endif + + printf( "RSA data decrypt ok\n" ); + + // after + afterLen = reply.reply.encrypt.cipher.data.rsappkcs1.m->nbytes; + afterPtr = (unsigned char*)malloc( afterLen ); + my_bignum2bin( afterPtr, afterLen, handle, + reply.reply.decrypt.plain.data.bignum.m ); + + NFastApp_Free_Command( handle, NULL, NULL, &cmd ); + NFastApp_Free_Reply( handle, NULL, NULL, &reply ); + + // data show + PrintArray( (char*)"before", beforePtr, beforeLen ); + PrintArray( (char*)"middle", middlePtr, middleLen ); + PrintArray( (char*)"after", afterPtr, afterLen ); + } // encrypt & decrypt + + return result; +} // verify_rsa_keypair + +void PrintArray( char *pStr, const unsigned char *pData, int length ) +{ + int i; + printf( "%s(%d bytes)", pStr, length ); + for ( i = 0; i < length; i++ ) + { + if ( (i % 16) == 0 ) printf( "\n" ); + printf( "%02X ", pData[ i ] ); + } + printf( "\n" ); +} // PrintArray + +int main( int argc, char *argv[] ) +{ + int result = Status_OK; + + M_Command cmd; + M_Reply reply; + + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // init nFast + result = NFastApp_InitEx( &handle, NULL, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFastApp_InitEx\n", result ); + return 1; + } + + // connecting to hardserver + result = NFastApp_Connect( handle, &nc, 0, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFastApp_Connect\n", result ); + return 1; + } + + // set bignum upcalls setting + result = NFastApp_SetBignumUpcalls( + handle, + my_bignumreceiveupcall, + my_bignumsendlenupcall, + my_bignumsendupcall, + my_bignumfreeupcall, + my_bignumformatupcall, + NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFastApp_SetBignumUpcalls\n", result ); + return 1; + } + + // NFKM getinfo + result = NFKM_getinfo( handle, &world, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_getinfo\n", result ); + return 1; + } + + // init card-loading lib + result = RQCard_init( &card, handle, nc, world, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : RQCard_init\n", result ); + return 1; + } + + // init FIPS state + result = RQCard_fips_init( &card, &fips ); + if ( result != Status_OK ) + { + printf( "error(%d) : RQCard_fips_init\n", result ); + return 1; + } + + // ui select + result = RQCard_ui_default( &card ); + if ( result != Status_OK ) + { + printf( "error(%d) : RQCard_ui_default\n", result ); + return 1; + } + + // get strict-FIPS authorization +#if 0 + NFKM_FIPS140AuthHandle fipsHandle; + M_SlotID slotId; + result = RQCard_fips_get( &fips, 1, &fipsHandle, &slotId ); + if ( result != Status_OK ) + { + printf( "error(%d) : RQCard_fips_get\n", result ); + return 0; + } + if ( fipsHandle == NULL ) + { + printf( "this sworld isn't strict-FIPS.\n" ); + } +#endif + +#if 0 + // list cardsets + int card_num; + NFKM_CardSetIdent *cardident = NULL; + result = NFKM_listcardsets( handle, &card_num, &cardident, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_listcardsets\n", result ); + return 0; + } + + // find cardsets + result = NFKM_findcardset( handle, cardident, &cardset, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_findcardset\n", result ); + return 0; + } + + // load cardset + result = RQCard_logic_ocs_specific( &card, &(cardset->hkltu), "Load Cardset" ); + if ( result != Status_OK ) + { + printf( "error(%d) : RQCard_logic_ocs_specific\n", result ); + return 0; + } + + // use specific module : #1 + // important!! : if you set resultplace=NULL, abort. (possibility is 100%) + result = RQCard_whichmodule_specific( &card, world->modules[0]->module, <id ); + if ( result != Status_OK ) + { + printf( "error(%d) : RQCard_whichmodule_specific\n", result ); + } + + // wait event loop + result = card.uf->eventloop( &card ); + if ( result != Status_OK ) + { + printf( "error(%d) : card module event loop\n", result ); + } +#endif + + // get usable module + moduleinfo = world->modules[0]; + result = NFKM_getusablemodule( world, MODULE_ID, &moduleinfo ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_getusablemodule\n", result ); + return 1; + } + +#if 0 + // RSA privkey のインポート + result = importRSAPrivate( priv_keyident ); + if ( result != Status_OK ) + { + printf( "error : importRSAPrivate\n" ); + return 1; + } + printf( "RSA privkey import success.\n" ); +#endif + + // RSA pubkey + result = importRSAPublic( pub_keyident ); + if ( result != Status_OK ) + { + printf( "error : importRSAPublic\n" ); + return 1; + } + printf( "RSA pubkey import success.\n" ); + + // RSA privkey のインポート + result = importRSAPrivate( priv_keyident ); + if ( result != Status_OK ) + { + printf( "error : importRSAPrivate\n" ); + return 1; + } + printf( "RSA privkey import success.\n" ); + + // list key +#if 0 + int key_num; + NFKM_KeyIdent *keylist = NULL; + result = NFKM_listkeys( handle, &key_num, &keylist, "simple", NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : NFKM_listkeys\n", result ); + } + NFKM_KeyIdent **tkp = &keylist; + for ( i = 0; i < key_num; i++ ) + { + printf( "appname : %s, ident : %s\n", tkp[i]->appname, tkp[i]->ident ); + } +#endif + + // verify key pair + result = verifyRSAKeyPair( priv_keyident, pub_keyident ); + if ( result != Status_OK ) + { + printf( "error : verifyRSAKeyPair\n" ); + return 1; + } + printf( "RSA keypair verify success.\n" ); + + // end processing + RQCard_fips_free( &card, &fips ); + RQCard_destroy( &card ); + NFKM_freeinfo( handle, &world, NULL ); + NFastApp_Disconnect( nc, NULL ); + NFastApp_Finish( handle, NULL ); + + return 0; + +} // main diff --git a/tags/20100201_Sharp_Release/hsm_utils/my_hsm_alloc.c b/tags/20100201_Sharp_Release/hsm_utils/my_hsm_alloc.c new file mode 100644 index 0000000..abaaad2 --- /dev/null +++ b/tags/20100201_Sharp_Release/hsm_utils/my_hsm_alloc.c @@ -0,0 +1,45 @@ +/* +* my_hsm_alloc.c +*/ + +#include +#include +#include +#include +#include +#include + +#include "nfastapp.h" +#include "nfutil.h" +#include "my_hsm_alloc.h" + +/* --------------------- */ + +const NFast_MallocUpcalls my_hsm_malloc_upcalls = +{ + my_hsm_malloc, my_hsm_realloc, my_hsm_free +}; + +/* --------------------- */ + +void *my_hsm_malloc( size_t nbytes, + struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx ) +{ + return malloc( nbytes ); +} + +/* --------------------- */ + +void *my_hsm_realloc( void *ptr, size_t nbytes, + struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx ) +{ + return realloc( ptr, nbytes ); +} + +/* --------------------- */ + +void my_hsm_free( void *ptr, + struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx ) +{ + free( ptr ); +} diff --git a/tags/20100201_Sharp_Release/hsm_utils/my_hsm_alloc.h b/tags/20100201_Sharp_Release/hsm_utils/my_hsm_alloc.h new file mode 100644 index 0000000..91a39ff --- /dev/null +++ b/tags/20100201_Sharp_Release/hsm_utils/my_hsm_alloc.h @@ -0,0 +1,30 @@ +/* +* my_hsm_alloc.h +*/ + +#ifndef MY_HSM_ALLOC_H +#define MY_HSM_ALLOC_H + +#include "nfastapp.h" + +#ifdef __cplusplus +extern "C" { +#endif + +extern const NFast_MallocUpcalls my_hsm_malloc_upcalls; + +void *my_hsm_malloc( size_t nbytes, + struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx ); + +void *my_hsm_realloc( void *ptr, size_t nbytes, + struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx ); + +void my_hsm_free( void *ptr, + struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx ); + +#ifdef __cplusplus +} +#endif + +#endif // MY_HSM_ALLOC_H + diff --git a/tags/20100201_Sharp_Release/hsm_utils/my_hsm_bignum.c b/tags/20100201_Sharp_Release/hsm_utils/my_hsm_bignum.c new file mode 100644 index 0000000..7883b7e --- /dev/null +++ b/tags/20100201_Sharp_Release/hsm_utils/my_hsm_bignum.c @@ -0,0 +1,357 @@ +/* +* SIMPLEBIGNUM.C +* +* Simple bignumber upcalls +* +* This example source code is provided for your information and +* assistance. See the file LICENCE.TXT for details and the +* terms and conditions of the licence which governs the use of the +* source code. By using such source code you will be accepting these +* terms and conditions. If you do not wish to accept these terms and +* conditions, DO NOT OPEN THE FILE OR USE THE SOURCE CODE. +* +* Note that there is NO WARRANTY. +* +* Copyright 2001 - 2002 nCipher Corporation Limited. +*/ + +#include +#include +#include +#include +#include +#include + +#include "nfastapp.h" +#include "nfutil.h" +#include "my_hsm_bignum.h" + +/* --------------------- */ + +int my_bignumreceiveupcall(struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx, + M_Bignum *bignum, int nbytes, + const void *source, + int msbitfirst, int mswordfirst) +{ + struct NFast_Bignum *pBN; + + if ( nbytes > MAXBIGNUMBITS/8 ) return Status_OutOfRange; + assert( (nbytes & 3)==0 ); + + pBN = (struct NFast_Bignum *)NFastApp_Malloc(app, sizeof(struct NFast_Bignum), cctx, tctx); + if ( !pBN ) return NOMEM; + + nfutil_copybytes(pBN->bytes, (const unsigned char *)source, + nbytes, 0, 0); + + pBN->msb_first = msbitfirst; + pBN->msw_first = mswordfirst; + pBN->nbytes=nbytes; + *bignum=pBN; + return Status_OK; +} + +/* --------------------- */ + +int my_bignumsendlenupcall(struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx, + const M_Bignum *bignum, int *nbytes_r) +{ + assert( ((*bignum)->nbytes & 3)==0 ); + *nbytes_r= (*bignum)->nbytes; + return Status_OK; +} + +/* --------------------- */ + +int my_bignumsendupcall(struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx, + const M_Bignum *bignum, int nbytes, + void *dest, int msbitfirst, int mswordfirst) +{ + int swapends, swapwords; + struct NFast_Bignum *pBN = *bignum; + + assert( pBN->nbytes==nbytes ); + + /* Is format which we're sending in the same as that of the + bignumber? + (NB '!' used to constrain result to 0,1 range) + If not, work out which ends to swap. + */ + + swapends = (!msbitfirst) ^ (!pBN->msb_first); + swapwords = (!mswordfirst) ^ (!pBN->msw_first); + nfutil_copybytes( (unsigned char *)dest, (*bignum)->bytes, nbytes, + swapends, swapwords ); + return Status_OK; +} + +/* --------------------- */ + +void my_bignumfreeupcall(struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx, + M_Bignum *bignum) +{ + NFastApp_Free(app, (*bignum), cctx, tctx); + *bignum=NULL; +} + +/* --------------------- */ + +int my_bignumformatupcall(struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx, + int *msbitfirst_io, int *mswordfirst_io) +{ + /* Send to the module in little-endian format. + (This is not officially necessary. However, some + versions of the monitor (Maintenance mode) don't accept + big-endian bignums due to a bug) */ + *msbitfirst_io=0; + *mswordfirst_io=0; + return Status_OK; +} + +NFast_BignumUpcalls my_upcalls = { + my_bignumreceiveupcall, + my_bignumsendlenupcall, + my_bignumsendupcall, + my_bignumfreeupcall, + my_bignumformatupcall +}; + +/* --------------------- */ + +static int char2hex ( char c ) +{ + if ( c >= '0' && c <= '9' ) return c-'0'; + if ( c >= 'A' && c <= 'F' ) return c-'A'+10; + if ( c >= 'a' && c <= 'f' ) return c-'a'+10; + return -1; +} + +/* --------------------- */ + +int my_char2bignum ( struct NFast_Bignum **ppBN_out, + const char *text, + struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx ) +{ + struct NFast_Bignum *pBN; + int d; + size_t len, i; + + /* Strip leading whitespace */ + + while ( text[0] != 0 && isspace((unsigned char)text[0]) ) + text++; + + /* Strip trailing whitespace */ + len=strlen(text); + while ( len > 0 && isspace((unsigned char)text[len-1]) ) + len--; + + if ( len > MAXBIGNUMBITS/4 ) return Status_OutOfRange; + + pBN = (struct NFast_Bignum *)NFastApp_Malloc(app, sizeof(struct NFast_Bignum), cctx, tctx); + if ( !pBN ) return NOMEM; + + pBN->msb_first = 0; + pBN->msw_first = 0; + + /* Read in from the LS digit */ + for ( i=0; ibytes[i/2] |= (d << 4); + else + pBN->bytes[i/2] = d; + } + + /* Pad to words if necessary */ + i = (len+1)/2; + while ( (i & 3) != 0 ) + pBN->bytes[i++] = 0; + + assert(i <= INT_MAX); + pBN->nbytes=(int)i; + *ppBN_out=pBN; + return Status_OK; +} + +/* --------------------- */ + +// bin データを NFast_Bignum データに変換する +int my_bin2bignum ( struct NFast_Bignum **ppBN_out, + struct NFast_Application *app, + const unsigned char *bin, const int size ) +{ + struct NFast_Bignum *pBN; + int len, i; + + len = size; + + if ( len > MAXBIGNUMBITS/4 ) return Status_OutOfRange; + + pBN = (struct NFast_Bignum *)NFastApp_Malloc( app, sizeof(struct NFast_Bignum), NULL, NULL ); + if ( !pBN ) return NOMEM; + + pBN->msb_first = 0; + pBN->msw_first = 0; + + for ( i = 0; i < len; i++ ) + pBN->bytes[i] = bin[len-1-i]; + + while ( (i & 3) != 0 ) + pBN->bytes[i++] = 0; + + pBN->nbytes = i; + + *ppBN_out = pBN; + + return Status_OK; +} // my_bin2bignum + +/* --------------------- */ + +static int getbyte ( const struct NFast_Bignum *pN, int pos ) +{ + /* Get a byte from a bignum, taking account of possible strange endianness */ + if ( pos >= pN->nbytes ) return 0; + + if ( pN->msb_first ) pos ^= 3; /* Big endian words */ + + if ( pN->msw_first ) + { + pos = pN->nbytes-1-pos; + pos ^= 3; + } + + return pN->bytes[pos]; +} + +/* --------------------- */ + +static int getbytelen ( const struct NFast_Bignum *pN ) +{ + int n=pN->nbytes-1; + while ( n >= 0 && getbyte(pN, n)==0 ) + n--; + + return n+1; +} + +/* --------------------- */ + +int my_bignum2char ( char *buf, int buflen, + const struct NFast_Bignum *pBN, + struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx ) +{ + int i, d, pos, len; + static const char *hexdigits="0123456789ABCDEF"; + + len = pBN->nbytes; + + pos = len*2+1; + if ( buflen < pos ) + return Status_BufferFull; + + buf[--pos] = 0; + + for ( i=0; i>4) & 0xF]; + } + + return Status_OK; +} + +/* --------------------- */ + +int my_bignum2bin ( unsigned char *buf, int buflen, + struct NFast_Application *app, + const struct NFast_Bignum *pBN ) +{ + int i, pos, len; + + len = pBN->nbytes; + pos = len; + if ( buflen < pos ) + return Status_BufferFull; + + for ( i = 0; i < len; i++ ) + { + buf[--pos] = getbyte( pBN, i ); + } + + return Status_OK; +} // my_bignum2bin + +/* --------------------- */ + +int my_bignumCopy( struct NFast_Bignum **dst, + const struct NFast_Bignum *src, + struct NFast_Application *app ) +{ + struct NFast_Bignum *pBN; + pBN = (struct NFast_Bignum *)NFastApp_Malloc( app, sizeof(struct NFast_Bignum), NULL, NULL ); + if ( !pBN ) return NOMEM; + + pBN->msb_first = src->msb_first; + pBN->msw_first = src->msw_first; + pBN->nbytes = src->nbytes; + memcpy( pBN->bytes, src->bytes, src->nbytes ); + + *dst = pBN; + + return Status_OK; +} + +/* --------------------- */ + +void my_printbignum ( FILE *f, const char *prefix, const struct NFast_Bignum *pBN ) +{ + char buf[MAXBIGNUMBITS/4+1]; + int rc; + + rc = my_bignum2char(buf, sizeof(buf), pBN, NULL, NULL, NULL); + if ( rc != Status_OK ) strcpy(buf, ""); + fprintf( f, "%s=\n %s\n", prefix, buf ); +} + +/* --------------------- */ + +int my_compare ( const struct NFast_Bignum *pA, + const struct NFast_Bignum *pB ) +{ + int i, aa, bb; + + aa=getbytelen(pA); + bb=getbytelen(pB); + if ( aa != bb ) return (aa > bb) ? 1 : -1; + + i=aa; + while ( i-- > 0 ) + { + aa=getbyte(pA,i); + bb=getbyte(pB,i); + if ( aa != bb ) return (aa > bb) ? 1 : -1; + } + + return 0; +} + + diff --git a/tags/20100201_Sharp_Release/hsm_utils/my_hsm_bignum.h b/tags/20100201_Sharp_Release/hsm_utils/my_hsm_bignum.h new file mode 100644 index 0000000..c029d8a --- /dev/null +++ b/tags/20100201_Sharp_Release/hsm_utils/my_hsm_bignum.h @@ -0,0 +1,178 @@ +/** \file simplebignum.h Simple bignum support + * + * Illustrates simple easy-to-use bignumber format. This provides a + * definition of the \ref NFast_Bignum structure which can be used + * in applications which do not already have an equivalent structure + * defined. + * + * See also: + * - \ref nfastapp.h + * - \ref gsbignum + */ +/* Copyright 1999-2002 nCipher Corporation Limited. +* +* This example source code is provided for your information and +* assistance. See the file LICENCE.TXT for details and the +* terms and conditions of the licence which governs the use of the +* source code. By using such source code you will be accepting these +* terms and conditions. If you do not wish to accept these terms and +* conditions, DO NOT OPEN THE FILE OR USE THE SOURCE CODE. +* +* Note that there is NO WARRANTY. +* +*/ + +#ifndef MY_ALLOC_H +#define MY_ALLOC_H + +#include "nfastapp.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef MAXBIGNUMBITS +/** Maximum size of a bignum in bits */ +#define MAXBIGNUMBITS 16384 +#endif + +/** Structure of a bignum + * + * \ref M_Bignum will be a pointer to this structure. */ +struct NFast_Bignum { + /** Byte order + * + * If this is set then each 32-bit word in the bignum is big-endian + * (most-significant byte first); otherwise it is little-endian + * (least-significant byte first). */ + int msb_first; + /** Word order + * + * If this is set then 32-bit words in the bignum are in big-endian order + * (most-significant word first); otherwise they are in little-endian + * order (least-significant words first). + */ + int msw_first; + /** Number of bytes */ + int nbytes; + /** Bignum data + * + * Only the first \a nbytes are used. */ + unsigned char bytes[MAXBIGNUMBITS/8]; +}; + +/* Bignum send & receive upcalls -------------------------- */ + +/* As well as being used directly as upcalls, + these can be used to create bignums from data blocks and + extract data from bignums. + */ + +/** Bignum receive upcall + * + * See \ref NFast_BignumReceiveUpcall_t */ +extern int my_bignumreceiveupcall(struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx, + M_Bignum *bignum, int nbytes, + const void *source, + int msbitfirst, int mswordfirst); + + +/** Bignum send-length upcall + * + * See \ref NFast_BignumSendLenUpcall_t */ +extern int my_bignumsendlenupcall(struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx, + const M_Bignum *bignum, int *nbytes_r); + +/** Bignum send upcall + * + * See \ref NFast_BignumSendUpcall_t */ +extern int my_bignumsendupcall(struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx, + const M_Bignum *bignum, int nbytes, + void *dest, int msbitfirst, int mswordfirst); + + +/** Free bignum upcall + * + * See \ref NFast_BignumFreeUpcall_t */ +extern void my_bignumfreeupcall(struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx, + M_Bignum *bignum); + +/** Bignum format upcall + * + * See \ref NFast_BignumFormatUpcall_t */ +extern int my_bignumformatupcall(struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx, + int *msbitfirst_io, int *mswordfirst_io); + +/** Structure containing bignum upcalls + * + * See \ref NFastAppInitArgs and \ref NFAPP_IF_BIGNUM */ +extern NFast_BignumUpcalls my_upcalls; + +/* Bignum utility functions ----------------------------- */ + +/** Convert a hex string to a bignum + * + * \return Status code + */ +extern int my_char2bignum ( struct NFast_Bignum **ppBN_out, + const char *text, + struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx ); + +// convert binary to NFast_Bignum +extern int my_bin2bignum ( struct NFast_Bignum **ppBN_out, + struct NFast_Application *app, + const unsigned char *bin, const int size ); + +/** Convert a bignum to a hex string + * + * \return Status code + */ +extern int my_bignum2char ( char *buf, int buflen, + const struct NFast_Bignum *pBN, + struct NFast_Application *app, + struct NFast_Call_Context *cctx, + struct NFast_Transaction_Context *tctx ); + +// convert NFast_Bignum to binary +int my_bignum2bin ( unsigned char *buf, int buflen, + struct NFast_Application *app, + const struct NFast_Bignum *pBN ); + +// NFast_Bignum copy +int my_bignumCopy( struct NFast_Bignum **dst, + const struct NFast_Bignum *src, + struct NFast_Application *app ); + +/** Print a bignum in hex to a file + * + * Call ferror() to test for output errors. + */ +extern void my_printbignum ( FILE *f, + const char *prefix, const struct NFast_Bignum *pBN ); + + +/** Compare two bignums + * + * \return -1, 0 or 1 if A\B + */ +extern int my_compare ( const struct NFast_Bignum *pA, + const struct NFast_Bignum *pB ); + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/tags/20100201_Sharp_Release/hsm_utils/test_key/test-ecdsa-privkey.der b/tags/20100201_Sharp_Release/hsm_utils/test_key/test-ecdsa-privkey.der new file mode 100644 index 0000000..bf50d4d Binary files /dev/null and b/tags/20100201_Sharp_Release/hsm_utils/test_key/test-ecdsa-privkey.der differ diff --git a/tags/20100201_Sharp_Release/hsm_utils/test_key/test-ecdsa-pubkey.der b/tags/20100201_Sharp_Release/hsm_utils/test_key/test-ecdsa-pubkey.der new file mode 100644 index 0000000..a00aad5 Binary files /dev/null and b/tags/20100201_Sharp_Release/hsm_utils/test_key/test-ecdsa-pubkey.der differ diff --git a/tags/20100201_Sharp_Release/main.c b/tags/20100201_Sharp_Release/main.c new file mode 100644 index 0000000..9a2a33e --- /dev/null +++ b/tags/20100201_Sharp_Release/main.c @@ -0,0 +1,371 @@ + +#define RAND_MAX 0xffffffff +#include +#include +#include +#include +#include + +#ifdef DEV_CYGWIN +#include +#else // Cygwin +#include +#include +#endif // Linux + +#include "cr_generate_id.h" + +#define BONDING_OPTION_PROD 0 // 陬ス蜩∫畑ID +#define BONDING_OPTION_DEV 1 // 髢狗匱逕ィID + +// extern const int isDummyPrivateKey; + +/* + gen_id.exe 0x01 0x02 + gen_id.exe 0x01 0x02 ctrid090716.dat + gen_id.exe 0x01 0x03 ctrid090728.dat +*/ + +#ifndef DEV_CYGWIN + +static struct termios initial_setting, new_setting; +static int peek_character = -1; +void keyboard_initialize( void ) +{ + tcgetattr( 0, &initial_setting ); + new_setting = initial_setting; + new_setting.c_lflag &= ~ICANON; + new_setting.c_lflag &= ~ECHO; + new_setting.c_lflag &= ~ISIG; + new_setting.c_cc[VMIN] = 0; + new_setting.c_cc[VTIME] = 0; + tcsetattr( 0, TCSANOW, &initial_setting ); +} // keyboard_initialize + +void keyboard_finalize( void ) +{ + tcsetattr( 0, TCSANOW, &initial_setting ); +} // keyboard_finalize + +int kbhit( void ) +{ + char ch; + int nread; + + if ( peek_character != -1 ) + return 1; + new_setting.c_cc[VMIN] = 0; + tcsetattr( 0, TCSANOW, &new_setting ); + nread = read( 0, &ch, 1 ); + new_setting.c_cc[VMIN] = 1; + tcsetattr( 0, TCSANOW, &new_setting ); + + if ( nread == 1 ) + { + peek_character = ch; + return 1; + } + + return 0; +} // kbhit + +int getch( void ) +{ + char ch; + + if ( peek_character != -1 ) + { + ch = peek_character; + peek_character = -1; + return ch; + } + read( 0, &ch, 1 ); + return ch; +} // readch + +#endif // DEV_CYGWIN + +// char *str = "0x11111111"; +static int str_to_u32(u32 *num, const char *str) +{ + u32 c; + int shift = 0; + char *s; + int hex_mode = 0; + + *num = 0; + + if( *str == '0' && *(str+1) == 'x' ) { + hex_mode = 1; + s = (char *)(str + 2); + } + else { + s = (char *)str; + } + + while( *s != '\0' ) { + + if( shift > 8 ) { + return -1; /* error */ + } + + if( hex_mode ) { + if( '0' <= *s && *s <= '9' ) { + c = (u32)(*s - '0'); + } + else if( 'a' <= *s && *s <= 'f' ) { + c = (u32)(*s - 'a') + 10; + } + else if( 'A' <= *s && *s <= 'F' ) { + c = (u32)(*s - 'A') + 10; + } + else { + return -1; /* error */ + } + *num <<= 4; + *num |= c; + } + else { + if( '0' <= *s && *s <= '9' ) { + c = (u32)(*s - '0'); + } + else { + return -1; /* error */ + } + *num *= 10; + *num += c; + } + shift++; + s++; + } + + return 0; +} + +static double gettimeofday_sec(void) +{ + struct timeval tv; + +#if 0 + struct timeval { + time_t tv_sec; /* 遘 */ + suseconds_t tv_usec; /* 繝槭う繧ッ繝ュ遘 */ + }; + + struct timezone { + int tz_minuteswest; /* 繧ー繝ェ繝九ャ繧ク讓呎コ匁凾縺ィ縺ョ蟾ョ (隘ソ譁ケ縺ォ蛻蜊倅ス) */ + int tz_dsttime; /* 螟乗凾髢楢ェソ謨エ縺ョ蝙 */ + }; + + int gettimeofday(struct timeval *tv, struct timezone *tz); + +#endif + + + gettimeofday(&tv, NULL); + return tv.tv_sec + (double)tv.tv_usec*1e-6; +} + +int main(int ac, char *argv[]) +{ + u8 bonding_option = BONDING_OPTION_PROD; + u32 device_id[CR_NUM_OF_DEVICEID]; + u8 id[CR_ID_BUF_SIZE]; /* 256byte(2048bit) */ + int ret_code; + int c; + FILE *fp; + double time_start,time_end; + long double time_total = 0; + int time_count = 0; + int myseed; + time_t tloc; + u32 counter0, counter0_bak; + u64 counter1, counter1_bak; + u64 counter2, counter2_bak; + u32 i; + +#ifndef DEV_CYGWIN + keyboard_initialize(); +#endif + +#ifdef USE_DUMMY_KEY + printf( "[TEST MODE] Use dummy key.\n"); +#endif + + time(&tloc); + myseed = tloc; + srand(myseed); + + // ID逕滓仙燕縺ォ繧ォ繧ヲ繝ウ繧ソ蜉邂励r縺吶k縺ェ繧峨∝晄悄蛟、縺ッ 0 縺ァ OK + counter0 = 0x00000000; + counter1 = 0x0000000000000000ll; + counter2 = 0x0000000000000000ll; + + // cr_generate_id 繧剃スソ逕ィ縺吶k蜑阪↓蜻シ縺ウ蜃コ縺 + ret_code = cr_generate_id_initialize( id ); + if ( ret_code != CR_GENID_SUCCESS ) + { + printf( "error : cr_generate_id_initialize\n" ); + return 0; // error + } + + + if( ac == 1 ) { + for( i = 1 ; i < 0xffffffff; i++ ) { + u64 unit; + + counter0_bak = counter0; + counter1_bak = counter1; + counter2_bak = counter2; + + // counter0 縺ッ縲1 縺壹▽蜉邂 + counter0 = i; + if( counter0 == 0 ) { + counter0 = 1; + } + + // counter1 縺ッ縲"1ス4 縺ョ荵ア謨ー蛟、" 繧貞刈邂 + unit = (u64)( ( rand() & 0x03 ) + 1 ); + counter1 += unit; + + // counter2 縺ッ縲"0 莉・螟悶ョ 32bit 荵ア謨ー蛟、" 繧貞刈邂 + do { + unit = ((u64)rand() & 0xffff) | ( ((u64)rand() & 0xffff) << 16 ); + }while( unit == 0 ); + counter2 += unit; + + // 繧ォ繧ヲ繝ウ繧ソ繧ェ繝シ繝舌シ繝輔Ο繝シ繝√ぉ繝繧ッ + if( counter0 < counter0_bak ) { + fprintf(stderr,"counter0 overflow : %08x\n", (unsigned int)counter0 ); + } + if( counter1 < counter1_bak ) { + fprintf(stderr,"counter1 overflow : %08x%08x\n", (unsigned int)( counter1 >> 32 ), (unsigned int)counter2 ); + } + if( counter2 < counter2_bak ) { + fprintf(stderr,"counter2 overflow : %08x%08x\n", (unsigned int)( counter2 >> 32 ), (unsigned int)counter2 ); + } + + device_id[0] = counter0; + device_id[1] = (u32)(counter1 & 0xffffffff); + device_id[2] = (u32)((counter1 >> 32) & 0xffffffff); + device_id[3] = (u32)(counter2 & 0xffffffff); + device_id[4] = (u32)((counter2 >> 32) & 0xffffffff); + + // id[0] 縺 0x100 豈弱↓骰オ繧呈鋤縺医k + if ( (counter0 % 0x100) == 0 ) + { + if ( bonding_option == BONDING_OPTION_PROD ) + bonding_option = BONDING_OPTION_DEV; + else + bonding_option = BONDING_OPTION_PROD; + } + + time_start = gettimeofday_sec(); + ret_code = cr_generate_id( device_id, id, bonding_option ); + if( ret_code != 0 ) { + fprintf(stderr,"generate_id failed\n"); + } + else { + time_end = gettimeofday_sec(); + time_total += (long double)(time_end - time_start); + time_count++; + /* printf("generate_id success\n"); */ + } + + if (kbhit()) + { + c = getch(); + if( 'p' == c ) { + printf("ID[0] = 0x%08x\n", (unsigned int)device_id[0]); + printf("ID[1] = 0x%08x%08x\n", (unsigned int)device_id[2], (unsigned int)device_id[1] ); + printf("ID[2] = 0x%08x%08x\n", (unsigned int)device_id[4], (unsigned int)device_id[3] ); + printf("time av. = %8.8f sec\n", (double)(time_total/(long double)time_count)); + cr_print_flag = 1; + } + else if( c == 'q' ) { + goto end; + } + } + else + { + cr_print_flag = 0; + } + } + } + else if( ac == 3 ) { + if( 0 == str_to_u32(&device_id[0], argv[1]) && 0 == str_to_u32(&device_id[1], argv[2]) ) { + printf("ID[0] = 0x%08x\n", (unsigned int)device_id[0]); + printf("ID[1] = 0x%08x%08x\n", (unsigned int)device_id[2], (unsigned int)device_id[1] ); + printf("ID[2] = 0x%08x%08x\n", (unsigned int)device_id[4], (unsigned int)device_id[3] ); + + time_start = gettimeofday_sec(); + cr_print_flag = 1; + if( 0 != cr_generate_id( device_id, id, bonding_option ) ) + { + fprintf(stderr,"cr_generate_id failed s1=0x%08x s2_lo=0x%08x s2_hi=0x%08x\n", + (int)device_id[0], (int)device_id[1], (int)device_id[2]); + } + else { + time_end = gettimeofday_sec(); + time_total += (long double)(time_end - time_start); + time_count++; + printf("time av. = %8.8f sec\n", (double)(time_total/(long double)time_count)); + } + cr_print_flag = 0; + } + else { + goto err_print; + } + + } + else if( ac == 4 ) { + if( 0 == str_to_u32(&device_id[0], argv[1]) && 0 == str_to_u32(&device_id[1], argv[2]) ) { + printf("ID[0] = 0x%08x\n", (unsigned int)device_id[0]); + printf("ID[1] = 0x%08x%08x\n", (unsigned int)device_id[2], (unsigned int)device_id[1] ); + printf("ID[2] = 0x%08x%08x\n", (unsigned int)device_id[4], (unsigned int)device_id[3] ); + fp = fopen( argv[3], "wb" ); + if( fp == NULL ) { + fprintf(stderr, "failed to fopen %s\n",argv[3]); + } + else { + time_start = gettimeofday_sec(); + if( 0 != cr_generate_id( device_id, id, bonding_option ) ) + { + fprintf(stderr,"cr_generate_id failed s1=0x%08x s2_lo=0x%08x s2_hi=0x%08x\n", + (int)device_id[0], (int)device_id[1], (int)device_id[2]); + } + else { + time_end = gettimeofday_sec(); + fwrite(id, CR_ID_BUF_SIZE, 1, fp); + } + fclose(fp); + } + } + else { + goto err_print; + } + } + else { + err_print: + fprintf(stderr,"Invalid argument!\n"); + fprintf(stderr,"Usage: %s\n", argv[0]); + fprintf(stderr,"Usage: %s device_id(32bit) filename.dat\n", argv[0]); + + } + +end: + // cr_generate_id 繧剃スソ逕ィ縺励◆蠕後↓蜻シ縺ウ蜃コ縺 + ret_code = cr_generate_id_finalize( id ); + if ( ret_code != CR_GENID_SUCCESS ) + { + printf( "error : cr_generate_id_finalize\n" ); + return 0; // error + } + +#ifndef DEV_CYGWIN + keyboard_finalize(); +#endif + + printf("end of main\n"); + return 0; +} diff --git a/tags/20100201_Sharp_Release/package/Makefile b/tags/20100201_Sharp_Release/package/Makefile new file mode 100644 index 0000000..6ad8e04 --- /dev/null +++ b/tags/20100201_Sharp_Release/package/Makefile @@ -0,0 +1,25 @@ + +OPENSSL = openssl-1.0.0-beta5 +# OPENSSL = openssl-0.9.8k + +ifeq ($(DEV_CYGWIN),TRUE) +OPENSSL_CONFIG_TARGET = mingw +else +OPENSSL_CONFIG_TARGET = +endif + +OUT_DIR = ../ + +.SUFFIXES: + +.PHONY: all clobber + +all: $(OUT_DIR)/$(OPENSSL)/libssl.a + +$(OUT_DIR)/$(OPENSSL)/libssl.a : $(OPENSSL).tar.gz + tar xzvf $< -C $(OUT_DIR) + cd $(OUT_DIR)/$(OPENSSL);./Configure $(OPENSSL_CONFIG_TARGET);make build_libs; + +clobber: + $(RM) -r $(OUT_DIR)/$(OPENSSL) + diff --git a/tags/20100201_Sharp_Release/package/openssl-0.9.8k.tar.gz b/tags/20100201_Sharp_Release/package/openssl-0.9.8k.tar.gz new file mode 100644 index 0000000..69d8d8f Binary files /dev/null and b/tags/20100201_Sharp_Release/package/openssl-0.9.8k.tar.gz differ diff --git a/tags/20100201_Sharp_Release/package/openssl-1.0.0-beta5.tar.gz b/tags/20100201_Sharp_Release/package/openssl-1.0.0-beta5.tar.gz new file mode 100644 index 0000000..0863080 Binary files /dev/null and b/tags/20100201_Sharp_Release/package/openssl-1.0.0-beta5.tar.gz differ diff --git a/tags/20100201_Sharp_Release/readme.txt b/tags/20100201_Sharp_Release/readme.txt new file mode 100644 index 0000000..fd006a8 --- /dev/null +++ b/tags/20100201_Sharp_Release/readme.txt @@ -0,0 +1,71 @@ +CTR - ID生成関数について 2009/09/30 + +---------------------------- +要、opensslライブラリ(バージョン0.9.8以上) +現在、openssl-1.0.0-beta2とopenssl-0.9.8kでテスト中。 + +----------------------------- +ファイル構成: + readme.txt + readme_openssl.txt + LICENSE_en.txt + LICENSE_jp.txt + cr_generate_id.h + cr_generate_id.c + cr_alloc.h + cr_alloc.c + cr_gen_id_rsa_key_priv.c + cr_gen_id_rsa_key_priv.h + cr_gen_id_rsa_key_pub.c + cr_gen_id_rsa_key_pub.h + maim.c(使用サンプル) + Makefile(Windows cygwin環境用) + +---------------------------- +関数仕様: + +#define CR_ID_BUF_SIZE (2048/8) +#define CR_NUM_OF_SERIAL 5 + +typedef signed char s8; +typedef unsigned char u8; +typedef unsigned short u16; +typedef unsigned long u32; +typedef unsigned long long u64; + +int cr_generate_id(u32 counter[CR_NUM_OF_SERIAL], u8 id[ID_BUF_SIZE]); +/* + Core2 Duo 2.66GHz 2GB で約0.016sec +*/ +---------------------------- +使用サンプル: + +main() +{ + u8 id_buf[CR_ID_BUF_SIZE]; /* 256byte(2048bit) */ + u32 counter_array[CR_NUM_OF_SERIAL]; + + u32 counter0 = 1; + u64 counter1 = 2; + u64 counter2 = 3; + + + while( 1 ) { + counter_array[0] = counter0; + counter_array[1] = (u32)(counter1 & 0xffffffff ); + counter_array[2] = (u32)( (counter1 >> 32) & 0xffffffff ); + counter_array[3] = (u32)(counter2 & 0xffffffff ); + counter_array[4] = (u32)( (counter2 >> 32) & 0xffffffff ); + + if( 0 != cr_generate_id(counter_array, id_buf) ) { + fprintf(stderr,"cr_generate_id failed c=0x%08x\n",counter0); + } + else { + fwrite(id, CR_ID_BUF_SIZE, 1, fp); + } + counter0++; + counter1 += (u64)rand(); + counter2 += (u64)rand(); + } +} + diff --git a/tags/20100201_Sharp_Release/readme_openssl.txt b/tags/20100201_Sharp_Release/readme_openssl.txt new file mode 100644 index 0000000..866bb14 --- /dev/null +++ b/tags/20100201_Sharp_Release/readme_openssl.txt @@ -0,0 +1,15 @@ +This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit. +(http://www.openssl.org/) + +This product includes cryptographic software written by Eric Young (eay@cryptsoft.com) + +------------------------------------------------------------------------------------------- +この製品には、OpenSSL Toolkit で使用するために OpenSSL Project によって開発されたソフトウェアが組み込まれています。 +(http://www.openssl.org/) + + +このパッケージは、Eric Young (eay@cryptsoft.com) により作成された SSL インプリメンテーションです。このインプリメンテーションは、Netscape SSL に準拠するように作成されています。 + +このライブラリーは、以下の条件に従う限り、無料での商業および非商業の使用が許可されます。以下の条件は、単に SSL コードだけでなく、この配布に含まれるすべてのコードに適用されます。この場合、そのコードが RC4、RSA、lhash、DES、などにいずれであっても構いません。この配布に含まれる SSL 資料は、著作権所有者が Tim Hudson (tjh@cryptsoft.com) である点を除き、同一著作権によってカバーされます。 + +著作権は Eric Young が所有していますので、コードの著作権表示を除去してはなりません。このパッケージをいずれかの製品に使用する場合は、使用するライブラリー部分の作成者として Eric Young を特定する必要があります。これは、プログラム始動時に、またはこのパッケージと一緒に提供される資料 (オンラインまたはテキスト) にテキスト形式のメッセージとして含めることができます。 diff --git a/tags/20100201_Sharp_Release/realKey/dev/NCT2_pub.der b/tags/20100201_Sharp_Release/realKey/dev/NCT2_pub.der new file mode 100644 index 0000000..8916fa0 Binary files /dev/null and b/tags/20100201_Sharp_Release/realKey/dev/NCT2_pub.der differ diff --git a/tags/20100201_Sharp_Release/realKey/dev/eFuse_iv.bin b/tags/20100201_Sharp_Release/realKey/dev/eFuse_iv.bin new file mode 100644 index 0000000..8b352bb Binary files /dev/null and b/tags/20100201_Sharp_Release/realKey/dev/eFuse_iv.bin differ diff --git a/tags/20100201_Sharp_Release/realKey/prod/NCT2_pub.der b/tags/20100201_Sharp_Release/realKey/prod/NCT2_pub.der new file mode 100644 index 0000000..ecfbec3 Binary files /dev/null and b/tags/20100201_Sharp_Release/realKey/prod/NCT2_pub.der differ diff --git a/tags/20100201_Sharp_Release/realKey/prod/eFuse_iv.bin b/tags/20100201_Sharp_Release/realKey/prod/eFuse_iv.bin new file mode 100644 index 0000000..856f415 --- /dev/null +++ b/tags/20100201_Sharp_Release/realKey/prod/eFuse_iv.bin @@ -0,0 +1,2 @@ +コOY +,?heトI \ No newline at end of file diff --git a/tags/20100201_Sharp_Release/tools/bin2c.plx b/tags/20100201_Sharp_Release/tools/bin2c.plx new file mode 100644 index 0000000..3f49af9 --- /dev/null +++ b/tags/20100201_Sharp_Release/tools/bin2c.plx @@ -0,0 +1,94 @@ +#!/usr/bin/perl -w +use strict; + +use File::Basename; + + +# バイナリファイルをCソースに変換 + +my $KEY_VER = 1; +my $srcfname = $ARGV[0]; +my $dstfname_c; +my $dstfname_h; +my $arrayname; +my $size; + +if( !$ARGV[0] || !$ARGV[1] ) { + die "parameter error.\n"; +} + +$_ = "cr_" . basename($srcfname, ""); +s/(\..*)/_$ARGV[1]\.c/; +$dstfname_c = $_; +#s/(\..*)/\.h/; +#$dstfname_h = $_; +s/(\..*)//; +$arrayname = $_; + +$size = -s $srcfname; + +open SRC, "< $srcfname" + or die "Cannot open file $srcfname : $!"; + +open DST, "> $dstfname_c" + or die "Cannot open file temp : $!"; + +#open DST2, "> $dstfname_h" +# or die "Cannot open file temp : $!"; + +binmode( SRC ); + +# $sizeが16byte超(AES鍵でない)なら、配列サイズを + magic_code(8) + keyLen(2) + padding(6) し、16bytesでROUNDUP +my $array_size = ( $size + 16 + 15) & 0xfffffff0; + +# .c ファイルに変換して出力 + +printf DST "#include \n\n"; +printf DST "\/\/下記配列は、KEYデータの前に magic_code[8] + keyLen[2] + keyVer[1] + padding[5] のデータが挿入されています。\n\n"; +printf DST "const unsigned char %s[ 0x%x ] = {\n\t", $arrayname, $array_size; + +# magic code +my $magic_priv = "REDCODER"; +my $magic_pub = "REDCODEU"; +my @magic_list; +if( $srcfname =~ m/priv/ ) { + @magic_list = unpack( "H2H2H2H2H2H2H2H2", $magic_priv ); +}else { + @magic_list = unpack( "H2H2H2H2H2H2H2H2", $magic_pub ); +} +foreach my $elem ( @magic_list ) { + printf DST "0x%s, ", $elem; +} + +# サイズ +printf DST "0x%02x, ", $size % 256; +printf DST "0x%02x, ", $size / 256; + +# KEYバージョン +printf DST "0x%02x, ", $KEY_VER; + +# パディング +my $i; +for ( $i = 0; $i < 5; $i++) { + printf DST "0x%02x, ", rand(255); +} + +# KEY実体 +my $buff; +my $count = 0; +while( sysread( SRC, $buff, 1 ) ) { + my $src = unpack( "C", $buff ); + print DST "\n\t" if( ( $count & 0x0f ) == 0 ); + printf DST "0x%02x, ", $src; + $count++; +} + +print DST "\n};\n"; + +close SRC; +close DST; + +# .h ファイルも出力 +#printf DST2 "extern const unsigned char %s[ 0x%x ];\n", $arrayname, $array_size; +#close DST2; + diff --git a/tags/20100201_Sharp_Release/tools/merge_lib_objs.plx b/tags/20100201_Sharp_Release/tools/merge_lib_objs.plx new file mode 100644 index 0000000..d367459 --- /dev/null +++ b/tags/20100201_Sharp_Release/tools/merge_lib_objs.plx @@ -0,0 +1,36 @@ +#!/usr/bin/perl -w +use strict; + +my $lib_name = "../libgenid.a"; + +my @lib_list = +( + "../openssl-1.0.0-beta5/libcrypto.a", + "../openssl-1.0.0-beta5/libssl.a", +); + +# move work directory +print "cd dep_objs/\n"; +chdir 'dep_objs'; + +# merge lib +foreach ( @lib_list ) +{ + print "ar x $_\n"; + system "ar", "x", $_; + if ( /libnf(.*)\.a/ ) + { + print "mv sys-unix.o sys-unix-$1.o\n"; + system "mv", "sys-unix.o", "sys-unix-$1.o"; + } + &merge_obj; +} + +sub merge_obj +{ + my @object_files = glob "*.o"; + print "ar rcs $lib_name @object_files\n"; + system "ar", "rcs", $lib_name, @object_files; + print "rm *.o\n"; + system "rm", @object_files; +} diff --git a/tags/20100201_Sharp_Release/tools/merge_lib_objs_hsm.plx b/tags/20100201_Sharp_Release/tools/merge_lib_objs_hsm.plx new file mode 100644 index 0000000..30a9763 --- /dev/null +++ b/tags/20100201_Sharp_Release/tools/merge_lib_objs_hsm.plx @@ -0,0 +1,40 @@ +#!/usr/bin/perl -w +use strict; + +my $lib_name = "../libgenid.a"; + +my @lib_list = +( + "../openssl-1.0.0-beta5/libcrypto.a", + "../openssl-1.0.0-beta5/libssl.a", + "/opt/nfast/c/ctd/gcc/lib/libnflog.a", + "/opt/nfast/c/ctd/gcc/lib/libcutils.a", + "/opt/nfast/c/ctd/gcc/lib/libnfstub.a", + "/opt/nfast/c/ctd/gcc/lib/libnfkm.a" +); + +# move work directory +print "cd dep_objs/\n"; +chdir 'dep_objs'; + +# merge lib +foreach ( @lib_list ) +{ + print "ar x $_\n"; + system "ar", "x", $_; + if ( /libnf(.*)\.a/ ) + { + print "mv sys-unix.o sys-unix-$1.o\n"; + system "mv", "sys-unix.o", "sys-unix-$1.o"; + } + &merge_obj; +} + +sub merge_obj +{ + my @object_files = glob "*.o"; + print "ar rcs $lib_name @object_files\n"; + system "ar", "rcs", $lib_name, @object_files; + print "rm *.o\n"; + system "rm", @object_files; +}