From 42b718d775c6ea17fe10110d26370d799b773c9a Mon Sep 17 00:00:00 2001 From: "(no author)" <(no author)@ff987cc8-cf2f-4642-8568-d52cce064691> Date: Mon, 21 Dec 2009 08:45:37 +0000 Subject: [PATCH] Add first files. git-svn-id: file:///Volumes/Transfer/gigaleak_20231201/2020-09-30%20-%20paladin.7z/paladin/ctr_eFuse@1 ff987cc8-cf2f-4642-8568-d52cce064691 --- LICENSE_en.txt | 127 ++ LICENSE_jp.txt | 37 + Makefile | 143 ++ Makefile.sharp | 50 + cr_alloc.c | 477 ++++++ cr_alloc.h | 30 + cr_generate_id.c | 1970 ++++++++++++++++++++++++ cr_generate_id.h | 188 +++ dummyCA/NintendoCA-G2_dummy.crt | 83 + dummyCA/NintendoCA-G2_dummy.csr | 18 + dummyCA/NintendoCA-G2_priv_dummy.der | Bin 0 -> 1191 bytes dummyCA/NintendoCA-G2_priv_dummy.pem | 27 + dummyCA/NintendoCA-G2_pub_dummy.der | Bin 0 -> 294 bytes dummyCA/NintendoCA-G2_pub_dummy.pem | 9 + dummyCA/NintendoCTR2_dummy.crt | 66 + dummyCA/NintendoCTR2_dummy.csr | 9 + dummyCA/NintendoCTR2_priv_dummy.der | Bin 0 -> 111 bytes dummyCA/NintendoCTR2_priv_dummy.pem | 8 + dummyCA/NintendoCTR2_pub_dummy.der | Bin 0 -> 84 bytes dummyCA/NintendoCTR2_pub_dummy.pem | 4 + dummyCA/Test_CTR-Device_dummy.crt | 50 + dummyCA/Test_CTR-Device_dummy.csr | 9 + dummyCA/Test_CTR-Device_priv_dummy.der | Bin 0 -> 111 bytes dummyCA/Test_CTR-Device_priv_dummy.pem | 8 + dummyCA/Test_CTR-Device_pub_dummy.der | Bin 0 -> 84 bytes dummyCA/Test_CTR-Device_pub_dummy.pem | 4 + main.c | 455 ++++++ package.csh | 29 + package.sh | 34 + readme.txt | 71 + readme_openssl.txt | 15 + tools/bin2c.plx | 94 ++ 32 files changed, 4015 insertions(+) create mode 100644 LICENSE_en.txt create mode 100644 LICENSE_jp.txt create mode 100644 Makefile create mode 100644 Makefile.sharp create mode 100644 cr_alloc.c create mode 100644 cr_alloc.h create mode 100644 cr_generate_id.c create mode 100644 cr_generate_id.h create mode 100644 dummyCA/NintendoCA-G2_dummy.crt create mode 100644 dummyCA/NintendoCA-G2_dummy.csr create mode 100644 dummyCA/NintendoCA-G2_priv_dummy.der create mode 100644 dummyCA/NintendoCA-G2_priv_dummy.pem create mode 100644 dummyCA/NintendoCA-G2_pub_dummy.der create mode 100644 dummyCA/NintendoCA-G2_pub_dummy.pem create mode 100644 dummyCA/NintendoCTR2_dummy.crt create mode 100644 dummyCA/NintendoCTR2_dummy.csr create mode 100644 dummyCA/NintendoCTR2_priv_dummy.der create mode 100644 dummyCA/NintendoCTR2_priv_dummy.pem create mode 100644 dummyCA/NintendoCTR2_pub_dummy.der create mode 100644 dummyCA/NintendoCTR2_pub_dummy.pem create mode 100644 dummyCA/Test_CTR-Device_dummy.crt create mode 100644 dummyCA/Test_CTR-Device_dummy.csr create mode 100644 dummyCA/Test_CTR-Device_priv_dummy.der create mode 100644 dummyCA/Test_CTR-Device_priv_dummy.pem create mode 100644 dummyCA/Test_CTR-Device_pub_dummy.der create mode 100644 dummyCA/Test_CTR-Device_pub_dummy.pem create mode 100644 main.c create mode 100644 package.csh create mode 100644 package.sh create mode 100644 readme.txt create mode 100644 readme_openssl.txt create mode 100644 tools/bin2c.plx diff --git a/LICENSE_en.txt b/LICENSE_en.txt new file mode 100644 index 0000000..a2c4adc --- /dev/null +++ b/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/LICENSE_jp.txt b/LICENSE_jp.txt new file mode 100644 index 0000000..48882ab --- /dev/null +++ b/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/Makefile b/Makefile new file mode 100644 index 0000000..6175a10 --- /dev/null +++ b/Makefile @@ -0,0 +1,143 @@ +# 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] " + +# 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)/librqcard.a \ + $(NFAST_LIBPATH)/libnfkm.a \ + $(NFAST_LIBPATH)/libnfstub.a \ + $(NFAST_LIBPATH)/libnflog.a \ + $(NFAST_LIBPATH)/libcutils.a -lm \ + +# nFast OBJS +NFAST_OBJS_PATH = $(NFAST_EXAMPLES)/nfuser/build-gcc-lib +NFAST_OBJS_LIST = \ + $(NFAST_OBJS_PATH)/simplebignum.o \ + $(NFAST_OBJS_PATH)/nfutil.o \ + +# $(NFAST_OBJS_PATH)/simplebignum.o \ + + +# 繝繝溘シ縺ョRSA骰オ繝壹い繧剃スソ逕ィ縺吶k蝣エ蜷医ッ縲ゞSE_DUMMY_KEY繧探RUE縺ォ縺励※縺上□縺輔>縲 +# 豁」蠑上↑縲RSA骰オ繝壹い繧剃スソ逕ィ縺吶k蝣エ蜷医ッ縲ゞSE_DUMMY_KEY繧偵さ繝。繝ウ繝医い繧ヲ繝医@縺ヲ縲.ER_KEY_DIR縺ォRSA骰オ繝壹い縺悟・縺」縺溘ヵ繧ゥ繝ォ繝繧呈欠螳壹@縺ヲ縺上□縺輔>縲 + +#USE_DUMMY_KEY = TRUE +#ENCRYPT_AES = TRUE + +ifeq ($(USE_DUMMY_KEY),TRUE) +DER_KEY_DIR = ./rsakey_dummy +else +#DER_KEY_DIR = ./rsakey +DER_KEY_DIR = ./rsakey_dummy +endif + +PACKAGE_DIR = ./package +# OPENSSL_DIR = ./openssl-1.0.0-beta2 +OPENSSL_DIR = ./openssl-0.9.8k + +# SFMT_DIR = ./SFMT-src-1.3.3 + +TARGET = gen_id + +KEYS_C = cr_gen_id_rsa_key_priv.c cr_gen_id_rsa_key_pub.c +KEYS_H = $(KEYS_C:.c=.h) +SRCS = main.c cr_generate_id.c cr_alloc.c $(KEYS_C) + +OBJS = $(notdir $(SRCS:.c=.o)) + + +#DEV_CYGWIN = TRUE +ifeq ($(DEV_CYGWIN),TRUE) +CC := C:/Cygwin/bin/gcc +CFLAGS = -mno-cygwin -Wall -DMEXP=216091 -msse2 -DHAVE_SSE2 +CPPFLAGS= -I. -I$(OPENSSL_DIR)/include -I$(OPENSSL_DIR)/crypto/ec -I$(SFMT_DIR) +else +CC := /usr/bin/gcc +CFLAGS = -Wall -DMEXP=216091 -msse2 -DHAVE_SSE2 +CPPFLAGS = -I. -I$(OPENSSL_DIR)/include -I$(OPENSSL_DIR)/crypto/ec $(NFAST_CPPFLAGS) +endif + +ifeq ($(USE_DUMMY_KEY),TRUE) +CFLAGS += -DUSE_DUMMY_KEY +endif + +ifeq ($(ENCRYPT_AES),TRUE) +CFLAGS += -DENCRYPT_AES +endif + +ifeq ($(DEV_CYGWIN),TRUE) +LD = C:/Cygwin/bin/gcc +LDFLAGS = -Wl,--subsystem,console -mwindows -mno-cygwin -L$(OPENSSL_DIR) +LDLIBS = -lcrypto -lssl +else +LD = /usr/bin/gcc +LDFLAGS = -Wl -mwindows -L$(OPENSSL_DIR) +LDLIBS = -lcrypto -lssl -ldl -lnsl $(NFAST_LDLIBS) +endif + +.SUFFIXES: + +all: package_build $(KEYS_C) $(TARGET) + +# install: $(TARGET) +# install -c -m 777 $(TARGET) ../bin + +package_build : + cd $(PACKAGE_DIR);make + +$(TARGET): $(OBJS) + $(LD) $(LDFLAGS) $(OBJS) -o $@ $(LDLIBS) $(NFAST_OBJS_LIST) + +$(OBJS): $(HEADS) Makefile + +# %.o:$(SFMT_DIR)/%.c +# $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@ + +%.o:%.c + $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@ + +#%.c:$(DER_KEY_DIR)/%.der +# perl tools/bin2c.plx $< + +cr_gen_id_rsa_key_priv.c : $(DER_KEY_DIR)/gen_id_rsa_key_priv.der + perl tools/bin2c.plx $< + +cr_gen_id_rsa_key_pub.c : $(DER_KEY_DIR)/gen_id_rsa_key_pub.der + perl tools/bin2c.plx $< + + +.PHONY: clean clobber +clean: + $(RM) $(OBJS) $(TARGET).exe $(KEYS_C) $(KEYS_H) + +clobber: + $(RM) $(OBJS) $(TARGET).exe $(KEYS_C) $(KEYS_H) + cd $(PACKAGE_DIR);make clobber + diff --git a/Makefile.sharp b/Makefile.sharp new file mode 100644 index 0000000..1780152 --- /dev/null +++ b/Makefile.sharp @@ -0,0 +1,50 @@ + +# OPENSSL_DIR = ../openssl-1.0.0-beta2 +OPENSSL_DIR = ../openssl-0.9.8k +SFMT_DIR = ../SFMT-src-1.3.3 + +USE_SFMT = TRUE + + + +TARGET = gen_id + +SRCS = main.c cr_generate_id.c cr_alloc.c cr_gen_id_rsa_key_priv.c cr_gen_id_rsa_key_pub.c $(SFMT_DIR)/SFMT.c + +OBJS = $(notdir $(SRCS:.c=.o)) + +CC := C:/Cygwin/bin/gcc + +CFLAGS = -mno-cygwin -Wall + +ifeq ($(USE_SFMT),TRUE) +CFLAGS += -DUSE_SFMT -DMEXP=216091 -msse2 -DHAVE_SSE2 +endif + +CPPFLAGS= -I. -I$(OPENSSL_DIR)/include -I$(OPENSSL_DIR)/crypto/ec -I$(SFMT_DIR) + +LD = C:/Cygwin/bin/gcc +LDFLAGS = -Wl,--subsystem,console -mwindows -mno-cygwin -L$(OPENSSL_DIR) +LDLIBS = -lcrypto -lssl + + +.SUFFIXES: + +all: $(TARGET) + +$(TARGET): $(OBJS) + $(LD) $(LDFLAGS) $(OBJS) -o $@ $(LDLIBS) + +$(OBJS): $(HEADS) Makefile + +%.o:$(SFMT_DIR)/%.c + $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@ + +%.o:%.c + $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@ + +.PHONY: clean clobber +clean clobber: + $(RM) $(OBJS) $(TARGET).exe + + diff --git a/cr_alloc.c b/cr_alloc.c new file mode 100644 index 0000000..b59fea4 --- /dev/null +++ b/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/cr_alloc.h b/cr_alloc.h new file mode 100644 index 0000000..d6c6f2c --- /dev/null +++ b/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/cr_generate_id.c b/cr_generate_id.c new file mode 100644 index 0000000..a9751ba --- /dev/null +++ b/cr_generate_id.c @@ -0,0 +1,1970 @@ +/* ==================================================================== + * 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 + +// nShield +#include "nfastapp.h" +#include "nfkm.h" +#include "rqcard-applic.h" +#include "rqcard-fips.h" + +// nShield optional +#include "simplebignum.h" + +// openssl +#include +#include +#include +#include +#include +#include +#include + +// openssl optional +#include "ec_lcl.h" // ec_key_st讒矩菴薙ョ蜿らァ縺ォ蠢隕 +#include "openssl-0.9.8k/crypto/pem/pem.h" // for PEM_read_X509 髢「謨ー + +#include "cr_generate_id.h" +#include "cr_alloc.h" +#include "cr_gen_id_rsa_key_priv.h" +#include "cr_gen_id_rsa_key_pub.h" + +// #define DEBUG_PRINT 1 + +#define CR_GEN_ID_VERSION 1 +#define CR_NUM_OF_SERIAL 5 +#define CR_RSV_LENGTH 0x0C +#define CR_RANDOM_LENGTH 0x50 +#define EC_PRIVATE_KEY_LENGTH 0x20 +#define ECDSA_SIGN_LENGTH 0x44 +//#define SHA256_DIGEST_LENGTH 0x20 // OpenSSL蛛エ縺ァ螳夂セゥ貂医∩ +#define EC_CURVE_NAME NID_sect233r1 + +#define CA_FILE "dummyCA/NintendoCTR2_dummy.crt" +#define CA_KEY "dummyCA/NintendoCTR2_priv_dummy.pem" +#define DAYS_TILL_EXPIRE (365*10) +#define EXPIRE_SECS (60*60*24*DAYS_TILL_EXPIRE) + +#define AES_PASS_PHRASE "foo1foo2foo3foo4" // TORIAEZU + +#define HSM_MODULE_ID 1 + +const char *issuerNameDev = "NintendoCA - G2_NintendoCTR2dev"; +const char *issuerNameProd = "NintendoCA - G2_NintendoCTR2prod"; + +// TORIAEZU : nFast variables +NFast_AppHandle hsmHandle; +NFastApp_Connection hsmConnection; +NFKM_WorldInfo *hsmWorld = NULL; // allocate +RQCard hsmCard; +RQCard_FIPS hsmFips; +M_KeyID hsmLtid; +// AES +M_KeyID hsmAeskeyid; +const NFKM_KeyIdent hsmAeskeyident = { (char*)"simple", (char*)"aes-test-key" }; +NFKM_Key *hsmAeskeyinfo = NULL; // allocate +// RSA Private +M_KeyID hsmRsaPrivkeyid, hsmRsaPubkeyid; +const NFKM_KeyIdent hsmRsakeyident = { (char*)"simple", (char*)"rsa-priv-key-2048" }; +NFKM_Key *hsmRsakeyinfo = NULL; // allocate +NFKM_ModuleInfo *hsmModuleinfo = NULL; +M_ByteBlock *hsmBlobptr = NULL; + +// functions +static int hsm_generate_random( unsigned char *buf, int bytes ); +static int hsm_get_rtc( time_t *time ); + +static struct _caInfo +{ + X509 *cert; // 險シ譏取嶌 + EVP_PKEY *privKey; // 遘伜ッ骰オ +} +caInfo; + +typedef struct _certEntry +{ + char *key; + char *value; +} +certEntry; + +#define ENTRY_COUNT 6 +certEntry certEntries[ENTRY_COUNT] = +{ + { "countryName", "JP" }, + { "stateOrProvinceName", "KYOTO" }, + { "localityName", "KYOTO" }, + { "organizationName", "NINTENDO" }, + { "organizationalUnitName", "CTR" }, + { "commonName", "Device" } +}; + +#if 0 +typedef struct CTR_Device_Cert { + u32 deviceID; + u8 bonding_option; +// u8 signatureAlgorithmIdentifier[x]; // openssl/crypto/objects/obj_dat.h霎コ繧翫〒螳夂セゥシ +// u8 publicKeyAlgorithmIdentifier[x]; + u8 timestamp[ 8 ]; + u8 ca_name[ 16 ]; + u8 public_key[ 61 ]; + u8 signature[ 64 ]; +} CTR_Device_Cert; +#else +// TWL device cert base +typedef struct CTR_Device_Cert +{ + u8 sigType[4]; // 0x000 - 0x003 : 0x00010002, signature type is ECDSA + u8 eccSignature[60]; // 0x004 - 0x03F : ECDSA using SHA-1 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-yyyyyyyyyyyyyyyy" + 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 +} CTR_Device_Cert; +#endif + + +typedef struct { + u32 magic_number; /* 0x00 - 0x03 = 0xdeadb00f 遒コ螳夲シ*/ + u32 serial[CR_NUM_OF_SERIAL]; /* 0x04 - 0x07 32bit device ID + (32bit縲1蝗コ螳壹き繧ヲ繝ウ繝医い繝繝励ゑシ + (譛ャIDシ脚andom縺ョ蜈磯ュ0x1C bytes繧堤オ縺ソ蜷医o縺帙※縲√ョ繝舌う繧ケ遘伜ッ骰オ縺ィ縺吶k縲) + 0x08 - 0x0F 64bit CTR逡ェ蜿キ seed + (34bit縺ョ縺ソ菴ソ逕ィ縲1ス4縺ョ荵ア謨ー繧ォ繧ヲ繝ウ繝医い繝繝) + 0x10 - 0x17 64bit 莠亥yID + (64bit繝輔Ν縺ォ菴ソ逕ィ縲1ス0x100000000縺ョ荵ア謨ー繧ォ繧ヲ繝ウ繝医い繝繝) + */ + u8 version; /* 0x18 = CR_GEN_ID_VERSION = 1 */ + u8 bondingOption; /* 0x19 繝懊Φ繝繧」繝ウ繧ー繧ェ繝励す繝ァ繝ウ */ + u8 year; /* 0x1A 繝繝舌う繧ケ險シ譏取嶌逋コ陦梧凾髢 シHSM縺九i蜿門セ暦シ */ + u8 month; /* 0x1B */ + u8 mday; /* 0x1C */ + u8 hour; /* 0x1D */ + u8 min; /* 0x1E */ + u8 sec; /* 0x1F */ + u8 devicePrivKey[ EC_PRIVATE_KEY_LENGTH ]; + /* 0x20 - 0x3F ECC233 private key (big endian) 繝ヲ繝九シ繧ッ諤ァ菫晁ィシ縺ェ縺 */ + u8 deviceCertSign[ ECDSA_SIGN_LENGTH ]; + /* 0x40 - 0x83 ECC233 ECDSA signature (big endian) */ + u8 reserved[ CR_RSV_LENGTH ]; /* 0x84 - 0x8F 莠育エ */ + u8 random[ CR_RANDOM_LENGTH ]; /* 0x90 - 0xDF 荵ア謨ー */ + u8 hash[ SHA256_DIGEST_LENGTH ]; /* 0xE0 - 0xFF "0x00-0xDF"鬆伜沺縺ョSHA256繝上ャ繧キ繝・ */ +} CR_ID_BUFFER; /* 蜷郁ィ256bytes = 2048bit */ + +typedef struct { + u32 magic_number; /* 0x00 - 0x03 0x01234567 遒コ螳夲シ*/ + u32 serial0; /* 0x04 - 0x07 */ + u32 openssl_err_code; /* 0x08 - 0x0b */ + s32 top; /* 0x0c - 0x0f */ + s32 bottom; /* 0x10 - 0x13 */ + + /* #define ERR_NUM_ERRORS 16 */ + u32 err_buffer[ERR_NUM_ERRORS]; /* 0x14 - 0x17 .... 0x50 - 0x53 */ + //#define ERR_GET_LIB(l) (int)((((unsigned long)l)>>24L)&0xffL) + //#define ERR_GET_FUNC(l) (int)((((unsigned long)l)>>12L)&0xfffL) + //#define ERR_GET_REASON(l) (int)((l)&0xfffL) + //#define ERR_FATAL_ERROR(l) (int)((l)&ERR_R_FATAL) + s32 err_line[ERR_NUM_ERRORS]; /* 0x54 - 0x57 .... 0x90 - 0x93 */ +} CR_ERR_BUFFER; + +int cr_print_flag = 0; + +// EC遘伜ッ骰オ繧堤函謌 +static int generate_EC_private_key( EC_KEY *eckey, u8 *privKey ) +{ + int ret_code; + BIGNUM *bn_privkey = NULL; + +#ifdef USE_SFMT // 繝。繝ォ繧サ繝ウ繝後サ繝繧、繧ケ繧ソ + for ( i = 0; i < EC_PRIVATE_KEY_LENGTH; i++ ) + { + privKey[i] = (u8)gen_rand32(); + } +#else /* USE_SFMT */ + ret_code = hsm_generate_random( privKey, EC_PRIVATE_KEY_LENGTH ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : hsm_generate_random\n", ret_code ); + return ret_code; + } +#endif /* USE_SFMT */ + + // ECC233 縺ァ30繝舌う繝医□縺大茜逕ィ縺吶k縺ョ縺ァ縲∝セ後m2繝舌う繝医ッ0縺ァ蝓九a繧 + // (DER(BER) 縺 big endian 縺ェ縺ョ縺ァ縲√%縺薙〒縺ッ蜈磯ュ2byte) + // + 7bit clear + 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 ) + { + return CR_GENID_ERROR_BN_NEW_0; + } + BN_init( bn_privkey ); /* memset(a,0,sizeof(BIGNUM)); */ + (void)BN_bin2bn( privKey, EC_PRIVATE_KEY_LENGTH, bn_privkey ); + eckey->priv_key = bn_privkey; + +#ifdef DEBUG_PRINT + if( cr_print_flag ) { + int i; + printf("ec private key:"); + for( i = 0 ; i < EC_PRIVATE_KEY_LENGTH ; i++ ) { + if( (i%8) == 0 ) { + printf("\n "); + } + printf("0x%02x ", privKey[i] ); + } + printf("\n"); + } +#endif /* DEBUG_PRINT */ + + return 0; +} // generate_EC_private_key + +// EC蜈ャ髢矩嵯繧堤函謌 +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 + +// X.509 險シ譏取嶌隕∵アゅr逕滓 +static int generate_X509_csr( EVP_PKEY *evp_pkey, X509_REQ *req ) +{ + int i = 0; + int ok = 0; + + X509_NAME *subj; + + X509_REQ_set_pubkey( req, evp_pkey ); + + // subjectName 蜑イ繧雁ス薙※ + subj = X509_NAME_new(); + if ( !subj ) + { + printf( "error : X509_NAME_new\n" ); + return 0; // error + } + + for ( i = 0; i < ENTRY_COUNT; i++ ) + { + int nid; + X509_NAME_ENTRY *ent; + + nid = OBJ_txt2nid( certEntries[i].key ); + if ( nid == NID_undef ) + { + printf( "Error finding NID for %s\n", certEntries[i].key ); + return 0; // error + } + + ent = X509_NAME_ENTRY_create_by_NID( NULL, nid, MBSTRING_ASC, + certEntries[i].value, -1 ); + if ( !ent ) + { + printf( "error : X509_NAME_ENTRY_create_by_NID\n" ); + return 0; // error + } + + if ( X509_NAME_add_entry( subj, ent, -1, 0 ) != 1 ) + { + printf( "error : X509_NAME_add_entry\n" ); + return 0; // error + } + } + if ( X509_REQ_set_subject_name( req, subj ) != 1 ) + { + printf( "error : X509_REQ_set_subject_name\n" ); + return 0; // error + } + + // todo : 縺薙%縺ァ v3 諡。蠑オ鬆伜沺繧偵′繧薙ー繧 + +#if 0 + // EVP_PKEY縺ョ繧ソ繧、繝励′EC縺ァ縺ゅk縺狗「コ隱 + u16 type = EVP_PKEY_type( evp_pkey->type ); + if ( type != EVP_PKEY_EC ) + { + printf( "error : EVP_PKEY_type, %d\n", type ); + return 0; // error + } +#endif + + // 隕∵アゅ↓鄂イ蜷阪☆繧 : ECDSA + if ( !(X509_REQ_sign( req, evp_pkey, EVP_ecdsa() )) ) + { + printf( "error : X509_REQ_sign\n" ); + return 0; // error + } + +#if 0 + // CSR縺ョ遒コ隱 + if( cr_print_flag ) + { + X509_REQ_print_fp( stdout, req ); + } +#endif + + ok = 1; + + return ( ok ); +} // generate_X509_csr + +// X.509 險シ譏取嶌繧堤函謌 +static int generate_X509_cert( EVP_PKEY *evp_pkey, X509_REQ *req, X509 *cert, u32 deviceId ) +{ + int ok = 0; + + X509_NAME *name; + +#if 1 + // 隕∵アよ嶌縺ォ莉倥>縺ヲ縺繧狗スイ蜷阪ョ讀懆ィシ繧定。後≧ + EVP_PKEY *pkey; + pkey = X509_REQ_get_pubkey( req ); + if ( !pkey ) + { + printf( "error : X509_REQ_get_pubkey\n" ); + return 0; // error + } + if ( X509_REQ_verify( req, pkey ) != 1 ) + { + printf( "error : X509_REQ_verify\n" ); + return 0; // error + } + EVP_PKEY_free( pkey ); +#endif + +#if 0 + // show subjectName + name = X509_REQ_get_subject_name( req ); + if ( !name ) + { + printf( "error : X509_REQ_get_subject_name\n" ); + return 0; // error + } + X509_NAME_print_ex_fp( stdout, name, 0, 0 ); + printf( "\n" ); +#endif + + // set version = 3 (0x2) + if ( X509_set_version( cert, 2L ) != 1 ) + { + printf( "error : X509_set_version\n" ); + return 0; // error + } + ASN1_INTEGER_set( X509_get_serialNumber( cert ), deviceId ); + + // 險シ譏取嶌縺ョ逋コ陦瑚蜷阪→謇譛芽蜷阪r險ュ螳 + name = X509_REQ_get_subject_name( req ); + if ( !name ) + { + printf( "error : X509_REQ_get_subject_name\n" ); + return 0; // error + } + if ( X509_set_subject_name( cert, name ) != 1 ) + { + printf( "error : X509_set_subject_name\n" ); + return 0; // error + } + + name = X509_get_subject_name( caInfo.cert ); + if ( !name ) + { + printf( "error : X509_get_subject_name\n" ); + return 0; // error + } + if ( X509_set_issuer_name( cert, name ) != 1 ) + { + printf( "error : X509_set_issuer_name\n" ); + return 0; // error + } + + // 險シ譏取嶌縺ォ蜈ャ髢矩嵯繧定ィュ螳壹☆繧 + if ( X509_set_pubkey( cert, evp_pkey ) != 1 ) + { + printf( "error : X509_set_pubkey\n" ); + return 0; // error + } + + // 險シ譏取嶌縺ョ譛牙柑譛滄俣繧定ィュ螳壹☆繧 + if ( !(X509_gmtime_adj( X509_get_notBefore( cert ), 0 )) ) + { + printf( "error : X509_gmtime_adj before\n" ); + return 0; // error + } + if ( !(X509_gmtime_adj( X509_get_notAfter( cert ), EXPIRE_SECS )) ) + { + printf( "error : X509_gmtime_adj after\n" ); + return 0; // error + } + + // CA縺ョ遘伜ッ骰オ繧剃スソ縺」縺ヲ險シ譏取嶌縺ォ鄂イ蜷阪☆繧 + //EVP_MD *dgst = EVP_ecdsa(); + //printf( "dgst length : %d\n", dgst->md_size ); + if ( !(X509_sign( cert, caInfo.privKey, EVP_ecdsa() )) ) + { + printf( "error : X509_sign\n" ); + return 0; // error + } + +#if 0 + // 險シ譏取嶌遒コ隱 + if ( cr_print_flag ) + { + X509_print_fp( stdout, cert ); + } +#endif + +#if 0 + if ( cr_print_flag ) + { + int i; + for ( i = 0; i < cert->signature->length; i++ ) + { + if ( i % 8 == 0 ) + printf( "\n" ); + printf( "0x%02X ", cert->signature->data[i] ); + } + printf( "\n" ); + } +#endif + +#if 0 + // 險シ譏取嶌縺ョ譖ク縺崎セシ縺ソ繝繧ケ繝 + FILE *fp; + char fn[256]; + sprintf( fn, "output/0x%08x.crt", deviceId ); + fp = fopen( fn, "w" ); + PEM_write_X509( fp, cert ); + fclose( fp ); +#endif + + ok = 1; + + return (ok); +} // generate_X509_cert + +// create CTR Custom cert +static int generate_CTRCustom_cert( CTR_Device_Cert *cert, u32 deviceId, u8 bondingOption ) +{ + int result; + char str[80]; + + // sigType + cert->sigType[0] = 0x00; + cert->sigType[1] = 0x01; + cert->sigType[2] = 0x00; + cert->sigType[3] = 0x02; + + // issuerName + memcpy( cert->issuerName, issuerNameDev, strlen( issuerNameDev ) ); + + // keyType + cert->keyType[0] = 0x00; + cert->keyType[1] = 0x00; + cert->keyType[2] = 0x00; + cert->keyType[3] = 0x01; + + // subject : CT + deviceID + BondingOption + sprintf( str, "CT%08X%02X", (unsigned int)deviceId, bondingOption ); + memcpy( cert->subject, str, strlen( str ) ); + + // expiryDate + result = hsm_get_rtc( &cert->expiryDate ); + if ( result != 0 ) + { + printf( "error(%d) : hsm_get_rtc\n", result ); + return result; + } + +#if 0 + if ( cr_print_flag ) + { + int i; + printf( "CTR custom cert\n" ); + printf( "sigType : 0x%08X\n", *(unsigned int*)cert->sigType ); + printf( "eccSignature :" ); + for ( i = 0; i < 60; i++ ) + { + if ( i % 16 == 0 ) + printf( "\n" ); + printf( "0x%02X ", cert->eccSignature[i] ); + } + printf( "\n" ); + printf( "padding :" ); + for ( i = 0; i < 60; i++ ) + { + if ( i % 16 == 0 ) + printf( "\n" ); + printf( "0x%02X ", cert->padding0[i] ); + } + printf( "\n" ); + printf( "subject : " ); + for ( i = 0; i < 64; i++ ) + printf( "%c", cert->issuerName[i] ); + printf( "\n" ); + printf( "keyType : 0x%08X\n", *(unsigned int*)cert->keyType ); + printf( "subject : " ); + for ( i = 0; i < 64; i++ ) + printf( "%c", cert->subject[i] ); + printf( "\n" ); + printf( "expiryDate : 0x%08X\n", (unsigned int)cert->expiryDate ); + printf( "eccPubKey :" ); + for ( i = 0; i < 60; i++ ) + { + if ( i % 16 == 0 ) + printf( "\n" ); + printf( "0x%02X ", cert->eccPubKey[i] ); + } + printf( "\n" ); + printf( "padding :" ); + for ( i = 0; i < 60; i++ ) + { + if ( i % 16 == 0 ) + printf( "\n" ); + printf( "0x%02X ", cert->padding1[i] ); + } + printf( "\n" ); + + // 險シ譏取嶌縺ョ譖ク縺崎セシ縺ソ繝繧ケ繝 + FILE *fp; + char fn[256]; + sprintf( fn, "output/0x%08x.crt", (unsigned int)deviceId ); + fp = fopen( fn, "w" ); + fwrite( cert, sizeof( CTR_Device_Cert ), 1, fp ); + fclose( fp ); + } +#endif + + return 0; +} // generate_CTRCustom_cert + +#ifndef ENCRYPT_AES +// RSA證怜捷蛹->蠕ゥ蜿キ蛹->繝吶Μ繝輔ぃ繧、 +static unsigned char local_rsa_buf_1[CR_ID_BUF_SIZE]; +static unsigned char local_rsa_buf_2[CR_ID_BUF_SIZE]; + +#ifdef DEV_CYGWIN +static int crypto_rsa_enc_dec( RSA *rsa_key_pub, RSA *rsa_key_priv, + unsigned char *dst_buf,unsigned char *org_buf) +{ + int rsa_outlen = 0; + + memset(local_rsa_buf_1, 0,CR_ID_BUF_SIZE); + memset(local_rsa_buf_2, 0,CR_ID_BUF_SIZE); + + if( (rsa_outlen = RSA_private_encrypt(CR_ID_BUF_SIZE, org_buf, local_rsa_buf_1, + rsa_key_priv, RSA_NO_PADDING)) == -1) { + return CR_GENID_ERROR_RSA_ENC; + } + else { + if((rsa_outlen = RSA_public_decrypt(rsa_outlen, local_rsa_buf_1, local_rsa_buf_2, + rsa_key_pub, RSA_NO_PADDING)) == -1) { + return CR_GENID_ERROR_RSA_DEC; + } + else { + int i; + int error_flag = 0; + for( i = 0 ; i < CR_ID_BUF_SIZE ; i++ ) { + if( org_buf[i] != local_rsa_buf_2[i] ) { + error_flag++; + } + } + if( error_flag ) { + return CR_GENID_ERROR_RSA_VERIFY; + } + } + } + memcpy(dst_buf,local_rsa_buf_1,CR_ID_BUF_SIZE); + return 0; +} +#else // cygwin +static int hsm_crypto_rsa_enc_dec( unsigned char *dst_buf,unsigned char *org_buf ) +{ + int i, ret_code; + + M_Command cmd; + M_Reply reply; + M_IV enc_iv, dec_iv; + + ret_code = 0; + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // iv + enc_iv.mech = dec_iv.mech = Mech_RSApPKCS1; + for ( i = 0; i < sizeof( enc_iv.iv.generic256.iv.bytes ); i++ ) + enc_iv.iv.generic256.iv.bytes[i] = dec_iv.iv.generic256.iv.bytes[i] = i; + + for ( i = 0; i < 256; i++ ) + { + if ( i % 16 == 0 ) + printf( "\n" ); + printf( "0x%02X ", org_buf[i] ); + } + printf( "\n" ); + + // encrypt + cmd.cmd = Cmd_Encrypt; + //cmd.args.encrypt.flags = Cmd_Encrypt_Args_flags_given_iv_present; + cmd.args.encrypt.flags |= gt_jog_flags; + cmd.args.encrypt.key = hsmRsaPubkeyid; + cmd.args.encrypt.mech = Mech_RSApPKCS1; + cmd.args.encrypt.plain.type = PlainTextType_Bytes; + cmd.args.encrypt.plain.data.bytes.data.len = CR_ID_BUF_SIZE; + cmd.args.encrypt.plain.data.bytes.data.ptr = org_buf; + cmd.args.encrypt.given_iv = &enc_iv; + ret_code = NFastApp_Transact( hsmConnection, NULL, &cmd, &reply, NULL ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : Encryption by HSM\n", ret_code ); + } + ret_code = reply.status; + if ( ret_code != Status_OK ) + { + printf( "error(%d) : Encrypt Reply Status by HSM\n", ret_code ); + } + memcpy( local_rsa_buf_1, + reply.reply.encrypt.cipher.data.generic128.cipher.ptr, + CR_ID_BUF_SIZE ); + + //NFastApp_Free_Command( hsmHandle, NULL, NULL, &cmd ); + NFastApp_Free_Reply( hsmHandle, NULL, NULL, &reply ); + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // decyrpt + cmd.cmd = Cmd_Decrypt; + cmd.args.decrypt.flags = 0; + cmd.args.decrypt.key = hsmAeskeyid; + cmd.args.decrypt.mech = Mech_RijndaelmCBCpNONE; + cmd.args.decrypt.cipher.mech = Mech_RijndaelmCBCpNONE; + cmd.args.decrypt.cipher.data.generic128.cipher.len = CR_ID_BUF_SIZE; + cmd.args.decrypt.cipher.data.generic128.cipher.ptr = local_rsa_buf_1; + cmd.args.decrypt.cipher.iv = dec_iv.iv; + cmd.args.decrypt.reply_type = PlainTextType_Bytes; + ret_code = NFastApp_Transact( hsmConnection, NULL, &cmd, &reply, NULL ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : Decryption by HSM\n", ret_code ); + } + ret_code = reply.status; + if ( ret_code != Status_OK ) + { + printf( "error(%d) : Decrypt Reply Status by HSM\n", ret_code ); + } + memcpy( local_rsa_buf_2, + reply.reply.decrypt.plain.data.bytes.data.ptr, + CR_ID_BUF_SIZE ); + + //NFastApp_Free_Command( hsmHandle, NULL, NULL, &cmd ); + NFastApp_Free_Reply( hsmHandle, NULL, NULL, &reply ); + + // 繝吶Μ繝輔ぃ繧、 + for ( i = 0 ; i < CR_ID_BUF_SIZE ; i++ ) + { + if( org_buf[i] != local_rsa_buf_2[i] ) + { + printf( "error : aes verify\n" ); + return 0; + } + } + + // 繝舌ャ繝輔ぃ繧ウ繝斐シ + memcpy( dst_buf, local_rsa_buf_1, CR_ID_BUF_SIZE ); + + return 0; +} // hsm_crypto_rsa_enc_dec +#endif // linux +#else +// AES證怜捷蛹 -> 蠕ゥ蜿キ蛹 -> 繝吶Μ繝輔ぃ繧、 +static unsigned char local_aes_buf_1[ CR_ID_BUF_SIZE ]; +static unsigned char local_aes_buf_2[ CR_ID_BUF_SIZE ]; + +#ifdef DEV_CYGWIN +static int crypto_aes_enc_dec( unsigned char *dst_buf, unsigned char *org_buf ) +{ + int i; + + AES_KEY aesEncKey; + AES_KEY aesDecKey; + + u8 temp_iv[16]; + + memset( local_aes_buf_1, 0, CR_ID_BUF_SIZE ); + memset( local_aes_buf_2, 0, CR_ID_BUF_SIZE ); + + // AES 證怜捷蛹也畑骰オ 菴懈 + if ( AES_set_encrypt_key( AES_PASS_PHRASE, 128, &aesEncKey ) != 0 ) + { + printf( "error : AES_set_encrypt_key\n" ); + return 0; + } + + // AES 蠕ゥ蜿キ蛹也畑骰オ 菴懈 + if ( AES_set_decrypt_key( AES_PASS_PHRASE, 128, &aesDecKey ) != 0 ) + { + printf( "error : AES_set_decrypt_key\n" ); + return 0; + } + + // iv 蛻晄悄蛹 + for ( i = 0; i < 16; i++ ) + { + temp_iv[i] = i; + } + + // AES 證怜捷蛹 + AES_cbc_encrypt ( org_buf, local_aes_buf_1, CR_ID_BUF_SIZE, &aesEncKey, temp_iv, AES_ENCRYPT ); + + // iv 蛻晄悄蛹 + for ( i = 0; i < 16; i++ ) + { + temp_iv[i] = i; + } + + // AES 蠕ゥ蜿キ蛹 + AES_cbc_encrypt ( local_aes_buf_1, local_aes_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_aes_buf_2[i] ) + { + printf( "error : aes verify\n" ); + return 0; + } + } + + // 繝舌ャ繝輔ぃ繧ウ繝斐シ + memcpy( dst_buf, local_aes_buf_1, CR_ID_BUF_SIZE ); + + return 0; +} // crypto_aes_enc_dec +#else // DEV_CYGWIN(openssl) +static int hsm_crypto_aes_enc_dec( unsigned char *dst_buf, unsigned char *org_buf ) +{ + int i, ret_code; + + M_Command cmd; + M_Reply reply; + M_IV enc_iv, dec_iv; + + ret_code = 0; + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // iv + enc_iv.mech = dec_iv.mech = Mech_RijndaelmCBCpNONE; + for ( i = 0; i < 16; i++ ) + enc_iv.iv.generic128.iv.bytes[i] = dec_iv.iv.generic128.iv.bytes[i] = i; + + // encrypt + cmd.cmd = Cmd_Encrypt; + cmd.args.encrypt.key = hsmAeskeyid; + cmd.args.encrypt.mech = Mech_RijndaelmCBCpNONE; + cmd.args.encrypt.plain.type = PlainTextType_Bytes; + cmd.args.encrypt.plain.data.bytes.data.len = CR_ID_BUF_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; + ret_code = NFastApp_Transact( hsmConnection, NULL, &cmd, &reply, NULL ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : Encryption by HSM\n", ret_code ); + } + ret_code = reply.status; + if ( ret_code != Status_OK ) + { + printf( "error(%d) : Encrypt Reply Status by HSM\n", ret_code ); + } + memcpy( local_aes_buf_1, + reply.reply.encrypt.cipher.data.generic128.cipher.ptr, + CR_ID_BUF_SIZE ); + + //NFastApp_Free_Command( hsmHandle, NULL, NULL, &cmd ); + NFastApp_Free_Reply( hsmHandle, NULL, NULL, &reply ); + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // decyrpt + cmd.cmd = Cmd_Decrypt; + cmd.args.decrypt.flags = 0; + cmd.args.decrypt.key = hsmAeskeyid; + cmd.args.decrypt.mech = Mech_RijndaelmCBCpNONE; + cmd.args.decrypt.cipher.mech = Mech_RijndaelmCBCpNONE; + cmd.args.decrypt.cipher.data.generic128.cipher.len = CR_ID_BUF_SIZE; + cmd.args.decrypt.cipher.data.generic128.cipher.ptr = local_aes_buf_1; + cmd.args.decrypt.cipher.iv = dec_iv.iv; + cmd.args.decrypt.reply_type = PlainTextType_Bytes; + ret_code = NFastApp_Transact( hsmConnection, NULL, &cmd, &reply, NULL ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : Decryption by HSM\n", ret_code ); + } + ret_code = reply.status; + if ( ret_code != Status_OK ) + { + printf( "error(%d) : Decrypt Reply Status by HSM\n", ret_code ); + } + memcpy( local_aes_buf_2, + reply.reply.decrypt.plain.data.bytes.data.ptr, + CR_ID_BUF_SIZE ); + + //NFastApp_Free_Command( hsmHandle, NULL, NULL, &cmd ); + NFastApp_Free_Reply( hsmHandle, NULL, NULL, &reply ); + + // 繝吶Μ繝輔ぃ繧、 + for ( i = 0 ; i < CR_ID_BUF_SIZE ; i++ ) + { + if( org_buf[i] != local_aes_buf_2[i] ) + { + printf( "error : aes verify\n" ); + return 0; + } + } + + // 繝舌ャ繝輔ぃ繧ウ繝斐シ + memcpy( dst_buf, local_aes_buf_1, CR_ID_BUF_SIZE ); + + return 0; +} // hsm_crypto_aes_enc_dec +#endif // HSM +#endif + +static int hsm_generate_random( unsigned char *buf, int bytes ) +{ + int ret_code; + 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 != Status_OK ) + { + printf( "error(%d) : generate random\n", ret_code ); + return ret_code; + } + ret_code = reply.status; + if ( ret_code != Status_OK ) + { + printf( "error(%d) : generate random reply\n", ret_code ); + 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 0; +} // hsm_generate_rand + +#if 0 +static int hsm_set_rtc( struct timeval time ) +{ + int result; + + M_Command cmd; + M_Reply reply; + + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + cmd.cmd = Cmd_SetRTC; + cmd.args.setrtc.module = HSM_MODULE_ID; + cmd.args.setrtc.time.currenttimelow = time.tv_sec; + + result = NFastApp_Transact( hsmConnection, NULL, &cmd, &reply, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : set rtc(transaction)\n", result ); + return result; + } + result = reply.status; + if ( result != Status_OK ) + { + printf( "error(%d) : set rtc(reply status)\n", result ); + return result; + } + + return 0; +} +#endif + +static int hsm_get_rtc( time_t *time ) +{ + int result; + + 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; + + result = NFastApp_Transact( hsmConnection, NULL, &cmd, &reply, NULL ); + if ( result != Status_OK ) + { + printf( "error(%d) : get rtc(transaction)\n", result ); + return result; + } + result = reply.status; + if ( result != Status_OK ) + { + printf( "error(%d) : get rtc(reply status)\n", result ); + return result; + } + + *time = (int)reply.reply.getrtc.time.currenttimelow; + + return 0; +} // hsm_get_rtc + + +int cr_generate_id_initialize( void ) +{ + int ret_code = 0; + + FILE *fp; + + // init HSM + ret_code = NFastApp_InitEx( &hsmHandle, NULL, NULL ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : NFastApp_InitEx\n", ret_code ); + return ret_code; + } + + // set BigNum upcalls for HSM + ret_code = NFastApp_SetBignumUpcalls( + hsmHandle, + sbn_bignumreceiveupcall, + sbn_bignumsendlenupcall, + sbn_bignumsendupcall, + sbn_bignumfreeupcall, + sbn_bignumformatupcall, + NULL ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : NFastApp_SetBignumUpcalls\n", ret_code ); + } + + // connect HSM + // arg3 is flag + // NFastApp_ConnectionFlags_Privileged flag need to run by nfast user. + ret_code = NFastApp_Connect( hsmHandle, &hsmConnection, 0, NULL ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : NFastApp_Connect\n", ret_code ); + } + + // get NFKM info + ret_code = NFKM_getinfo( hsmHandle, &hsmWorld, NULL ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : NFKM_getinfo\n", ret_code ); + } + + // init Card-Loading Lib(RQCard) + ret_code = RQCard_init( &hsmCard, hsmHandle, hsmConnection, hsmWorld, NULL ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : RQCard_init\n", ret_code ); + } + + // init FIPS state + ret_code = RQCard_fips_init( &hsmCard, &hsmFips ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : RQCard_fips_init\n", ret_code ); + } + + // select Card-Auth UI + ret_code = RQCard_ui_scroll( &hsmCard ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : RQCard_ui_scroll\n", ret_code ); + } + + // load AES key object + { + // find key + ret_code = NFKM_findkey( hsmHandle, hsmAeskeyident, &hsmAeskeyinfo, NULL ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : NFKM_findkey\n", ret_code ); + } + + // if Key_flags_ProtectionCardSet is enable, eventloop is an essential. + if ( hsmAeskeyinfo->flags & Key_flags_ProtectionCardSet ) + { + // load specific OCS + ret_code = RQCard_logic_ocs_specific( &hsmCard, &hsmAeskeyinfo->cardset, NULL ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : RQCard_logic_ocs_specific\n", ret_code ); + } + + // use specific Module + ret_code = RQCard_whichmodule_specific( &hsmCard, HSM_MODULE_ID, &hsmLtid ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : RQCard_whichmodule_specific\n", ret_code ); + } + + // eventloop + ret_code = hsmCard.uf->eventloop( &hsmCard ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : Card eventloop\n", ret_code ); + } + } + + // get usable Module + hsmModuleinfo = hsmWorld->modules[0]; + ret_code = NFKM_getusablemodule( hsmWorld, HSM_MODULE_ID, &hsmModuleinfo ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : NFKM_getusablemodule\n", ret_code ); + } + + // load key blob + if ( hsmAeskeyinfo->pubblob.len ) + hsmBlobptr = &hsmAeskeyinfo->pubblob; + else + hsmBlobptr = &hsmAeskeyinfo->privblob; + ret_code = NFKM_cmd_loadblob( hsmHandle, hsmConnection, + hsmModuleinfo->module, hsmBlobptr, + hsmLtid, &hsmAeskeyid, + "loading key blob", NULL ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : NFKM_cmd_loadblob\n", ret_code ); + } + + printf( "AES key object load : ok\n" ); + } // load AES key object + + // load RSA private key object + { + // find key + ret_code = NFKM_findkey( hsmHandle, hsmRsakeyident, &hsmRsakeyinfo, NULL ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : NFKM_findkey\n", ret_code ); + } + + // if Key_flags_ProtectionCardSet is enable, eventloop is an essential. + if ( hsmRsakeyinfo->flags & Key_flags_ProtectionCardSet ) + { + // load specific OCS + ret_code = RQCard_logic_ocs_specific( &hsmCard, &hsmRsakeyinfo->cardset, NULL ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : RQCard_logic_ocs_specific\n", ret_code ); + } + + // use specific Module + ret_code = RQCard_whichmodule_specific( &hsmCard, HSM_MODULE_ID, &hsmLtid ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : RQCard_whichmodule_specific\n", ret_code ); + } + + // eventloop + ret_code = hsmCard.uf->eventloop( &hsmCard ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : Card eventloop\n", ret_code ); + } + } + + // get usable Module + hsmModuleinfo = hsmWorld->modules[0]; + ret_code = NFKM_getusablemodule( hsmWorld, HSM_MODULE_ID, &hsmModuleinfo ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : NFKM_getusablemodule\n", ret_code ); + } + + // load key blob + printf( "pubblob.len : %d, privblob.len : %d\n", + (int)hsmRsakeyinfo->pubblob.len, (int)hsmRsakeyinfo->privblob.len ); + hsmBlobptr = &hsmRsakeyinfo->privblob; + ret_code = NFKM_cmd_loadblob( hsmHandle, hsmConnection, + hsmModuleinfo->module, hsmBlobptr, + hsmLtid, &hsmRsaPrivkeyid, + "loading priv-key blob", NULL ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : NFKM_cmd_loadblob(priv-key)\n", ret_code ); + } + printf( "RSA private key object load : ok\n" ); + hsmBlobptr = &hsmRsakeyinfo->pubblob; + ret_code = NFKM_cmd_loadblob( hsmHandle, hsmConnection, + hsmModuleinfo->module, hsmBlobptr, + hsmLtid, &hsmRsaPubkeyid, + "loading pub-key blob", NULL ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : NFKM_cmd_loadblob(pub-key)\n", ret_code ); + } + printf( "RSA public key object load : ok\n" ); + + // get key info + { + M_Command cmd; + M_Reply reply; + + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + cmd.cmd = Cmd_GetKeyInfo; + cmd.args.getkeyinfo.key = hsmRsaPrivkeyid; + ret_code = NFastApp_Transact( hsmConnection, NULL, &cmd, &reply, NULL ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : FastApp_Transact(Cmd_GetKeyInfo)\n", ret_code ); + } + } + + #if 0 + // get & set key acl + { + int i, j; + M_Command cmd; + M_Reply reply; + M_ACL newACL; + + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + + // GetACL + cmd.cmd = Cmd_GetACL; + cmd.args.getacl.key = hsmRsaPrivkeyid; + ret_code = NFastApp_Transact( hsmConnection, NULL, &cmd, &reply, NULL ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : FastApp_Transact(Cmd_GetKeyInfo)\n", ret_code ); + } + printf( "n_groups : %d\n", reply.reply.getacl.acl.n_groups ); + for ( i = 0; i < reply.reply.getacl.acl.n_groups; i++ ) + { + printf( "group[%d] : %d actions ok.\n", i, reply.reply.getacl.acl.groups[i].n_actions ); + for ( j = 0; j < reply.reply.getacl.acl.groups[i].n_actions; j++ ) + { + if ( reply.reply.getacl.acl.groups[i].actions[j].type == 1 ) // Act_OpPermissions + printf( "OpPermissions : %08X\n", + (int)reply.reply.getacl.acl.groups[i].actions[j].details.oppermissions.perms ); + } + } + newACL = reply.reply.getacl.acl; + + memset( &cmd, 0, sizeof( cmd ) ); + memset( &reply, 0, sizeof( reply ) ); + NFastApp_Free_Reply( hsmHandle, NULL, NULL, &reply ); + + // find cardsets + NFKM_CardSet *cardset = NULL; + ret_code = NFKM_findcardset( hsmHandle, &(hsmRsakeyinfo->cardset), &cardset, NULL ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : NFKM_findcardset\n", ret_code ); + } + + #if 0 + // make new ACL + NFKM_MakeACLParams map; + NFKM_MakeBlobsParams mbp; + M_ACL newACL; + memset( &map, 0, sizeof( map ) ); + map.f = NFKM_NKF_RecoveryEnabled | NFKM_NKF_ProtectionCardSet; + map.op_base = (NFKM_DEFOPPERMS_SIGN | NFKM_DEFOPPERMS_VERIFY | + NFKM_DEFOPPERMS_ENCRYPT | NFKM_DEFOPPERMS_DECRYPT ); + map.cs = cardset; + ret_code = NFKM_newkey_makeaclx( hsmHandle, hsmConnection, hsmWorld, &map, + &newACL, NULL ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : NFKM_newkey_makeaclx\n", ret_code ); + } + #endif + + // SetACL + cmd.cmd = Cmd_SetACL; + cmd.args.setacl.key = hsmRsaPrivkeyid; + cmd.args.setacl.newacl = newACL; + ret_code = NFastApp_Transact( hsmConnection, NULL, &cmd, &reply, NULL ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : set acl(transaction)\n", ret_code ); + } + ret_code = reply.status; + if ( ret_code != Status_OK ) + { + printf( "error(%d) : set acl(reply status)\n", ret_code ); + } + + } + #endif + } // load RSA private key object + + // CA縺ョ險シ譏取嶌繧定ェュ縺ソ霎シ繧 + fp = fopen( CA_FILE, "r" ); + if ( !fp ) + { + printf( "error : read CA_Cert file\n" ); + return 0; // error + } + caInfo.cert = PEM_read_X509( fp, NULL, NULL, NULL ); + if ( !(caInfo.cert) ) + { + printf( "error : read CA_Cert in file\n" ); + return 0; // error + } + fclose( fp ); + +#if 0 + // CA縺ョ險シ譏取嶌遒コ隱 + if ( cr_print_flag ) + { + X509_print_fp( stdout, caCert ); + } +#endif + + // CA縺ョ遘伜ッ骰オ繧定ェュ縺ソ霎シ繧 + fp = fopen( CA_KEY, "r" ); + if ( !fp ) + { + printf( "error : read CA_KEY file\n" ); + return 0; // error + } + caInfo.privKey = PEM_read_PrivateKey( fp, NULL, NULL, NULL ); + if ( !(caInfo.privKey) ) + { + printf( "error : read CA_KEY in file\n" ); + return 0; // error + } + fclose( fp ); + + ret_code = 1; + + return ( ret_code ); +} // cr_generate_id_initialize + +int cr_generate_id_finalize( void ) +{ + int ok = 0; + + // openssl + ERR_remove_state(0); + EVP_cleanup(); + CRYPTO_cleanup_all_ex_data(); + + // HSM + RQCard_fips_free( &hsmCard, &hsmFips ); + RQCard_destroy( &hsmCard ); + NFKM_freekey( hsmHandle, hsmAeskeyinfo, NULL ); + NFKM_freeinfo( hsmHandle, &hsmWorld, NULL ); + NFastApp_Disconnect( hsmConnection, NULL ); + NFastApp_Finish( hsmHandle, NULL ); + + ok = 1; + + return ( ok ); +} // cr_generate_id_finalize + +/* + unsigned long ERR_get_error(void); + 繧ィ繝ゥ繝シ縺瑚オキ縺薙▲縺溘→縺 id_buf 縺ォ繧ィ繝ゥ繝シ繝ュ繧ー繧定ソ斐☆縺具シ + */ + +int cr_generate_id( u32 serial[CR_NUM_OF_SERIAL], u8 id_buf[CR_ID_BUF_SIZE], u8 bondingOption ) +{ + int i; + int ret_code; + EC_KEY *my_eckey = NULL; + EVP_PKEY *my_evppkey = NULL; + RSA *rsa_privkey = NULL; + RSA *rsa_pubkey = NULL; + + X509_REQ *req = NULL; + X509 *cert = NULL; + + struct tm *tm_time; + struct timeval tv; + struct timezone tz; + + CR_ID_BUFFER *cr_id_buf; + u8 hash[SHA256_DIGEST_LENGTH]; /* SHA256 check */ + CTR_Device_Cert ctr_dev_cert; + + if( sizeof(CR_ID_BUFFER) != 256 ) { + ret_code = CR_GENID_ERROR_ID_BUF_SIZE; + goto end; + } + + if( sizeof(CR_ERR_BUFFER) > 256 ) { + ret_code = CR_GENID_ERROR_ERR_BUF_SIZE; + goto end; + } + + if ( sizeof( CTR_Device_Cert ) > 384 ) + { + //ret_code = CR_GENID_ERROR_CERT_BUF_SIZE; // ATODE + goto end; + } + + ret_code = CR_GENID_ERROR_NON; /* CR_GENID_ERROR_NON = 0 */ + + // printf("sizeof(CR_ID_BUFFER) = %d bytes\n",sizeof(CR_ID_BUFFER) ); + // printf("offset(factory, CR_ID_BUFFER) = 0x%02x bytes\n", offsetof(CR_ID_BUFFER,factory ) ); + // printf("sizeof(CR_ERR_BUFFER) = 0x%02x bytes\n",sizeof(CR_ERR_BUFFER) ); + // printf("offset(err_buffer, CR_ERR_BUFFER) = 0x%02x bytes\n", offsetof(CR_ERR_BUFFER,err_buffer ) ); + // printf("offset(err_line, CR_ERR_BUFFER) = 0x%02x bytes\n", offsetof(CR_ERR_BUFFER,err_line ) ); + +// 繝繧、繧ク繧ァ繧ケ繝医い繝ォ繧エ繝ェ繧コ繝繧定ソス蜉縺吶k +#if 0 + OpenSSL_add_all_digests(); +#else + EVP_add_digest( EVP_ecdsa() ); +#endif + + //-------------------------------------------------------------- + // 證怜捷蜃ヲ逅蛻晄悄蛹 + //-------------------------------------------------------------- + + // 繝。繝「繝ェ繝ェ繝シ繧ッ髦イ豁「縺ョ縺溘a縲√が繝ェ繧ク繝翫Ν縺ョ繧「繝ュ繧ア繝シ繧ソ繧剃スソ逕ィ縲 + CRYPTO_set_mem_functions(cr_mem_malloc, cr_mem_realloc, cr_mem_free); + cr_mem_bufmgr_initialize(); + +#ifdef MY_CRYPTO_DEBUG + ERR_load_crypto_strings(); +#endif /* MY_CRYPTO_DEBUG */ + + //-------------------------------------------------------------- + // FuseID繝舌ャ繝輔ぃ縺ォ蝗コ螳壹ョ繝シ繧ソ繧サ繝繝 + //-------------------------------------------------------------- + memset(id_buf, 0, CR_ID_BUF_SIZE); + + cr_id_buf = (CR_ID_BUFFER *)id_buf; + cr_id_buf->magic_number = 0xdeadb00f; /* 0xdeadbeef縺ォ縺吶k縺ィシイシウシ。縺ァ繧ウ繧ア繧九 */ + cr_id_buf->version = CR_GEN_ID_VERSION; + + //-------------------------------------------------------------- + // 蠑墓焚縺ョ繝懊Φ繝繧」繝ウ繧ー繧ェ繝励す繝ァ繝ウ繧偵そ繝繝 + //-------------------------------------------------------------- + cr_id_buf->bondingOption = bondingOption; + + //-------------------------------------------------------------- + // serialNo.繧サ繝繝 + //-------------------------------------------------------------- + for( i = 0 ; i < CR_NUM_OF_SERIAL ; i++ ) + { + cr_id_buf->serial[i] = serial[i]; /* serial[0] => ec priv key */ + } + +//#ifdef DEBUG_PRINT +#if 1 + if( cr_print_flag ) { + printf("serialNo:\n"); + for( i = 0 ; i < CR_NUM_OF_SERIAL ; i++ ) { + if( i == 0 ) printf(" 0x%08x\n", (unsigned int)serial[i] ); + else if( i & 0x01 ) printf(" 0x%08x", (unsigned int)serial[i] ); + else printf("%08x\n", (unsigned int)serial[i] ); + } + printf("\n"); + } +#endif /* DEBUG_PRINT */ + + //-------------------------------------------------------------- + // 繧ソ繧、繝繧ケ繧ソ繝ウ繝励そ繝繝 + //-------------------------------------------------------------- + hsm_get_rtc( &tv.tv_sec ); + tm_time = gmtime( &tv.tv_sec ); + + +#ifdef DEBUG_PRINT + if( cr_print_flag ) + { + printf("GMT:%d-%02d-%02d %02d:%02d:%02d\n", + tm_time->tm_year+1900, /* 蟷エ */ + tm_time->tm_mon+1, /* 譛 */ + tm_time->tm_mday, /* 譌・ */ + tm_time->tm_hour, /* 譎 */ + tm_time->tm_min, /* 蛻 */ + tm_time->tm_sec /* 遘 */ + ); + } +#endif /* DEBUG_PRINT */ + + cr_id_buf->year = (u8)tm_time->tm_year; + cr_id_buf->month = (u8)tm_time->tm_mon+1; + cr_id_buf->mday = (u8)tm_time->tm_mday; + cr_id_buf->hour = (u8)tm_time->tm_hour; + cr_id_buf->min = (u8)tm_time->tm_min; + cr_id_buf->sec = (u8)tm_time->tm_sec; + + //-------------------------------------------------------------- + // 荵ア謨ー繧堤函謌舌@縺ヲ繧サ繝繝 + //-------------------------------------------------------------- + ret_code = hsm_generate_random( cr_id_buf->random, CR_RANDOM_LENGTH ); + if ( ret_code != Status_OK ) + { + printf( "error(%d) : hsm_generate_random\n", ret_code ); + return ret_code; + } + +#ifdef DEBUG_PRINT + if( cr_print_flag ) { + unsigned char *p = (unsigned char *)cr_id_buf->random; + printf("rand:" ); + for( i = 0 ; i < CR_RANDOM_LENGTH; i++ ) { + if( (i % 16) == 0 ) { + printf("\n "); + } + printf("0x%02x ", p[ i ] ); + } + printf("\n"); + } +#endif /* DEBUG_PRINT */ + + //-------------------------------------------------------------- + // 讌募譖イ邱夐嵯繝壹い繧堤函謌 + //-------------------------------------------------------------- + // 讌募繧帝∈謚 ( NID_X9_62_prime256v1 -> 32bytes縺セ縺ァ縲 NID_sect571r1 -> 71bytes縺セ縺ァ 鄂イ蜷阪↓繝繝シ繧ソ繧貞性繧√i繧後k ) + my_eckey = EC_KEY_new_by_curve_name( NID_sect233r1 ); + if( my_eckey == NULL ) + { + ret_code = CR_GENID_ERROR_EC_KEY_NEW_1; + goto end; + } + + // 遘伜ッ骰オ逕滓 + ret_code = generate_EC_private_key( my_eckey, cr_id_buf->devicePrivKey ); + if( ret_code != 0 ) + { + ret_code = CR_GENID_ERROR_EC_GENERATE_PRIVATE_KEY; + goto end; + } + + // 蜈ャ髢矩嵯逕滓 + ret_code = generate_EC_public_key( my_eckey ); + if ( ret_code == 0 ) + { + ret_code = CR_GENID_ERROR_EC_GENERATE_PUBLIC_KEY; + goto end; + } + + // ASN.1 蠖「蠑乗欠螳壹ヵ繝ゥ繧ー繧偵そ繝繝医☆繧 + // (縺薙l繧偵そ繝繝医@縺ェ縺縺ィ濶イ縲螟峨↑繝輔ぅ繝シ繝ォ繝峨′蜈・縺」縺ヲ縺励∪縺縺溘a) + EC_KEY_set_asn1_flag( my_eckey, 1 ); + + ret_code = CR_GENID_ERROR_NON; // TORIAEZU + +#if 0 + //-------------------------------------------------------------- + // 逕滓舌@縺滄嵯繝壹い繧脱CDSA縺ァ蜍穂ス懃「コ隱 + //-------------------------------------------------------------- + ret_code = TestECDSA( hoge hoge ); + // 蠖鍋┯繧繧九∋縺 +#endif + + //-------------------------------------------------------------- + // 險シ譏取嶌縺ョ逋コ陦後↓蜈育ォ九▲縺ヲEVP_PKEY繧ェ繝悶ず繧ァ繧ッ繝医r逕滓舌☆繧 + //-------------------------------------------------------------- + // EC_KEY繧貞縺ォEVP_PKEY繧堤函謌 + my_evppkey = EVP_PKEY_new(); + if ( !my_evppkey ) + { + printf( "error : EVP_PKEY_new\n" ); + return 0; // error + } + // assign_EC_KEY 縺縺ィ縲骰オ繧ェ繝悶ず繧ァ繧ッ繝医r謇譛峨☆繧九◆繧√√Γ繝「繝ェ繝ェ繝シ繧ッ縺吶kシ +#if 1 + if ( !EVP_PKEY_set1_EC_KEY( my_evppkey, my_eckey ) ) + { + printf( "error : EVP_PKEY_set1_EC_KEY\n" ); + return 0; // error + } +#else + if ( !EVP_PKEY_assign_EC_KEY( my_evppkey, my_eckey) ) + { + printf( "error : EVP_PKEY_assign_EC_KEY\n" ); + return 0; // error + } +#endif + + //printf( "evp_pkey size : %d\n", EVP_PKEY_size( my_evppkey ) ); + + //-------------------------------------------------------------- + // 繝繝舌う繧ケ險シ譏取嶌隕∵アら函謌 + //-------------------------------------------------------------- + req = X509_REQ_new(); // 蜻シ縺ウ蜃コ縺怜医〒 new 縺吶k縺ィ豁」縺励¥繝。繝「繝ェ遒コ菫昴&繧後↑縺シ + if ( !req ) + { + printf( "error : X509_REQ_new\n" ); + return 0; // error + } + generate_X509_csr( my_evppkey, req ); + + //-------------------------------------------------------------- + // 繝繝舌う繧ケ險シ譏取嶌逋コ陦 (X.509 v3) + //-------------------------------------------------------------- + cert = X509_new(); // 蜻シ縺ウ蜃コ縺怜医〒 new 縺吶k縺ィ豁」縺励¥繝。繝「繝ェ遒コ菫昴&繧後↑縺シ + if ( !cert ) + { + printf( "error : X509_new\n" ); + return 0; // error + } + generate_X509_cert( my_evppkey, req, cert, cr_id_buf->serial[0] ); + + //-------------------------------------------------------------- + // 繝繝舌う繧ケ險シ譏取嶌縺ョ鄂イ蜷阪r繧サ繝繝 + //-------------------------------------------------------------- + int padding = ECDSA_SIGN_LENGTH % cert->signature->length; + for ( i = 0; i < padding; i++ ) + cr_id_buf->deviceCertSign[i] = 0; + for ( i = 0; i < cert->signature->length; i++ ) + cr_id_buf->deviceCertSign[ i + padding ] = cert->signature->data[i]; + // mistake!! + + // TORIAEZU : create Custom cert + memset( &ctr_dev_cert, 0, sizeof( ctr_dev_cert ) ); + // copy ecpubkey to Custom cert + int len = BN_num_bytes( &my_eckey->pub_key->X ); + u8 *buf = (u8*)malloc( len ); + len = BN_bn2bin( &my_eckey->pub_key->X, buf ); + memcpy( ctr_dev_cert.eccPubKey, buf, len ); + free( buf ); + len = BN_num_bytes( &my_eckey->pub_key->Y ); + buf = (u8*)malloc( len ); + len = BN_bn2bin( &my_eckey->pub_key->Y, buf ); + memcpy( &ctr_dev_cert.eccPubKey[30], buf, len ); + free( buf ); + // copy sign to Custom cert +//#define SHOW_SIG + u8 *ptr = cert->signature->data; +#ifdef SHOW_SIG + printf( "signature\n" ); + printf( "SEQUENCE : 0x%02X\n", *(ptr++) ); + printf( "ALL_LEN : 0x%02X\n", *(ptr++) ); + printf( "INTEGER : 0x%02X\n", *(ptr++) ); + len = *(ptr++); + printf( "r LEN : 0x%02X\n", len ); + printf( "r :" ); + for ( i = 0; i < len; i++ ) + { + if ( i % 8 == 0 ) + printf( "\n" ); + printf( "0x%02X ", *(ptr++) ); + } + printf( "\n" ); + printf( "INTEGER : 0x%02X\n", *(ptr++) ); + len = *(ptr++); + printf( "s LEN : 0x%02X\n", len ); + printf( "s :" ); + for ( i = 0; i < len; i++ ) + { + if ( i % 8 == 0 ) + printf( "\n" ); + printf( "0x%02X ", *(ptr++) ); + } + printf( "\n" ); +#else + ptr += 3; + int r_len = *(ptr++); + for ( i = 0; i < r_len; i++ ) + ctr_dev_cert.eccSignature[i] = *(ptr++); + ptr++; + int s_len = *(ptr++); + for ( i = 0; i < r_len; i++ ) + ctr_dev_cert.eccSignature[i+30] = *(ptr++); + + // create CTR Custom cert + ret_code = generate_CTRCustom_cert( &ctr_dev_cert, + cr_id_buf->serial[0], cr_id_buf->bondingOption ); +#endif + +#if 0 + if( cr_print_flag ) + { + for( i = 0 ; i < ECDSA_SIGN_LENGTH; i++ ) + { + if( (i%8) == 0 ) + { + printf( "\n "); + } + printf("0x%02x ", cr_id_buf->deviceCertSign[i] ); + } + printf("\n"); + } +#endif /* DEBUG_PRINT */ + + //-------------------------------------------------------------- + // FuseID繝舌ャ繝輔ぃ蜈ィ菴薙ョSHA256繝上ャ繧キ繝・繧堤ョ怜コ縺励※繧サ繝繝 + //-------------------------------------------------------------- + SHA256(id_buf, CR_ID_BUF_SIZE - SHA256_DIGEST_LENGTH, cr_id_buf->hash); + + memcpy( hash, cr_id_buf->hash, SHA256_DIGEST_LENGTH ); + +#ifdef DEBUG_PRINT + if( cr_print_flag ) { + printf("SHA256 Digest:"); + for( i = 0 ; i < SHA256_DIGEST_LENGTH ; i++ ) { + if( (i%8) == 0 ) { + printf("\n "); + } + printf("0x%02x ", cr_id_buf->hash[i] ); + } + printf("\n"); + } +#endif /* DEBUG_PRINT */ + +#ifndef ENCRYPT_AES + //-------------------------------------------------------------- + // FuseID繝舌ャ繝輔ぃ蜈ィ菴薙rRSA遘伜ッ骰オ縺ァ證怜捷蛹 + //-------------------------------------------------------------- + +#ifdef DEBUG_PRINT + if( cr_print_flag ) { + printf("ORG buf:"); + for( i = 0 ; i < CR_ID_BUF_SIZE ; i++ ) { + if( (i%16) == 0 ) { + printf("\n "); + } + printf("0x%02x ", id_buf[i] ); + } + printf("\n"); + } +#endif /* DEBUG_PRINT */ + +#ifdef DEV_CYGWIN + // DER繝輔か繝シ繝槭ャ繝医ョRSA骰オ繧定ェュ縺ソ霎シ縺ソ + { + const unsigned char *der_priv = cr_gen_id_rsa_key_priv_DER + 0x10; // 繝倥ャ繝驛ィ蛻繧帝勁螟悶@縺ヲKEY螳滉ス薙r謖螳 + const unsigned char *der_pub = cr_gen_id_rsa_key_pub_DER + 0x10; // 蜷御ク + int priv_len = cr_gen_id_rsa_key_priv_DER[ 8 ] | cr_gen_id_rsa_key_priv_DER[ 9 ] << 8; // KEY髟キ繧貞叙繧雁コ縺 + int pub_len = cr_gen_id_rsa_key_pub_DER [ 8 ] | cr_gen_id_rsa_key_pub_DER [ 9 ] << 8; // 蜷御ク + // 繧ウ繝槭Φ繝峨Λ繧、繝ウ縺ョopenssl縺悟コ蜉帙☆繧狗ァ伜ッ骰オ縺ッ縲 ̄KCS#1 RSAPublicKey繝輔か繝シ繝槭ャ繝医↑縺ョ縺ァ縲√%縺ョ髢「謨ー繧剃スソ縺縲 + rsa_privkey = d2i_RSAPrivateKey( NULL, &der_priv, priv_len ); + if( rsa_privkey == NULL ) { + ret_code = CR_GENID_ERROR_RSA_READ_PRIVATE_KEY; + goto end; + } + // 繧ウ繝槭Φ繝峨Λ繧、繝ウ縺ョopenssl縺悟コ蜉帙☆繧句ャ髢矩嵯縺ッ縲ヾubjectPublicKeyInfo蠖「蠑上↑縺ョ縺ァ縲√%縺ョ髢「謨ー繧剃スソ縺縲 + rsa_pubkey = d2i_RSA_PUBKEY( NULL, &der_pub, pub_len ); + if( rsa_pubkey == NULL ) { + ret_code = CR_GENID_ERROR_RSA_READ_PUBLIC_KEY; + goto end; + } + } + + // RSA證怜捷蛹 -> 蠕ゥ蜿キ蛹 -> 繝吶Μ繝輔ぃ繧、 + if( 0 != (ret_code = crypto_rsa_enc_dec( rsa_pubkey, rsa_privkey, id_buf, id_buf)) ) { + switch( ret_code ) { + case CR_GENID_ERROR_RSA_ENC: + break; + case CR_GENID_ERROR_RSA_DEC: + break; + case CR_GENID_ERROR_RSA_VERIFY: + break; + } + goto end; + } +#else // Cygwin + + ret_code = hsm_crypto_rsa_enc_dec( id_buf, id_buf ); + if ( ret_code != 0 ) + { + printf( "error(%d) : hsm_crypto_aes_enc_dec\n", ret_code ); + } + +#endif // Linux + +#ifdef DEBUG_PRINT + if( cr_print_flag ) { + printf("RSA encrypted:"); + for( i = 0 ; i < CR_ID_BUF_SIZE ; i++ ) { + if( (i%16) == 0 ) { + printf("\n "); + } + printf("0x%02x ", id_buf[i] ); + } + printf("\n"); + } +#endif /* DEBUG_PRINT */ + +#else + //-------------------------------------------------------------- + // FuseID繝舌ャ繝輔ぃ蜈ィ菴薙rAES蜈ア騾夐嵯縺ァ證怜捷蛹 + //-------------------------------------------------------------- + // AES證怜捷蛹 -> 蠕ゥ蜿キ蛹 -> 繝吶Μ繝輔ぃ繧、 +#ifdef DEV_CYGWIN + if( 0 != (ret_code = crypto_aes_enc_dec( id_buf, id_buf )) ) + { + switch( ret_code ) + { + case CR_GENID_ERROR_RSA_ENC: + break; + case CR_GENID_ERROR_RSA_DEC: + break; + case CR_GENID_ERROR_RSA_VERIFY: + break; + } + goto end; + } +#else // DEV_CYGWIN(openssl) + ret_code = hsm_crypto_aes_enc_dec( id_buf, id_buf ); + if ( ret_code != 0 ) + { + printf( "error(%d) : hsm_crypto_aes_enc_dec\n", ret_code ); + } +#endif // HSM + +#ifdef DEBUG_PRINT + if( cr_print_flag ) { + printf("AES encrypted:"); + for( i = 0 ; i < CR_ID_BUF_SIZE ; i++ ) { + if( (i%16) == 0 ) { + printf("\n "); + } + printf("0x%02x ", id_buf[i] ); + } + printf("\n"); + } +#endif + +#endif // ENCRYPT_AES + + //-------------------------------------------------------------- + // 邨ゆコ蜃ヲ逅 + //-------------------------------------------------------------- + end: + /* id_buf[]縺ォ繧ィ繝ゥ繝シ繝ュ繧ー繧呈嶌縺崎セシ繧縲 */ + if( ret_code != 0 ) { + ERR_STATE *es = NULL; + CR_ERR_BUFFER *cr_err_buf = (CR_ERR_BUFFER *)id_buf; + memset( cr_err_buf, 0, sizeof(CR_ERR_BUFFER) ); + cr_err_buf->magic_number = 0x01234567; + cr_err_buf->serial0 = serial[0]; + cr_err_buf->openssl_err_code = ERR_get_error(); + es=ERR_get_state(); + cr_err_buf->top = es->top; + cr_err_buf->bottom = es->bottom; + for( i = 0 ; i < ERR_NUM_ERRORS ; i++ ) { + cr_err_buf->err_buffer[i] = es->err_buffer[i]; + cr_err_buf->err_line[i] = es->err_line[i]; + } + } + + // 繝ェ繧ス繝シ繧ケ縺ョ隗」謾セ + if ( my_eckey ) EC_KEY_free( my_eckey ); + if ( my_evppkey ) EVP_PKEY_free( my_evppkey ); + if ( req ) X509_REQ_free( req ); + if ( rsa_privkey ) RSA_free( rsa_privkey ); + if ( rsa_pubkey ) RSA_free( rsa_pubkey ); + + ERR_remove_state(0); + EVP_cleanup(); + CRYPTO_cleanup_all_ex_data(); + +#ifdef MY_CRYPTO_DEBUG + ERR_free_strings(); +#endif /* MY_CRYPTO_DEBUG */ + + return ret_code; /* success */ +} diff --git a/cr_generate_id.h b/cr_generate_id.h new file mode 100644 index 0000000..29970b8 --- /dev/null +++ b/cr_generate_id.h @@ -0,0 +1,188 @@ +/* ==================================================================== + * 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_ + + +#define CR_GENID_SUCCESS 0 +#define CR_GENID_ERROR_NON 0 +#define CR_GENID_ERROR_RSA_ENC ( -1) +#define CR_GENID_ERROR_RSA_DEC ( -2) +#define CR_GENID_ERROR_RSA_VERIFY ( -3) +#define CR_GENID_ERROR_ECDSA_SIGN ( -4) +#define CR_GENID_ERROR_ECDSA_VERIFY ( -5) +#define CR_GENID_ERROR_SET_MEM_FUNCTIONS ( -6) +#define CR_GENID_ERROR_RSA_LOAD_PARAM ( -7) +#define CR_GENID_ERROR_EC_GENERATE_PRIVATE_KEY ( -8) +#define CR_GENID_ERROR_EC_GENERATE_PUBLIC_KEY ( -9) +#define CR_GENID_ERROR_RSA_READ_PRIVATE_KEY (-10) +#define CR_GENID_ERROR_RSA_READ_PUBLIC_KEY (-11) +#define CR_GENID_ERROR_BN_NEW_0 (-12) +#define CR_GENID_ERROR_BN_NEW_1 (-13) +#define CR_GENID_ERROR_BN_NEW_2 (-14) +#define CR_GENID_ERROR_BN_CTX_NEW (-15) +#define CR_GENID_ERROR_EC_POINT_NEW (-16) +#define CR_GENID_ERROR_EC_KEY_NEW_0 (-17) +#define CR_GENID_ERROR_EC_KEY_NEW_1 (-18) +#define CR_GENID_ERROR_ID_BUF_SIZE (-19) +#define CR_GENID_ERROR_ERR_BUF_SIZE (-20) +#define CR_GENID_ERROR_PRIVKEY_SCRAMBLE (-21) + +#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 DEBUG_PRINT 1 + +#ifdef USE_SFMT +#include "SFMT.h" +#endif /* USE_SFMT */ + +#define CR_ID_BUF_SIZE (2048/8) +#define CR_NUM_OF_SERIAL 5 + +/* + serial と 実際のID との関係は、下記のようになっています。 + ID0 = serial[ 0 ] + ID1 = serial[ 1 ] | ( serial[ 2 ] << 32 ) + ID2 = serial[ 3 ] | ( serial[ 4 ] << 32 ) +*/ + +// Nintendo ID 仕様 +#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 + +int cr_generate_id_initialize( void ); +int cr_generate_id_finalize( void ); + +int cr_generate_id( u32 serial[CR_NUM_OF_SERIAL], u8 id[CR_ID_BUF_SIZE], u8 bondingOption ); + +extern int cr_print_flag; + +#ifdef __cplusplus +} +#endif + + +#endif /* _CR_GENERATE_ID_H_ */ + diff --git a/dummyCA/NintendoCA-G2_dummy.crt b/dummyCA/NintendoCA-G2_dummy.crt new file mode 100644 index 0000000..363096c --- /dev/null +++ b/dummyCA/NintendoCA-G2_dummy.crt @@ -0,0 +1,83 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 0 (0x0) + Signature Algorithm: sha1WithRSAEncryption + Issuer: C=US, ST=WA, O=NINTENDO_OF_AMERICA, OU=SYSTEM, CN=ALL-PLATFORM/emailAddress=admin@nintendo.co.jp + Validity + Not Before: Nov 19 08:58:03 2009 GMT + Not After : Nov 17 08:58:03 2019 GMT + Subject: C=US, ST=WA, O=NINTENDO_OF_AMERICA, OU=SYSTEM, CN=ALL-PLATFORM/emailAddress=admin@nintendo.co.jp + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:b7:b9:5f:4b:d5:c8:d6:9c:04:05:0c:d3:64:b9: + 94:75:1e:08:6e:71:ee:86:9b:95:05:09:57:d4:2a: + 40:41:1c:ce:b3:5d:f9:2f:29:ef:13:1e:a2:d0:11: + 67:18:cc:a2:69:dd:eb:ce:90:d7:48:8b:60:0a:b9: + eb:32:ae:03:38:de:dc:4a:a6:83:1d:54:0c:73:50: + 32:97:cb:72:1d:7d:07:a8:a4:3d:ed:a7:6e:91:01: + bc:f4:97:d9:ae:22:33:30:2b:05:d7:f4:a7:11:0c: + be:f5:e5:fb:81:b3:7c:d3:87:22:cd:85:2b:0e:fb: + 7f:1e:7a:c4:65:0c:1e:6a:27:c5:24:e4:2a:da:c7: + 64:b0:b7:1d:72:0d:1c:cd:d7:85:f2:74:3a:c1:ba: + 03:49:06:43:95:f8:c9:48:e8:0f:7c:ca:1a:c5:d7: + a3:22:75:ff:7f:29:91:b8:aa:65:30:d1:19:18:7e: + 08:e1:a0:4a:54:f0:bc:42:89:f6:7a:81:c5:83:c5: + 78:28:b1:d7:9c:7e:69:78:09:14:12:75:13:62:ef: + 4b:d9:76:e3:29:9a:6b:35:e4:53:b8:14:4f:8b:93: + 9c:7b:21:8e:f0:5a:04:b3:04:3f:6a:f0:96:1a:e2: + 99:42:51:e0:e5:6f:13:d0:f9:86:5e:80:c6:31:21: + 47:6f + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Basic Constraints: + CA:FALSE + Netscape Comment: + OpenSSL Generated Certificate + X509v3 Subject Key Identifier: + C7:3D:11:8F:6F:EB:10:5C:CE:C4:CE:04:79:BF:61:E9:70:E0:58:B2 + X509v3 Authority Key Identifier: + keyid:C7:3D:11:8F:6F:EB:10:5C:CE:C4:CE:04:79:BF:61:E9:70:E0:58:B2 + + Signature Algorithm: sha1WithRSAEncryption + 02:56:8e:4c:e2:bb:c7:2c:3a:16:ef:26:c7:11:fa:1c:a5:fc: + a8:a3:be:7a:0b:d7:e1:32:77:b9:c5:0a:1a:d8:74:6e:f6:42: + 3e:c2:ae:60:94:57:6a:d6:4d:56:cd:3e:82:21:4f:e1:53:95: + a0:83:e1:24:10:57:ac:89:53:6f:45:9e:85:04:a2:47:1f:e9: + 85:01:3b:8e:f5:77:ae:66:93:49:90:53:5f:12:10:c3:14:b9: + 9b:f3:b9:02:54:60:c6:da:48:db:a1:23:9b:ae:9d:42:30:96: + af:b5:b2:23:5a:e0:33:89:51:db:f1:6b:a8:10:57:d6:f9:5d: + fb:d9:ec:29:92:8a:3b:e8:6d:e2:ae:a6:8d:3c:a1:bd:09:92: + 3e:d2:05:e4:c0:54:b7:49:92:03:c8:4b:9b:d5:66:91:04:41: + dd:65:dd:32:b9:00:f7:54:0e:a0:71:74:33:30:76:4b:59:34: + 7d:58:59:c7:65:69:3b:72:91:8f:ba:1b:a2:8b:2e:d5:fe:b0: + 64:2d:f3:ae:ae:76:76:21:a1:c0:a3:53:a6:93:62:99:e2:22: + fc:80:aa:d2:a6:2f:6f:03:28:6d:01:66:40:7d:36:0e:05:ca: + 06:09:4b:6d:7a:42:a9:57:85:80:50:f1:21:cd:df:47:e2:49: + 73:9d:12:ca +-----BEGIN CERTIFICATE----- +MIIEAjCCAuqgAwIBAgIBADANBgkqhkiG9w0BAQUFADCBhTELMAkGA1UEBhMCVVMx +CzAJBgNVBAgMAldBMRwwGgYDVQQKDBNOSU5URU5ET19PRl9BTUVSSUNBMQ8wDQYD +VQQLDAZTWVNURU0xFTATBgNVBAMMDEFMTC1QTEFURk9STTEjMCEGCSqGSIb3DQEJ +ARYUYWRtaW5AbmludGVuZG8uY28uanAwHhcNMDkxMTE5MDg1ODAzWhcNMTkxMTE3 +MDg1ODAzWjCBhTELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAldBMRwwGgYDVQQKDBNO +SU5URU5ET19PRl9BTUVSSUNBMQ8wDQYDVQQLDAZTWVNURU0xFTATBgNVBAMMDEFM +TC1QTEFURk9STTEjMCEGCSqGSIb3DQEJARYUYWRtaW5AbmludGVuZG8uY28uanAw +ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC3uV9L1cjWnAQFDNNkuZR1 +Hghuce6Gm5UFCVfUKkBBHM6zXfkvKe8THqLQEWcYzKJp3evOkNdIi2AKuesyrgM4 +3txKpoMdVAxzUDKXy3IdfQeopD3tp26RAbz0l9muIjMwKwXX9KcRDL715fuBs3zT +hyLNhSsO+38eesRlDB5qJ8Uk5Crax2Swtx1yDRzN14XydDrBugNJBkOV+MlI6A98 +yhrF16Midf9/KZG4qmUw0RkYfgjhoEpU8LxCifZ6gcWDxXgosdecfml4CRQSdRNi +70vZduMpmms15FO4FE+Lk5x7IY7wWgSzBD9q8JYa4plCUeDlbxPQ+YZegMYxIUdv +AgMBAAGjezB5MAkGA1UdEwQCMAAwLAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2Vu +ZXJhdGVkIENlcnRpZmljYXRlMB0GA1UdDgQWBBTHPRGPb+sQXM7EzgR5v2HpcOBY +sjAfBgNVHSMEGDAWgBTHPRGPb+sQXM7EzgR5v2HpcOBYsjANBgkqhkiG9w0BAQUF +AAOCAQEAAlaOTOK7xyw6Fu8mxxH6HKX8qKO+egvX4TJ3ucUKGth0bvZCPsKuYJRX +atZNVs0+giFP4VOVoIPhJBBXrIlTb0WehQSiRx/phQE7jvV3rmaTSZBTXxIQwxS5 +m/O5AlRgxtpI26Ejm66dQjCWr7WyI1rgM4lR2/FrqBBX1vld+9nsKZKKO+ht4q6m +jTyhvQmSPtIF5MBUt0mSA8hLm9VmkQRB3WXdMrkA91QOoHF0MzB2S1k0fVhZx2Vp +O3KRj7oboosu1f6wZC3zrq52diGhwKNTppNimeIi/ICq0qYvbwMobQFmQH02DgXK +BglLbXpCqVeFgFDxIc3fR+JJc50Syg== +-----END CERTIFICATE----- diff --git a/dummyCA/NintendoCA-G2_dummy.csr b/dummyCA/NintendoCA-G2_dummy.csr new file mode 100644 index 0000000..4690f02 --- /dev/null +++ b/dummyCA/NintendoCA-G2_dummy.csr @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIC3TCCAcUCAQAwgZcxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJXQTEQMA4GA1UE +BwwHUkVETU9ORDEcMBoGA1UECgwTTklOVEVORE9fT0ZfQU1FUklDQTEPMA0GA1UE +CwwGU1lTVEVNMRUwEwYDVQQDDAxBTEwtUExBVEZPUk0xIzAhBgkqhkiG9w0BCQEW +FGFkbWluQG5pbnRlbmRvLmNvLmpwMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB +CgKCAQEAt7lfS9XI1pwEBQzTZLmUdR4IbnHuhpuVBQlX1CpAQRzOs135LynvEx6i +0BFnGMyiad3rzpDXSItgCrnrMq4DON7cSqaDHVQMc1Ayl8tyHX0HqKQ97adukQG8 +9JfZriIzMCsF1/SnEQy+9eX7gbN804cizYUrDvt/HnrEZQweaifFJOQq2sdksLcd +cg0czdeF8nQ6wboDSQZDlfjJSOgPfMoaxdejInX/fymRuKplMNEZGH4I4aBKVPC8 +Qon2eoHFg8V4KLHXnH5peAkUEnUTYu9L2XbjKZprNeRTuBRPi5OceyGO8FoEswQ/ +avCWGuKZQlHg5W8T0PmGXoDGMSFHbwIDAQABoAAwDQYJKoZIhvcNAQEFBQADggEB +ACz+sEe0XyW4NkDJvTEJbtPaIyL8PYcz7Iz6sAdwyoj67sZh/H1evyKPDDF6AHtp +Q+TMzGFUWxrv3Rwp2xHNi35T8jpCpvZNNtAQ7+v0/IHn1TPyIjxWcSh8qShR6OqE +LhBhs+5jumbJVw0D7R1CGc9n/hhjJyfVt1l4PSIYbMWkdPcl/3rXJtc/PQUzcLoH +jQZC8OlvZKH77SiJ5avdfq5co7By0Pw4ANNuw8hZnG8BuRed1/xo7ZsR4F63P0g3 +Hi2G9bNWR1eeORo1ouGQDg8RhCgKk39BDLIQWEqto6GwHYpolydzUKtWkHV7zEU1 +Gt3UGMqCqltOj8RIZKsIIF8= +-----END CERTIFICATE REQUEST----- diff --git a/dummyCA/NintendoCA-G2_priv_dummy.der b/dummyCA/NintendoCA-G2_priv_dummy.der new file mode 100644 index 0000000000000000000000000000000000000000..c3e8b4de50da6c90b280fc7dd4964caf3a194214 GIT binary patch literal 1191 zcmV;Y1X%kpf&`-i0RRGm0RaHFxnE1w$kv<$1q{<4*P!|dc=ns6#8pYS6B6a_NDUrCUWiZhh7=8%hph{Hmyh4fg zdV$4*#ds*O*PMQ7cnK5|brWLmOWAhgDVl3FSbwaCC8Zi<4pOOux>5H;r zvSj$}Pvj~AAkXe<+Smr|qFSuW!TzP}=X@HJ*UMUIc%ptk*$#^i*%)lt?#@%Tg)-0A)3P=%b|({tE9YwFHSBR6PZjMJdtWEiT!G->kif5pE6VODmqp2RP2!W`U+b1UbW*Czd-&SZP=7?;0d6~OV}>D>0Q zBnr0J1f2{OTZ!spK|Gj4&5f?CGMjkDM&-eD5u01I^uZBQO^o2UIfna1UL!WCDIBjL z^f`+?FvK*&BAX;(%Tyn1i%|NuvbD0S0)c>2hsJ!wA3uY3x(u8Fn1u?MuicRBv#NpPZh&yiW_{Lu3I>IhkFfok-xdK~`mbmoBN*M?@hhMI FY2aL(LdO6A literal 0 HcmV?d00001 diff --git a/dummyCA/NintendoCA-G2_priv_dummy.pem b/dummyCA/NintendoCA-G2_priv_dummy.pem new file mode 100644 index 0000000..8400eb6 --- /dev/null +++ b/dummyCA/NintendoCA-G2_priv_dummy.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAt7lfS9XI1pwEBQzTZLmUdR4IbnHuhpuVBQlX1CpAQRzOs135 +LynvEx6i0BFnGMyiad3rzpDXSItgCrnrMq4DON7cSqaDHVQMc1Ayl8tyHX0HqKQ9 +7adukQG89JfZriIzMCsF1/SnEQy+9eX7gbN804cizYUrDvt/HnrEZQweaifFJOQq +2sdksLcdcg0czdeF8nQ6wboDSQZDlfjJSOgPfMoaxdejInX/fymRuKplMNEZGH4I +4aBKVPC8Qon2eoHFg8V4KLHXnH5peAkUEnUTYu9L2XbjKZprNeRTuBRPi5OceyGO +8FoEswQ/avCWGuKZQlHg5W8T0PmGXoDGMSFHbwIDAQABAoIBAGgTLYWjDEtuQ+Ss +eE+1xQB3S+Vsyucb2VXqDgPVD2MTM5BuKotqINFe6HIfeZyVx2dbXIo+iIXC1lwd +J7wk0RR1QqtTGjER/J+SDabpi7JismT47U/kKgEgz+5q2tgG7aJarMvB/qXs53wa +lNfLWmnlQnTT/ClXlJIqj3iCXfRZrmzlwvO8U0kil0oe1jFAlgYAj/ktnsvQmK/t +Mli7zQdg2GYLouRSk1HexLkf9Hmf3pKJjmNL4Xx2WblaGGX+sGTOZP4d1Mwx1q3z +kEscTjxWiTh1YRjxY8gdf1W63w1H0+9eBxp7DfzwmEt6wBu/dsLaBwDDAmqdgyqY +nEc8yFkCgYEA7N8GJ1on2dYtDkVXrTHA9lOoj6es10F59FRydaRMm2FMY9m6lEg3 +jstSKf8AZTV+6KOlEf4K7ym1BIkdVD0FlkUp0d8tLtmF36y9qV8L0zUwaZAaR/Pi +xRZ6cP+Fr6KNYqB5O9iPb+z4cDQtwS9SYFLjP6ZU2Q0lUDoQZPyfnk0CgYEAxo+b +lRDLhADN0A+df8W/AWFWdrCexC9vwhzcinMr55nXJv2gzmR78BiXv2IVwPHg6dz2 +sSQKttgEnQwVW4nqY0E8mEPNja6sMpt4xkblwXQRm1u09MERUk2M4Lg5hvtFXiM2 +qSkcryD0OYs9MMQ0wyKbJGHLVB9si1D6trK1sqsCgYBTh8Z8xB8/g3a6DJwBmIUK +mK/dkOyzsARYtBr0/26AcMxmfdZ9CgaFlY+w/ZrfFgFd+q9wa9zhQBz0r4GnPiml +N1irCP+/ALhkC1+Kxdi+r4gWAdoyu3+hru6YwJMdP76KJDr8br8OYkuuDciA0rZC +/5fhzz8ml6sr4n37jtafFQKBgQCW7JUfivKGVW4a1aOreQ0j6W6lLL6g9EWIUBO6 +EKywj5igBGx0NKCX8Ll3OQC79Z41ZEUGhBS4wh1Pmd2qBHxqES4TtoXJSZmNper5 +Gu6MSsMPSXeUCiQ2YMfSD3V6igdB9JYZoiwxWWUJUDKknJ5WLDmsP8EjIfeJNXY7 +5D6DnQKBgDdiPyGUHRLQy7+hm5EYWVhc8L//ejtF73XHxeBao6V7QZvM6dLalqie +eY8bNy9nDUbk9dnL193VPbmH3ZcYkcKtkGuBRQsFcImCVkxcxtG110LMHbOcuVax +Bsh6Ia0hswVFY4mzKf6mpzo2oNHT7s8vaDtVCJkjGN3d8Suf/2ng +-----END RSA PRIVATE KEY----- diff --git a/dummyCA/NintendoCA-G2_pub_dummy.der b/dummyCA/NintendoCA-G2_pub_dummy.der new file mode 100644 index 0000000000000000000000000000000000000000..5367e1aa39bd3e9c16d65a80dab9dbe943e31fcb GIT binary patch literal 294 zcmV+>0ondAf&n5h4F(A+hDe6@4FLfG1potr0S^E$f&mHwf&l>lx4BaT@LB}31V3u zp+EyZ00aQp0sZAwVA(P=C6iMMx?`ghP?jxBa`Kwyp!;jT0lwD5jARj_Y}2f&F`D&f Rq=jeJlV=2r@SvV8B{lU3F&qE@ literal 0 HcmV?d00001 diff --git a/dummyCA/NintendoCTR2_priv_dummy.pem b/dummyCA/NintendoCTR2_priv_dummy.pem new file mode 100644 index 0000000..c41d4f7 --- /dev/null +++ b/dummyCA/NintendoCTR2_priv_dummy.pem @@ -0,0 +1,8 @@ +-----BEGIN EC PARAMETERS----- +BgUrgQQAGw== +-----END EC PARAMETERS----- +-----BEGIN EC PRIVATE KEY----- +MG0CAQEEHSPpFxKbsybBnzhicMZAWpTsdlB1u/Ca7PlXn9SZoAcGBSuBBAAboUAD +PgAEANkB/eVVYNkyMyWTUwq6Y6MUUJYtTHLymuag+2u/Ab7Ww4xkEaJs06yqMZr1 +Z6SFZ9aTZwSL8KCeLSU1 +-----END EC PRIVATE KEY----- diff --git a/dummyCA/NintendoCTR2_pub_dummy.der b/dummyCA/NintendoCTR2_pub_dummy.der new file mode 100644 index 0000000000000000000000000000000000000000..33399db87ad5747665e0009d049978a5710e7a6e GIT binary patch literal 84 zcmV-a0IUBnQZNt(2P%e0&OHJF1_djD1OOWYJ^%y&*#Z6KRbbgNGbNK#3c6#X6i}8e qOmgy?=Aip)zX871!;EARqHNQwsxg}NXQYK^){|!hi}0YHEhROjULouN literal 0 HcmV?d00001 diff --git a/dummyCA/NintendoCTR2_pub_dummy.pem b/dummyCA/NintendoCTR2_pub_dummy.pem new file mode 100644 index 0000000..589f57f --- /dev/null +++ b/dummyCA/NintendoCTR2_pub_dummy.pem @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFIwEAYHKoZIzj0CAQYFK4EEABsDPgAEANkB/eVVYNkyMyWTUwq6Y6MUUJYtTHLy +muag+2u/Ab7Ww4xkEaJs06yqMZr1Z6SFZ9aTZwSL8KCeLSU1 +-----END PUBLIC KEY----- diff --git a/dummyCA/Test_CTR-Device_dummy.crt b/dummyCA/Test_CTR-Device_dummy.crt new file mode 100644 index 0000000..91f9a0d --- /dev/null +++ b/dummyCA/Test_CTR-Device_dummy.crt @@ -0,0 +1,50 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 2 (0x2) + Signature Algorithm: ecdsa-with-SHA1 + Issuer: C=JP, ST=KYOTO, L=KYOTO, O=NINTENDO, OU=RED, CN=CTR/emailAddress=ctr_admin@nintendo.co.jp + Validity + Not Before: Nov 19 09:19:06 2009 GMT + Not After : Nov 17 09:19:06 2019 GMT + Subject: C=JP, ST=OKAYAMA, L=ODA, O=SHARP, OU=TAKAYA, CN=HSM/emailAddress=admin@sharp.co.jp + Subject Public Key Info: + Public Key Algorithm: id-ecPublicKey + Public-Key: (233 bit) + pub: + 04:01:b3:a1:96:8b:60:29:fe:b9:18:86:89:82:4c: + 92:d8:98:0d:d8:f3:8f:6a:68:8e:f5:93:f2:4f:5a: + d4:01:5a:02:86:1f:cd:e1:37:7b:1b:5e:47:b2:f9: + 8f:f5:85:a3:ae:e2:4a:51:28:22:2d:1a:82:6e:91: + 96 + ASN1 OID: sect233r1 + X509v3 extensions: + X509v3 Basic Constraints: + CA:FALSE + Netscape Comment: + OpenSSL Generated Certificate + X509v3 Subject Key Identifier: + 6F:90:5B:FE:66:6D:4D:4B:B1:6D:3F:CC:64:1A:26:BF:8F:5D:1D:1B + X509v3 Authority Key Identifier: + keyid:71:C3:EC:E7:2A:49:31:38:31:5B:7B:76:9D:2E:10:03:FE:19:78:4C + + Signature Algorithm: ecdsa-with-SHA1 + 30:3f:02:1d:2d:13:94:04:c0:cc:57:48:fe:73:b8:c0:25:88: + 92:9b:27:ec:ba:fc:cb:bd:e6:40:87:91:4d:7b:1f:02:1e:00: + 94:a0:7b:72:a0:72:e3:87:fd:3d:d1:9b:db:18:87:5b:54:24: + 3a:f5:48:7e:9c:86:ad:89:69:bf:fa +-----BEGIN CERTIFICATE----- +MIICXzCCAgygAwIBAgIBAjAJBgcqhkjOPQQBMIGFMQswCQYDVQQGEwJKUDEOMAwG +A1UECAwFS1lPVE8xDjAMBgNVBAcMBUtZT1RPMREwDwYDVQQKDAhOSU5URU5ETzEM +MAoGA1UECwwDUkVEMQwwCgYDVQQDDANDVFIxJzAlBgkqhkiG9w0BCQEWGGN0cl9h +ZG1pbkBuaW50ZW5kby5jby5qcDAeFw0wOTExMTkwOTE5MDZaFw0xOTExMTcwOTE5 +MDZaMH4xCzAJBgNVBAYTAkpQMRAwDgYDVQQIDAdPS0FZQU1BMQwwCgYDVQQHDANP +REExDjAMBgNVBAoMBVNIQVJQMQ8wDQYDVQQLDAZUQUtBWUExDDAKBgNVBAMMA0hT +TTEgMB4GCSqGSIb3DQEJARYRYWRtaW5Ac2hhcnAuY28uanAwUjAQBgcqhkjOPQIB +BgUrgQQAGwM+AAQBs6GWi2Ap/rkYhomCTJLYmA3Y849qaI71k/JPWtQBWgKGH83h +N3sbXkey+Y/1haOu4kpRKCItGoJukZajezB5MAkGA1UdEwQCMAAwLAYJYIZIAYb4 +QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1UdDgQWBBRv +kFv+Zm1NS7FtP8xkGia/j10dGzAfBgNVHSMEGDAWgBRxw+znKkkxODFbe3adLhAD +/hl4TDAJBgcqhkjOPQQBA0IAMD8CHS0TlATAzFdI/nO4wCWIkpsn7Lr8y73mQIeR +TXsfAh4AlKB7cqBy44f9PdGb2xiHW1QkOvVIfpyGrYlpv/o= +-----END CERTIFICATE----- diff --git a/dummyCA/Test_CTR-Device_dummy.csr b/dummyCA/Test_CTR-Device_dummy.csr new file mode 100644 index 0000000..29171dd --- /dev/null +++ b/dummyCA/Test_CTR-Device_dummy.csr @@ -0,0 +1,9 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIBKjCB2QIBADB+MQswCQYDVQQGEwJKUDEQMA4GA1UECAwHT0tBWUFNQTEMMAoG +A1UEBwwDT0RBMQ4wDAYDVQQKDAVTSEFSUDEPMA0GA1UECwwGVEFLQVlBMQwwCgYD +VQQDDANIU00xIDAeBgkqhkiG9w0BCQEWEWFkbWluQHNoYXJwLmNvLmpwMFIwEAYH +KoZIzj0CAQYFK4EEABsDPgAEAbOhlotgKf65GIaJgkyS2JgN2POPamiO9ZPyT1rU +AVoChh/N4Td7G15HsvmP9YWjruJKUSgiLRqCbpGWoAAwCQYHKoZIzj0EAQNBADA+ +Ah1hHULgGMJQ9thR6xIXnKnf7MRoL+8MM+7IiytapwIdE4cmzuPZRQ1TohuAI4zZ +seqaK/9grU1rWEcDZT0= +-----END CERTIFICATE REQUEST----- diff --git a/dummyCA/Test_CTR-Device_priv_dummy.der b/dummyCA/Test_CTR-Device_priv_dummy.der new file mode 100644 index 0000000000000000000000000000000000000000..bf50d4d43104cbdbdc77fd6088358ac23a9cbb7c GIT binary patch literal 111 zcmV-#0FeJMZ2|!S1Rdz8p2I~d^Rj!ET} zp+EyZ00aTEp_YqaDgL<_hKYhqlGvCH*z=ESXpZ%h@=sdS0a^lvAI;%6dmCOyviXno Rg`=+GN>L~xEgFJuk(L8TGbI23 literal 0 HcmV?d00001 diff --git a/dummyCA/Test_CTR-Device_priv_dummy.pem b/dummyCA/Test_CTR-Device_priv_dummy.pem new file mode 100644 index 0000000..f8d67dd --- /dev/null +++ b/dummyCA/Test_CTR-Device_priv_dummy.pem @@ -0,0 +1,8 @@ +-----BEGIN EC PARAMETERS----- +BgUrgQQAGw== +-----END EC PARAMETERS----- +-----BEGIN EC PRIVATE KEY----- +MG0CAQEEHeionsNFKvOye5ZdTN7DgNma1Hecm5/085LBPsdVoAcGBSuBBAAboUAD +PgAEAbOhlotgKf65GIaJgkyS2JgN2POPamiO9ZPyT1rUAVoChh/N4Td7G15HsvmP +9YWjruJKUSgiLRqCbpGW +-----END EC PRIVATE KEY----- diff --git a/dummyCA/Test_CTR-Device_pub_dummy.der b/dummyCA/Test_CTR-Device_pub_dummy.der new file mode 100644 index 0000000000000000000000000000000000000000..a00aad590d8c04c15f9f81d0a287af6dcd6965b5 GIT binary patch literal 84 zcmV-a0IUBnQZNt(2P%e0&OHJF1_djD1OOWYJ^%y(v!RxYU@88&7>0?0Op@4`4cPOK qYG{u2lk!hm)B#!oh9Ax0H+vgiN3!{k^@XFZ;!05{A}tz%ZjqMB&mpJ) literal 0 HcmV?d00001 diff --git a/dummyCA/Test_CTR-Device_pub_dummy.pem b/dummyCA/Test_CTR-Device_pub_dummy.pem new file mode 100644 index 0000000..6ee4d3a --- /dev/null +++ b/dummyCA/Test_CTR-Device_pub_dummy.pem @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFIwEAYHKoZIzj0CAQYFK4EEABsDPgAEAbOhlotgKf65GIaJgkyS2JgN2POPamiO +9ZPyT1rUAVoChh/N4Td7G15HsvmP9YWjruJKUSgiLRqCbpGW +-----END PUBLIC KEY----- diff --git a/main.c b/main.c new file mode 100644 index 0000000..8b5c075 --- /dev/null +++ b/main.c @@ -0,0 +1,455 @@ + +#define RAND_MAX 0xffffffff +#include +#include +#include + +#ifdef DEV_CYGWIN +#include +#else // Cygwin +#include +#include +#endif // Linux + +#include +#include + +#include + +#include "cr_generate_id.h" + +#define T_BONDING_OPTION 0 // TORIAEZU bondingOption = 0 + +// extern const int isDummyPrivateKey; + +/* + gen_id.exe 0x01 0x02 + gen_id.exe 0x01 0x02 ctrid090716.dat + gen_id.exe 0x01 0x03 ctrid090728.dat +*/ + +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 + +// 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[]) +{ + u32 serial[CR_NUM_OF_SERIAL]; + 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 + fprintf(stderr,"RSA private key is dummy!\n"); + return -1; /* error */ +#endif + + time(&tloc); + myseed = tloc; + srand(myseed); + +#ifdef USE_SFMT + init_gen_rand((u32)myseed); + /* 縺縺上i縺倶ケア謨ー繧定ェュ縺ソ謐ィ縺ヲ縺励◆譁ケ縺瑚憶縺シ */ +#endif + + // ID逕滓仙燕縺ォ繧ォ繧ヲ繝ウ繧ソ蜉邂励r縺吶k縺ェ繧峨∝晄悄蛟、縺ッ 0 縺ァ OK + counter0 = 0x00000000; + counter1 = 0x0000000000000000ll; + counter2 = 0x0000000000000000ll; + + // cr_generate_id 繧剃スソ逕ィ縺吶k蜑阪↓蜻シ縺ウ蜃コ縺 + if ( !cr_generate_id_initialize() ) + { + 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 { +#ifdef USE_SFMT + unit = (u64)gen_rand32(); +#else + unit = (u64)rand() | ( (u64)rand() << 16 ); +#endif + }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 ); + } + + serial[0] = counter0; + serial[1] = (u32)(counter1 & 0xffffffff); + serial[2] = (u32)((counter1 >> 32) & 0xffffffff); + serial[3] = (u32)(counter2 & 0xffffffff); + serial[4] = (u32)((counter2 >> 32) & 0xffffffff); + + + time_start = gettimeofday_sec(); + ret_code = cr_generate_id( serial, id, T_BONDING_OPTION ); + if( ret_code != 0 ) { + fprintf(stderr,"generate_id failed\n"); + switch( ret_code ) { + case CR_GENID_ERROR_ID_BUF_SIZE: + fprintf(stderr,"failed to CR_ID_BUFFER structure size\n"); + break; + case CR_GENID_ERROR_ERR_BUF_SIZE: + fprintf(stderr,"failed to CR_ERR_BUFFER structure size\n"); + break; + case CR_GENID_ERROR_RSA_ENC: + fprintf(stderr,"failed to RSA_public_encrypt\n"); + fprintf(stderr," internal errcode=0x%02x%02x%02x%02x\n", id[11],id[10],id[9],id[8]); + break; + case CR_GENID_ERROR_RSA_DEC: + fprintf(stderr,"failed to RSA_private_decrypt\n"); + fprintf(stderr," internal errcode=0x%02x%02x%02x%02x\n", id[11],id[10],id[9],id[8]); + break; + case CR_GENID_ERROR_RSA_VERIFY: + fprintf(stderr,"RSA verify failed\n"); + fprintf(stderr," internal errcode=0x%02x%02x%02x%02x\n", id[11],id[10],id[9],id[8]); + break; + case CR_GENID_ERROR_ECDSA_SIGN: + fprintf(stderr,"ECDSA sign failure. No ECDSA sign will be done.\n"); + fprintf(stderr," internal errcode=0x%02x%02x%02x%02x\n", id[11],id[10],id[9],id[8]); + break; + case CR_GENID_ERROR_ECDSA_VERIFY: + fprintf(stderr,"ECDSA_verify NG.\n"); + fprintf(stderr," internal errcode=0x%02x%02x%02x%02x\n", id[11],id[10],id[9],id[8]); + break; + case CR_GENID_ERROR_SET_MEM_FUNCTIONS: + fprintf(stderr,"CRYPTO_set_mem_functions error \n"); + fprintf(stderr," internal errcode=0x%02x%02x%02x%02x\n", id[11],id[10],id[9],id[8]); + break; + case CR_GENID_ERROR_RSA_LOAD_PARAM: + fprintf(stderr,"load rsa param failed\n"); + fprintf(stderr," internal errcode=0x%02x%02x%02x%02x\n", id[11],id[10],id[9],id[8]); + break; + case CR_GENID_ERROR_EC_GENERATE_PRIVATE_KEY: + fprintf(stderr,"error EC generate_private_key\n"); + fprintf(stderr," internal errcode=0x%02x%02x%02x%02x\n", id[11],id[10],id[9],id[8]); + break; + case CR_GENID_ERROR_EC_GENERATE_PUBLIC_KEY: + fprintf(stderr,"error EC generate_public_key\n"); + fprintf(stderr," internal errcode=0x%02x%02x%02x%02x\n", id[11],id[10],id[9],id[8]); + break; + case CR_GENID_ERROR_RSA_READ_PRIVATE_KEY: + fprintf(stderr,"error RSA read private key\n"); + fprintf(stderr," internal errcode=0x%02x%02x%02x%02x\n", id[11],id[10],id[9],id[8]); + break; + case CR_GENID_ERROR_RSA_READ_PUBLIC_KEY: + fprintf(stderr,"error RSA read public key\n"); + fprintf(stderr," internal errcode=0x%02x%02x%02x%02x\n", id[11],id[10],id[9],id[8]); + break; + case CR_GENID_ERROR_BN_NEW_0: + fprintf(stderr,"error bn_new 0\n"); + fprintf(stderr," internal errcode=0x%02x%02x%02x%02x\n", id[11],id[10],id[9],id[8]); + break; + case CR_GENID_ERROR_BN_NEW_1: + fprintf(stderr,"error bn_new 1\n"); + fprintf(stderr," internal errcode=0x%02x%02x%02x%02x\n", id[11],id[10],id[9],id[8]); + break; + case CR_GENID_ERROR_BN_NEW_2: + fprintf(stderr,"error bn_new 2\n"); + fprintf(stderr," internal errcode=0x%02x%02x%02x%02x\n", id[11],id[10],id[9],id[8]); + break; + case CR_GENID_ERROR_BN_CTX_NEW: + fprintf(stderr,"error bn_ctx_new\n"); + fprintf(stderr," internal errcode=0x%02x%02x%02x%02x\n", id[11],id[10],id[9],id[8]); + break; + case CR_GENID_ERROR_EC_POINT_NEW: + fprintf(stderr,"error ec_point_new\n"); + fprintf(stderr," internal errcode=0x%02x%02x%02x%02x\n", id[11],id[10],id[9],id[8]); + break; + case CR_GENID_ERROR_EC_KEY_NEW_0: + fprintf(stderr,"error EC_KEY_new_by_curve_name 0\n"); + fprintf(stderr," internal errcode=0x%02x%02x%02x%02x\n", id[11],id[10],id[9],id[8]); + break; + case CR_GENID_ERROR_EC_KEY_NEW_1: + fprintf(stderr,"error EC_KEY_new_by_curve_name 1\n"); + fprintf(stderr," internal errcode=0x%02x%02x%02x%02x\n", id[11],id[10],id[9],id[8]); + break; + case CR_GENID_ERROR_PRIVKEY_SCRAMBLE: + fprintf(stderr,"failed to decode privkey scramble.\n"); + break; + default: + fprintf(stderr,"error unknown error ret_code=%d\n", ret_code); + fprintf(stderr," internal errcode=0x%02x%02x%02x%02x\n", id[11],id[10],id[9],id[8]); + break; + } + } + 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)serial[0]); + printf("ID[1] = 0x%08x%08x\n", (unsigned int)serial[2], (unsigned int)serial[1] ); + printf("ID[2] = 0x%08x%08x\n", (unsigned int)serial[4], (unsigned int)serial[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(&serial[0], argv[1]) && 0 == str_to_u32(&serial[1], argv[2]) ) { + printf("ID[0] = 0x%08x\n", (unsigned int)serial[0]); + printf("ID[1] = 0x%08x%08x\n", (unsigned int)serial[2], (unsigned int)serial[1] ); + printf("ID[2] = 0x%08x%08x\n", (unsigned int)serial[4], (unsigned int)serial[3] ); + + time_start = gettimeofday_sec(); + cr_print_flag = 1; + if( 0 != cr_generate_id( serial, id, T_BONDING_OPTION ) ) + { + fprintf(stderr,"cr_generate_id failed s1=0x%08x s2_lo=0x%08x s2_hi=0x%08x\n", + (int)serial[0], (int)serial[1], (int)serial[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(&serial[0], argv[1]) && 0 == str_to_u32(&serial[1], argv[2]) ) { + printf("ID[0] = 0x%08x\n", (unsigned int)serial[0]); + printf("ID[1] = 0x%08x%08x\n", (unsigned int)serial[2], (unsigned int)serial[1] ); + printf("ID[2] = 0x%08x%08x\n", (unsigned int)serial[4], (unsigned int)serial[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( serial, id, T_BONDING_OPTION ) ) + { + fprintf(stderr,"cr_generate_id failed s1=0x%08x s2_lo=0x%08x s2_hi=0x%08x\n", + (int)serial[0], (int)serial[1], (int)serial[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 SerialNo.(32bit) filename.dat\n", argv[0]); + + } + +end: + // cr_generate_id 繧剃スソ逕ィ縺励◆蠕後↓蜻シ縺ウ蜃コ縺 + if ( !cr_generate_id_finalize() ) + { + 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/package.csh b/package.csh new file mode 100644 index 0000000..9d5fd4f --- /dev/null +++ b/package.csh @@ -0,0 +1,29 @@ +#!c:/tcsh/tcsh.exe + +set mydir="cr_generate_id" + +#../rsa_keysrcgen/gen_id_rsa_key.c + +set myfiles="main.c cr_generate_id.c cr_generate_id.h cr_alloc.c cr_alloc.h cr_gen_id_rsa_key_priv.c cr_gen_id_rsa_key_pub.c cr_gen_id_rsa_key_priv.h cr_gen_id_rsa_key_pub.h Makefile.sharp readme_openssl.txt LICENSE_en.txt LICENSE_jp.txt readme.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/package.sh b/package.sh new file mode 100644 index 0000000..f591787 --- /dev/null +++ b/package.sh @@ -0,0 +1,34 @@ +#!/usr/bin/sh + +mydir="generate_id" +echo $mydir + +#../rsa_keysrcgen/gen_id_rsa_key.c + +myfiles="main.c cr_generate_id.c cr_generate_id.h cr_alloc.c cr_alloc.h cr_gen_id_rsa_key_priv.c cr_gen_id_rsa_key_pub.c cr_gen_id_rsa_key_priv.h cr_gen_id_rsa_key_pub.h Makefile.sharp readme_openssl.txt LICENSE_en.txt LICENSE_jp.txt readme.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/readme.txt b/readme.txt new file mode 100644 index 0000000..fd006a8 --- /dev/null +++ b/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/readme_openssl.txt b/readme_openssl.txt new file mode 100644 index 0000000..866bb14 --- /dev/null +++ b/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/tools/bin2c.plx b/tools/bin2c.plx new file mode 100644 index 0000000..cde1a5b --- /dev/null +++ b/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] ) { + die "parameter error.\n"; +} + +$_ = "cr_" . basename($srcfname, ""); +s/(\..*)/\.c/; +$dstfname_c = $_; +s/(\..*)/\.h/; +$dstfname_h = $_; +s/(\..*)/_DER/; +$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 ); + +# 配列サイズを + magic_code(8) + keyLen(2) + padding(6) し、16bytesでROUNDUP +my $array_size = ( $size + 16 + 15) & 0xfffffff0; + +# .c ファイルに変換して出力 + +printf DST "#include \n\n"; +printf DST "\/\/下記配列は、DERフォーマットの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; +