RootCAの名称変更によるバージョンアップ

リリースバージョン4


git-svn-id: file:///Volumes/Transfer/gigaleak_20231201/2020-09-30%20-%20paladin.7z/paladin/ctr_eFuse@197 ff987cc8-cf2f-4642-8568-d52cce064691
This commit is contained in:
kubodera_yuichi 2010-02-01 11:02:49 +00:00
parent 161d102c76
commit f81fb7b405
59 changed files with 8952 additions and 0 deletions

View File

@ -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.]
*/

View File

@ -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 も含む) に含めることもできません。

View File

@ -0,0 +1,224 @@
# nm ntd_mem_allocator.o | grep " [T|B|D] "
# nm ntd_crypto_ecdsa.o | grep " [T|B|D] "
# nm ntd_crypto_rsa.o | grep " [T|B|D] "
# nm generate_id.o | grep " [T|B|D] "
# nm ../rsa_keysrcgen/rsa1_key.o | grep " [T|B|D] "
# 最終的なビルドスイッチの設定は、以下の通り。
# DEV_CYGWIN = FALSE
# DEBUG_PRINT = FALSE
# DEBUG_OUTPUT = FALSE
# ECDSA_SHA256 = TRUE
# USE_HSM = TRUE
# RESET_HSM = TRUE
DEV_CYGWIN = FALSE
DEBUG_PRINT = FALSE
DEBUG_OUTPUT = FALSE
ECDSA_SHA256 = TRUE
USE_HSM = TRUE
RESET_HSM = TRUE
ifeq ($(USE_HSM),TRUE)
# HSM使用時は強制的にDUMMY_KEYは未使用にする。
USE_DUMMY_KEY = FALSE
# nFast Path
NFAST_PATH = /opt/nfast
# nFast Developer tools installation
NFAST_DEV_PATH = $(NFAST_PATH)/c/ctd/gcc
NFAST_EXAMPLES = $(NFAST_PATH)/c/ctd/examples
# nFast Developer tools library
NFAST_LIBPATH = $(NFAST_DEV_PATH)/lib
# nFast Developer tools include
NFAST_INC = $(NFAST_DEV_PATH)/include
# nFast CPPFLAGS
NFAST_CPPFLAGS = \
-I$(NFAST_INC)/sworld \
-I$(NFAST_INC)/hilibs \
-I$(NFAST_INC)/nflog \
-I$(NFAST_INC)/cutils \
-I$(NFAST_EXAMPLES)/sworld \
-I$(NFAST_EXAMPLES)/hilibs \
-I$(NFAST_EXAMPLES)/nflog \
-I$(NFAST_EXAMPLES)/cutils \
# nFast LDLIBS
NFAST_LDLIBS = \
$(NFAST_LIBPATH)/libnfkm.a \
$(NFAST_LIBPATH)/libnfstub.a \
$(NFAST_LIBPATH)/libnflog.a \
$(NFAST_LIBPATH)/libcutils.a \
else # !USE_HSM
# HSMが使用できない場合は、DUMMY_KEYを使ってテストする。
USE_DUMMY_KEY = TRUE
endif # USE_HSM
ifeq ($(USE_DUMMY_KEY),TRUE)
DEV_DER_KEY_DIR = ./dummyKey/dev
PROD_DER_KEY_DIR = ./dummyKey/prod
else # !USE_DUMMY_KEY
DEV_DER_KEY_DIR = ./realKey/dev
PROD_DER_KEY_DIR = ./realKey/prod
endif # USE_DUMMY_KEY
PACKAGE_DIR = ./package
OPENSSL_DIR = ./openssl-1.0.0-beta5
# OPENSSL_DIR = ./openssl-0.9.8k
TARGET_LIB = libgenid.a
TARGET = gen_id
KEYS_C = cr_eFuse_iv_prod.c \
cr_eFuse_iv_dev.c \
cr_NCT2_pub_prod.c \
cr_NCT2_pub_dev.c
ifeq ($(USE_DUMMY_KEY),TRUE)
KEYS_C += cr_eFuse_privKey_prod.c cr_eFuse_pubKey_prod.c \
cr_eFuse_privKey_dev.c cr_eFuse_pubKey_dev.c \
cr_eFuse_aesKey_prod.c \
cr_eFuse_aesKey_dev.c \
cr_NCT2_priv_prod.c \
cr_NCT2_priv_dev.c
endif # USE_DUMMY_KEY
SRCS = main.c
OBJS = $(notdir $(SRCS:.c=.o))
LIB_SRCS = cr_generate_id.c cr_id_util.c cr_keyPair.c \
cr_device_cert.c cr_enc_id.c cr_alloc.c \
cr_hsm_code.c cr_hsm_alloc.c cr_hsm_bignum.c
LIB_OBJS = $(notdir $(LIB_SRCS:.c=.o))
CFLAGS = -Wall -DMEXP=216091 -msse2 -DHAVE_SSE2
CPPFLAGS= -I. -I$(OPENSSL_DIR)/include -I$(OPENSSL_DIR)/crypto/ec
LDFLAGS = -mwindows -L$(OPENSSL_DIR)
LDLIBS = -lcrypto -lssl
MERGE_PROG = merge_lib_objs.plx
ifeq ($(DEV_CYGWIN),TRUE)
CC := C:/Cygwin/bin/gcc
LD = C:/Cygwin/bin/gcc
CFLAGS += -mno-cygwin -DDEV_CYGWIN
LDFLAGS += -Wl,--subsystem,console -mno-cygwin
TARGET_DEL = $(TARGET).exe
else # DEV_CYGWIN
CC := /usr/bin/gcc
LD = /usr/bin/gcc
LDFLAGS += -Wl
LDLIBS += -ldl -lnsl
TARGET_DEL = $(TARGET)
endif # DEV_CYGWIN
ifeq ($(USE_DUMMY_KEY),TRUE)
CFLAGS += -DUSE_DUMMY_KEY
endif
ifeq ($(DEBUG_PRINT),TRUE)
CFLAGS += -DDEBUG_PRINT
endif
ifeq ($(DEBUG_OUTPUT),TRUE)
CFLAGS += -DDEBUG_OUTPUT_FILE
endif
ifeq ($(ECDSA_SHA256),TRUE)
CFLAGS += -DECDSA_SHA256
endif
ifeq ($(USE_HSM),TRUE)
CFLAGS += -DUSE_HSM
CPPFLAGS+= $(NFAST_CPPFLAGS)
LDLIBS += $(NFAST_LDLIBS)
MERGE_PROG = merge_lib_objs_hsm.plx
endif
ifeq ($(RESET_HSM),TRUE)
CFLAGS += -DRESET_HSM
endif
.SUFFIXES:
all: package_build $(KEYS_C) $(TARGET_LIB) $(TARGET)
# install: $(TARGET)
# install -c -m 777 $(TARGET) ../bin
ifeq ($(DEV_CYGWIN),TRUE)
package_build :
cd $(PACKAGE_DIR);make DEV_CYGWIN=TRUE
else
package_build :
cd $(PACKAGE_DIR);make
endif
$(TARGET): $(OBJS) $(TARGET_LIB)
$(LD) $(LDFLAGS) $(OBJS) -o $@ $(TARGET_LIB)
$(TARGET_LIB): $(LIB_OBJS)
ar rcs $@ $(LIB_OBJS)
perl tools/$(MERGE_PROG)
%.o:%.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@
#%.c:$(DER_KEY_DIR)/%.der
# perl tools/bin2c.plx $<
cr_eFuse_privKey_prod.c : $(PROD_DER_KEY_DIR)/eFuse_privKey.der
perl tools/bin2c.plx $< prod
cr_eFuse_pubKey_prod.c : $(PROD_DER_KEY_DIR)/eFuse_pubKey.der
perl tools/bin2c.plx $< prod
cr_eFuse_aesKey_prod.c : $(PROD_DER_KEY_DIR)/eFuse_aesKey.bin
perl tools/bin2c.plx $< prod
cr_eFuse_iv_prod.c : $(PROD_DER_KEY_DIR)/eFuse_iv.bin
perl tools/bin2c.plx $< prod
cr_NCT2_priv_prod.c : $(PROD_DER_KEY_DIR)/NCT2_priv.der
perl tools/bin2c.plx $< prod
cr_NCT2_pub_prod.c : $(PROD_DER_KEY_DIR)/NCT2_pub.der
perl tools/bin2c.plx $< prod
cr_eFuse_privKey_dev.c : $(DEV_DER_KEY_DIR)/eFuse_privKey.der
perl tools/bin2c.plx $< dev
cr_eFuse_pubKey_dev.c : $(DEV_DER_KEY_DIR)/eFuse_pubKey.der
perl tools/bin2c.plx $< dev
cr_eFuse_aesKey_dev.c : $(DEV_DER_KEY_DIR)/eFuse_aesKey.bin
perl tools/bin2c.plx $< dev
cr_eFuse_iv_dev.c : $(DEV_DER_KEY_DIR)/eFuse_iv.bin
perl tools/bin2c.plx $< dev
cr_NCT2_priv_dev.c : $(DEV_DER_KEY_DIR)/NCT2_priv.der
perl tools/bin2c.plx $< dev
cr_NCT2_pub_dev.c : $(DEV_DER_KEY_DIR)/NCT2_pub.der
perl tools/bin2c.plx $< dev
.PHONY: clean clobber
clean:
$(RM) $(LIB_OBJS) $(OBJS) $(TARGET_DEL) $(TARGET_LIB) $(KEYS_C) $(KEYS_H)
clobber:
$(RM) $(LIB_OBJS) $(OBJS) $(TARGET_DEL) $(TARGET_LIB) $(KEYS_C) $(KEYS_H)
cd $(PACKAGE_DIR);make clobber

View File

@ -0,0 +1,44 @@
# Linux 上でビルドする場合は、DEV_CYGWINをコメントアウトしてください。
#DEV_CYGWIN = TRUE
TARGET = gen_id
SRCS = main.c
OBJS = $(notdir $(SRCS:.c=.o))
ifeq ($(DEV_CYGWIN),TRUE)
CC := C:/Cygwin/bin/gcc
LD = C:/Cygwin/bin/gcc
CFLAGS += -mno-cygwin -DDEV_CYGWIN -Wall -I./
LDFLAGS += -Wl,--subsystem,console -mwindows -mno-cygwin -L./
LDLIBS += -lgenid
TARGET_DEL = $(TARGET).exe
else # DEV_CYGWIN
CC := /usr/bin/gcc
LD = /usr/bin/gcc
LDFLAGS += -Wl -L./
LDLIBS += -ldl -lnsl -lgenid
TARGET_DEL = $(TARGET)
endif # DEV_CYGWIN
.SUFFIXES:
all: $(TARGET)
$(TARGET): $(OBJS)
$(LD) $(LDFLAGS) $(OBJS) -o $@ $(LDLIBS)
%.o:%.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@
.PHONY: clean clobber
clean clobber:
$(RM) $(OBJS) $(TARGET_DEL)

View File

@ -0,0 +1,27 @@
#!c:/tcsh/tcsh.exe
set mydir="cr_generate_id"
set myfiles="Makefile.sharp main.c cr_generate_id.h libgenid.a readme_openssl.txt LICENSE_en.txt LICENSE_jp.txt readme.txt readme_openssl.txt"
if(-e $mydir.zip) then
rm -f $mydir.zip
endif
if(-d $mydir ) then
rm -rf $mydir
endif
mkdir $mydir
foreach myfile ($myfiles)
if(-e $mydir/$myfile) then
rm -f $mydir/$myfile
endif
cp $myfile $mydir/$myfile
end
mv $mydir/Makefile.sharp $mydir/Makefile
zip $mydir.zip $mydir/*

View File

@ -0,0 +1,32 @@
#!/usr/bin/sh
mydir="generate_id"
echo $mydir
myfiles="Makefile.sharp main.c cr_generate_id.h libgenid.a readme_openssl.txt LICENSE_en.txt LICENSE_jp.txt readme.txt readme_openssl.txt"
if [ -e mydir.zip ]
then
rm -f $mydir.zip
fi
if [ -e $mydir ]
then
rm -rf $mydir
fi
mkdir $mydir
for myfile in $myfiles
do
if [ -e $mydir/$myfile ]
then
rm -f $mydir/$myfile
fi
cp $myfile $mydir/$myfile
done
mv $mydir/Makefile.sharp $mydir/Makefile
zip $mydir.zip $mydir/*

View File

@ -0,0 +1,477 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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;
}

View File

@ -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_ */

View File

@ -0,0 +1,453 @@
/* ====================================================================
* Copyright (c) 1998-2008 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <time.h>
#include <sys/time.h>
#include <string.h>
#ifdef USE_HSM
#include "cr_hsm_code.h"
#include "cr_hsm_bignum.h"
// for develop
#include <openssl/sha.h>
#include <openssl/ec.h>
#include <openssl/ecdsa.h>
#else
// openssl
#include <openssl/sha.h>
#include <openssl/ec.h>
#include <openssl/ecdsa.h>
#include "cr_NCT2_priv_dev.c"
#include "cr_NCT2_priv_prod.c"
#endif // USE_HSM
#include "cr_NCT2_pub_dev.c"
#include "cr_NCT2_pub_prod.c"
#include "cr_generate_id.h"
#include "cr_generate_id_private.h"
#define CR_CERT_EXPIRE_SECS ( 60*60*24*365* 20 ) // デバイス証明書期限 20年 ※うるう年は無視
u8 tempSign[ 70 ];
// TWL device cert base
typedef struct CR_DeviceCert
{
u8 sigType [ 4 ]; // 0x000 - 0x003 : 0x00010005, signature type is ECDSA + SHA256
u8 eccSignature[ 60 ]; // 0x004 - 0x03F : ECDSA using SHA-256 and CA key
u8 padding0 [ 64 ]; // 0x040 - 0x07F : zero-filled
u8 issuerName [ 64 ]; // 0x080 - 0x0BF : issuer name, "Root-CA00000002-MS00000008"
u8 keyType [ 4 ]; // 0x0C0 - 0x0C3 : 0x00000002, cert public key type is ECC233
u8 subject [ 64 ]; // 0x0C4 - 0x103 : subject field, "CTxxxxxxxx-yy"
u32 expiryDate; // 0x104 - 0x107 : second from Epoch (Jan 1, 1970 00:00)
u8 eccPubKey [ 60 ]; // 0x108 - 0x143 : cert public key (openssl sect233r1)
u8 padding1 [ 60 ]; // 0x144 - 0x17F : zero-filled
} CR_DeviceCert;
const u8 issuerName[] = {
0x14, 0x33, 0x34, 0x2E, 0x3F, 0x34, 0x3E, 0x35,
0x7A, 0x19, 0x1B, 0x7A, 0x77, 0x7A, 0x1D, 0x69,
0x05, 0x14, 0x33, 0x34, 0x2E, 0x3F, 0x34, 0x3E,
0x35, 0x19, 0x0E, 0x08,
};
static void BN2BinWithPadding( BIGNUM *pBn, u8 *pDst, int dstLen );
// create CTR Device cert
int GenerateCTRDeviceCert( EC_KEY *pECkey, u32 device_id, u8 bonding_option, u8 *pDevCertSign, u32 *pExpiryDate )
{
int ret_code = CR_GENID_SUCCESS;
CR_DeviceCert deviceCert;
EC_KEY *NCT2 = NULL;
int i;
#ifdef DEBUG_PRINT
if ( sizeof( CR_DeviceCert ) > 384 )
{
printf( "CR_DeviceCert size error. %d\n", sizeof(CR_DeviceCert) );
}
#endif
memset( &deviceCert, 0, sizeof(deviceCert) );
// sigType
// ECDSA+SHA256 = 0x00010005, ECDSA+SHA1 = 0x00010002
deviceCert.sigType[0] = 0x00;
deviceCert.sigType[1] = 0x01;
deviceCert.sigType[2] = 0x00;
#ifdef ECDSA_SHA256
deviceCert.sigType[3] = 0x05;
#else // !ECDSA_SHA256
deviceCert.sigType[3] = 0x02;
#endif // ECDSA_SHA256
// issuerName
for( i = 0; i < sizeof(issuerName); i++ ) {
deviceCert.issuerName[ i ] = issuerName[ i ] ^ 0x5a;
}
sprintf( &deviceCert.issuerName[ sizeof(issuerName) ], "%s", bonding_option ? "dev" : "prod" );
// keyType 0x00000002 ECC233
deviceCert.keyType[0] = 0x00;
deviceCert.keyType[1] = 0x00;
deviceCert.keyType[2] = 0x00;
deviceCert.keyType[3] = 0x02;
// subject : CT + device_id + bonding_option
sprintf( deviceCert.subject, "CT%08X-%02X", (unsigned int)device_id, bonding_option );
// expiryDate +20years
*pExpiryDate += CR_CERT_EXPIRE_SECS; // ID_BUFにも証明書期限をセットする。
deviceCert.expiryDate = *pExpiryDate;
// eccPubKey
BN2BinWithPadding( &pECkey->pub_key->X, &deviceCert.eccPubKey[ 0 ], 30 );
BN2BinWithPadding( &pECkey->pub_key->Y, &deviceCert.eccPubKey[ 30 ], 30 );
#if 0
DEBUG_PRINT_ARRAY( "eccPubKey:", (const char *)deviceCert.eccPubKey, 60 );
DEBUG_PRINT_ARRAY( "eccPubKey.X:", (const char *)pECkey->pub_key->X.d, pECkey->pub_key->X.dmax * 4 );
DEBUG_PRINT_ARRAY( "eccPubKey.Y:", (const char *)pECkey->pub_key->Y.d, pECkey->pub_key->Y.dmax * 4 );
#endif
// eccSignature
#ifdef USE_HSM
// ECDSA署名付加
#ifdef ECDSA_SHA256
u8 sha256Buf[ SHA256_DIGEST_LENGTH ];
u8 modifyHash[ SHA256_DIGEST_LENGTH ];
// CR_DeviceCertのSHA256計算
SHA256( deviceCert.issuerName, (int)&deviceCert + sizeof(CR_DeviceCert) - (int)deviceCert.issuerName, sha256Buf );
DEBUG_PRINT_ARRAY( "sha256(HSM)", (const char *)sha256Buf, 32 );
// HSM は切り詰めないで署名してしまうので自前で加工する
memset( modifyHash, 0, sizeof( modifyHash ) );
modifyHash[2] = sha256Buf[0] >> 7;
for( i = 3; i < SHA256_DIGEST_LENGTH; i++ )
modifyHash[i] = (sha256Buf[i-3] << 1) | (sha256Buf[i-2] >> 7);
ret_code = hsm_ecdsa_sign( deviceCert.eccSignature, modifyHash, bonding_option );
#else // !ECDSA_SHA256
u8 sha1Buf[ 20 ];
SHA1( deviceCert.issuerName, (int)&deviceCert + sizeof(CR_DeviceCert) - (int)deviceCert.issuerName, sha1Buf );
DEBUG_PRINT_ARRAY( "sha1(HSM)", (const char *)sha1Buf, 20 );
ret_code = hsm_ecdsa_sign( deviceCert.eccSignature, sha1Buf, bonding_option );
#endif // ECDSA_SHA256
if ( ret_code != CR_GENID_SUCCESS )
{
SetErrorInfo( __FUNCTION__, __LINE__ );
return ret_code;
}
memcpy( pDevCertSign, &deviceCert.eccSignature, 60 );
#else // !USE_HSM
// DERフォーマットのECC鍵を読み込み
{
// bonding_option によって、鍵を差し替え
const unsigned char *der_priv = bonding_option ? cr_NCT2_priv_dev : cr_NCT2_priv_prod;
int priv_len = der_priv[ 8 ] | der_priv[ 9 ] << 8; // KEY長を取り出し
der_priv += 0x10; // ヘッダ部分を除外してKEY実体を指定
// ECCは、秘密鍵のみで公開鍵成分もセットされるようなので、公開鍵は読み込まない。
NCT2 = d2i_ECPrivateKey( NULL, &der_priv, priv_len );
if( NCT2 == NULL ) {
ret_code = CR_GENID_ERROR_ECC_READ_PRIVATE_KEY;
goto end;
}
#if 0
DEBUG_PRINT_ARRAY( "EC priv:", (const char *)NCT2->priv_key->d, NCT2->priv_key->dmax * 4);
DEBUG_PRINT_ARRAY( "EC pub.X:", (const char *)NCT2->pub_key->X.d, NCT2->pub_key->X.dmax * 4 );
DEBUG_PRINT_ARRAY( "EC pub.Y:", (const char *)NCT2->pub_key->Y.d, NCT2->pub_key->Y.dmax * 4 );
#endif
}
// ECDSA署名付加
#ifdef ECDSA_SHA256
u8 sha256Buf[ SHA256_DIGEST_LENGTH ];
u8 ecdsasig[ 0x80 ];
const u8 *pECDSAsig = ecdsasig;
ECDSA_SIG *sig = NULL;
int signLen = 0;
int test_ret = 0;
// CR_DeviceCertのSHA256計算
SHA256( deviceCert.issuerName, (int)&deviceCert + sizeof(CR_DeviceCert) - (int)deviceCert.issuerName, sha256Buf );
// 上位232bit分で署名
memset( ecdsasig, 0, sizeof(ecdsasig) );
test_ret = ECDSA_sign( 0, sha256Buf, 32, ecdsasig, &signLen, NCT2 );
#else // !ECDSA_SHA256
u8 sha1Buf[ 20 ];
u8 ecdsasig[ 0x80 ];
const u8 *pECDSAsig = ecdsasig;
ECDSA_SIG *sig = NULL;
int signLen = 0;
int test_ret = 0;
// CR_DeviceCertのSHA1計算
SHA1( deviceCert.issuerName, (int)&deviceCert + sizeof(CR_DeviceCert) - (int)deviceCert.issuerName, sha1Buf );
// 署名
memset( ecdsasig, 0, sizeof(ecdsasig) );
test_ret = ECDSA_sign( 0, sha1Buf, 20, ecdsasig, &signLen, NCT2 );
#endif // ECDSA_SHA256
if (test_ret == 0) {
ret_code = CR_GENID_ERROR_ECDSA_SIGN;
SetErrorInfo( __FUNCTION__, __LINE__ );
goto end;
}
DEBUG_PRINT_ARRAY( "ECDSA:", (const char *)ecdsasig, signLen );
// DERデコードして、r と s を eccSignature にセット
sig = d2i_ECDSA_SIG( NULL, &pECDSAsig, signLen );
if( sig == NULL ) {
ret_code = CR_GENID_ERROR_ECDSA_DEC;
SetErrorInfo( __FUNCTION__, __LINE__ );
goto end;
}
#if 0
DEBUG_PRINT_ARRAY( "ECDSA.r:", (const char *)sig->r->d, sig->r->dmax * 4);
DEBUG_PRINT_ARRAY( "ECDSA.s:", (const char *)sig->s->d, sig->s->dmax * 4 );
#endif
BN2BinWithPadding( sig->r, &deviceCert.eccSignature[ 0 ], 30 );
BN2BinWithPadding( sig->s, &deviceCert.eccSignature[ 30 ], 30 );
memcpy( pDevCertSign, &deviceCert.eccSignature, 60 );
if( sig ) ECDSA_SIG_free( sig );
if( NCT2 ) EC_KEY_free( NCT2 );
NCT2 = NULL;
#endif // USE_HSM
#ifdef DEBUG_OUTPUT_FILE
#ifdef ECDSA_SHA256
DebugFileOutput( device_id, "dgst", sha256Buf, 32 );
#else // !ECDSA_SHA256
DebugFileOutput( device_id, "dgst", sha1Buf, 20 );
#endif // ECDSA_SHA256
DebugFileOutput( device_id, "sign", deviceCert.eccSignature, 60 );
#endif // DEBUG_OUTPUT_FILE
// ECDSA署名検証
{
// bonding_option によって、鍵を差し替え
const unsigned char *der_pub = bonding_option ? cr_NCT2_pub_dev : cr_NCT2_pub_prod;
int pub_len = der_pub[ 8 ] | der_pub[ 9 ] << 8; // KEY長を取り出し
der_pub += 0x10; // ヘッダ部分を除外してKEY実体を指定
// BIT STRING の実データ部分のみを指定するよう調整
pub_len = der_pub[0x15] - 1;
der_pub += 0x17;
// ECC公開鍵の読み込み
NCT2 = EC_KEY_new_by_curve_name( NID_sect233r1 );
if( NCT2 == NULL ) {
SetErrorInfo( __FUNCTION__, __LINE__ );
ret_code = CR_GENID_ERROR_ECC_KEY_NEW;
goto end;
}
if( o2i_ECPublicKey( &NCT2, &der_pub, pub_len ) == NULL ) {
SetErrorInfo( __FUNCTION__, __LINE__ );
ret_code = CR_GENID_ERROR_ECC_READ_PUBLIC_KEY;
goto end;
}
// ECDSA署名DERを再構築
u8 signBuf[70];
int signLen = 66;
memset( signBuf, 0, sizeof( signBuf ) );
signBuf[0] = 0x30;
signBuf[1] = 0x40;
signBuf[2] = 0x02;
signBuf[3] = 0x1E;
memcpy( &signBuf[4], &deviceCert.eccSignature[0], 0x1E );
signBuf[0x22] = 0x02;
signBuf[0x23] = 0x1E;
memcpy( &signBuf[0x24], &deviceCert.eccSignature[30], 0x1E );
DEBUG_PRINT_ARRAY( (char*)"sign(HSM)", (const char *)signBuf, signLen );
// 署名ベリファイ
#ifdef ECDSA_SHA256
ret_code = ECDSA_verify( 0, sha256Buf, 32, signBuf, signLen, NCT2 );
#else // !ECDSA_SHA256
ret_code = ECDSA_verify( 0, sha1Buf, 20, signBuf, signLen, NCT2 );
#endif // ECDSA_SHA256
if( ret_code != 1) {
ret_code = CR_GENID_ERROR_ECDSA_VERIFY;
SetErrorInfo( __FUNCTION__, __LINE__ );
goto end;
}
}
ret_code = CR_GENID_SUCCESS;
#ifdef DEBUG_PRINT
if ( cr_print_flag )
{
int i;
printf( "deviceCert:\n" );
printf( "sigType : 0x%08X\n", *(unsigned int*)deviceCert.sigType );
DEBUG_PRINT_ARRAY( "eccSignature:", (const char *)deviceCert.eccSignature, sizeof(deviceCert.eccSignature) );
DEBUG_PRINT_ARRAY( "padding0:", (const char *)deviceCert.padding0, sizeof(deviceCert.padding0) );
printf( "issuerName : " );
for ( i = 0; i < sizeof(deviceCert.issuerName); i++ ) printf( "%c", deviceCert.issuerName[i] );
printf( "\n" );
printf( "keyType : 0x%08X\n", *(unsigned int*)deviceCert.keyType );
printf( "subject : " );
for ( i = 0; i < sizeof(deviceCert.subject); i++ ) printf( "%c", deviceCert.subject[i] );
printf( "\n" );
printf( "expiryDate : 0x%08X\n", (unsigned int)deviceCert.expiryDate );
{
struct tm *tmt;
tmt = gmtime( &deviceCert.expiryDate );
printf( " GMT:%d-%02d-%02d %02d:%02d:%02d\n",
tmt->tm_year+1900, tmt->tm_mon+1, tmt->tm_mday, tmt->tm_hour, tmt->tm_min, tmt->tm_sec );
}
DEBUG_PRINT_ARRAY( "eccPubKey :", (const char *)deviceCert.eccPubKey, sizeof(deviceCert.eccPubKey) );
DEBUG_PRINT_ARRAY( "padding1:", (const char *)deviceCert.padding1, sizeof(deviceCert.padding1) );
}
#endif // DEBUG_PRINT
#ifdef DEBUG_OUTPUT_FILE
DebugFileOutput( device_id, "crt", (const u8 *)&deviceCert, sizeof(CR_DeviceCert) );
#endif // DEBUG_OUTPUT_FILE
end:
if( NCT2 ) EC_KEY_free( NCT2 );
return ret_code;
} // generate_CTRCustom_deviceCert
// 指定BIGNUMをバイナリ変換して指定バッファに右詰めでセット
static void BN2BinWithPadding( BIGNUM *pBN, u8 *pDst, int dstLen )
{
int i;
int bnBitLen, bnByteLen;
u8 buffer[ 32 ];
memset( buffer, 0, sizeof(buffer) );
bnBitLen = BN_num_bits( pBN );
bnByteLen = ( bnBitLen / 8 ) + ( ( bnBitLen % 8 ) ? 1 : 0 );
BN_bn2bin( pBN, (u8*)buffer );
for( i = 0; i < bnByteLen; i++ ) {
pDst[ dstLen - 1 - i ] = buffer[ bnByteLen - 1 - i ];
}
}

View File

@ -0,0 +1,382 @@
/* ====================================================================
* Copyright (c) 1998-2008 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include "cr_generate_id.h"
#include "cr_generate_id_private.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <time.h>
#include <sys/time.h>
#include <string.h>
#ifdef USE_HSM
#include "cr_hsm_code.h"
#else // !USE_HSM
#include <openssl/rsa.h>
#include <openssl/aes.h>
#include "cr_eFuse_privKey_dev.c"
#include "cr_eFuse_pubKey_dev.c"
#include "cr_eFuse_privKey_prod.c"
#include "cr_eFuse_pubKey_prod.c"
#include "cr_eFuse_aesKey_dev.c"
#include "cr_eFuse_aesKey_prod.c"
extern RSA *d2i_RSA_PUBKEY(RSA **a, const unsigned char **pp, long length);
#endif // USE_HSM
#include "cr_eFuse_iv_dev.c"
#include "cr_eFuse_iv_prod.c"
#ifdef ENCRYPT_AES
static int crypto_aes_enc_dec( unsigned char *dst_buf,unsigned char *org_buf, u8 bonding_option );
#else // !ENCRYPT_AES
static int crypto_rsa_enc_dec( unsigned char *dst_buf,unsigned char *org_buf, u8 bonding_option );
#endif // ENCRYPT_AES
static unsigned char local_buf_1[CR_ID_BUF_SIZE];
static unsigned char local_buf_2[CR_ID_BUF_SIZE];
// ビルドスイッチに従ってAES or RSA で指定バッファを暗号化
int EncryptID( unsigned char *dst_buf, unsigned char *org_buf, u8 bonding_option )
{
#ifdef ENCRYPT_AES
#ifdef DEBUG_PRINT
if( cr_print_flag ) printf( "[AES]\n");
#endif // DEBUG_PRINT
return crypto_aes_enc_dec( dst_buf, org_buf, bonding_option ); // AES
#else // !ENCRYPT_AES
#ifdef DEBUG_PRINT
if( cr_print_flag ) printf( "[RSA]\n");
#endif // DEBUG_PRINT
return crypto_rsa_enc_dec( dst_buf, org_buf, bonding_option ); // RSA pubKey enc
#endif // ENCRYPT_AES
}
#ifdef ENCRYPT_AES
// AES
#ifdef USE_HSM
int crypto_aes_enc_dec( unsigned char *dst_buf, unsigned char *org_buf, u8 bonding_option )
{
int i;
int ret_code = CR_GENID_SUCCESS;
char *pIV = (char *)( bonding_option ? cr_eFuse_iv_dev : cr_eFuse_iv_prod ) + 0x10;
// encrypt
ret_code = hsm_aes_encrypt( local_buf_1, org_buf, CR_ID_BUF_SIZE, bonding_option, pIV );
if ( ret_code != CR_GENID_SUCCESS )
{
SetErrorInfo( __FUNCTION__, __LINE__ );
return ret_code;
}
// decyrpt
ret_code = hsm_aes_decrypt( local_buf_2, local_buf_1, CR_ID_BUF_SIZE, bonding_option, pIV );
if ( ret_code != CR_GENID_SUCCESS )
{
SetErrorInfo( __FUNCTION__, __LINE__ );
return ret_code;
}
// ベリファイ
for ( i = 0 ; i < CR_ID_BUF_SIZE ; i++ )
{
if( org_buf[i] != local_buf_2[i] )
{
ret_code = CR_GENID_ERROR_AES_VERIFY;
SetErrorInfo( __FUNCTION__, __LINE__ );
return ret_code;
}
}
memcpy( dst_buf, local_buf_1, CR_ID_BUF_SIZE );
return CR_GENID_SUCCESS;
} // hsm_crypto_aes_enc_dec
#else // !USE_HSM
int crypto_aes_enc_dec( unsigned char *dst_buf, unsigned char *org_buf, u8 bonding_option )
{
int i;
AES_KEY aesEncKey;
AES_KEY aesDecKey;
u8 temp_iv[16];
// 鍵データ取り出し。ヘッダ部分0x10を除去。
char *pAesKey = (char *)( bonding_option ? cr_eFuse_aesKey_dev : cr_eFuse_aesKey_prod ) + 0x10;
char *pIV = (char *)( bonding_option ? cr_eFuse_iv_dev : cr_eFuse_iv_prod ) + 0x10;
memset( local_buf_1, 0, CR_ID_BUF_SIZE );
memset( local_buf_2, 0, CR_ID_BUF_SIZE );
if ( AES_set_encrypt_key( pAesKey, 128, &aesEncKey ) != 0 )
{
SetErrorInfo( __FUNCTION__, __LINE__ );
return CR_GENID_ERROR_AES_ENC;
}
if ( AES_set_decrypt_key( pAesKey, 128, &aesDecKey ) != 0 )
{
SetErrorInfo( __FUNCTION__, __LINE__ );
return CR_GENID_ERROR_AES_DEC;
}
memcpy( temp_iv, pIV, 16 );
AES_cbc_encrypt ( org_buf, local_buf_1, CR_ID_BUF_SIZE, &aesEncKey, temp_iv, AES_ENCRYPT );
memcpy( temp_iv, pIV, 16 );
AES_cbc_encrypt ( local_buf_1, local_buf_2, CR_ID_BUF_SIZE, &aesDecKey, temp_iv, AES_DECRYPT );
// ベリファイ
for ( i = 0 ; i < CR_ID_BUF_SIZE ; i++ )
{
if( org_buf[i] != local_buf_2[i] )
{
SetErrorInfo( __FUNCTION__, __LINE__ );
return CR_GENID_ERROR_AES_VERIFY;
}
}
memcpy( dst_buf, local_buf_1, CR_ID_BUF_SIZE );
return CR_GENID_SUCCESS;
} // crypto_aes_enc_dec
#endif // USE_HSM
#else // !ENCRYPT_AES
// RSA
#ifdef USE_HSM
int crypto_rsa_enc_dec( unsigned char *dst_buf,unsigned char *org_buf, u8 bonding_option )
{
int i;
int ret_code = CR_GENID_SUCCESS;
// encrypt
ret_code = hsm_rsa_encrypt( local_buf_1, org_buf, CR_ID_BUF_SIZE, bonding_option );
if ( ret_code != CR_GENID_SUCCESS )
{
SetErrorInfo( __FUNCTION__, __LINE__ );
return ret_code;
}
// decyrpt
ret_code = hsm_rsa_decrypt( local_buf_2, local_buf_1, CR_ID_BUF_SIZE, bonding_option );
if ( ret_code != CR_GENID_SUCCESS )
{
SetErrorInfo( __FUNCTION__, __LINE__ );
return ret_code;
}
// ベリファイ
for ( i = 0 ; i < CR_ID_BUF_SIZE ; i++ )
{
if( org_buf[i] != local_buf_2[i] )
{
ret_code = CR_GENID_ERROR_RSA_VERIFY;
SetErrorInfo( __FUNCTION__, __LINE__ );
return ret_code;
}
}
memcpy( dst_buf, local_buf_1, CR_ID_BUF_SIZE );
return CR_GENID_SUCCESS;
} // hsm_crypto_rsa_enc_dec
#else // USE_HSM
int crypto_rsa_enc_dec( unsigned char *dst_buf,unsigned char *org_buf, u8 bonding_option )
{
int ret_code = CR_GENID_SUCCESS;
int rsa_outlen = 0;
RSA *rsa_privkey = NULL;
RSA *rsa_pubkey = NULL;
memset(local_buf_1, 0,CR_ID_BUF_SIZE);
memset(local_buf_2, 0,CR_ID_BUF_SIZE);
// DERフォーマットのRSA鍵を読み込み
{
// bonding_option によって、鍵を差し替え
const unsigned char *der_priv = bonding_option ? cr_eFuse_privKey_dev : cr_eFuse_privKey_prod;
const unsigned char *der_pub = bonding_option ? cr_eFuse_pubKey_dev : cr_eFuse_pubKey_prod;
int priv_len = der_priv[ 8 ] | der_priv[ 9 ] << 8; // KEY長を取り出し
int pub_len = der_pub [ 8 ] | der_pub [ 9 ] << 8; // 同上
der_priv += 0x10; // ヘッダ部分を除外してKEY実体を指定
der_pub += 0x10; // 同上
// コマンドラインのopensslが出力する秘密鍵は、PKCS#1 RSAPublicKeyフォーマットなので、この関数を使う。
rsa_privkey = d2i_RSAPrivateKey( NULL, &der_priv, priv_len );
if( rsa_privkey == NULL ) {
ret_code = CR_GENID_ERROR_RSA_READ_PRIVATE_KEY;
SetErrorInfo( __FUNCTION__, __LINE__ );
goto end;
}
// コマンドラインのopensslが出力する公開鍵は、SubjectPublicKeyInfo形式なので、この関数を使う。
rsa_pubkey = d2i_RSA_PUBKEY( NULL, &der_pub, pub_len );
if( rsa_pubkey == NULL ) {
ret_code = CR_GENID_ERROR_RSA_READ_PUBLIC_KEY;
SetErrorInfo( __FUNCTION__, __LINE__ );
goto end;
}
}
if( (rsa_outlen = RSA_private_encrypt(CR_ID_BUF_SIZE, org_buf, local_buf_1,
rsa_privkey, RSA_NO_PADDING)) == -1) {
ret_code = CR_GENID_ERROR_RSA_ENC;
SetErrorInfo( __FUNCTION__, __LINE__ );
goto end;
}
else {
if((rsa_outlen = RSA_public_decrypt(rsa_outlen, local_buf_1, local_buf_2,
rsa_pubkey, RSA_NO_PADDING)) == -1) {
ret_code = CR_GENID_ERROR_RSA_DEC;
SetErrorInfo( __FUNCTION__, __LINE__ );
goto end;
}
else {
int i;
int error_flag = 0;
for( i = 0 ; i < CR_ID_BUF_SIZE ; i++ ) {
if( org_buf[i] != local_buf_2[i] ) {
error_flag++;
}
}
if( error_flag ) {
ret_code = CR_GENID_ERROR_RSA_VERIFY;
SetErrorInfo( __FUNCTION__, __LINE__ );
goto end;
}
}
}
memcpy(dst_buf,local_buf_1,CR_ID_BUF_SIZE);
end:
if ( rsa_privkey ) RSA_free( rsa_privkey );
if ( rsa_pubkey ) RSA_free( rsa_pubkey );
return ret_code;
}
#endif // !USE_HSM
#endif // ENCRYPT_AES

View File

@ -0,0 +1,441 @@
/* ====================================================================
* Copyright (c) 1998-2008 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <time.h>
#include <sys/time.h>
#include <string.h>
#ifdef USE_HSM
#include "cr_hsm_code.h"
#include "cr_hsm_alloc.h" // temp
#endif // USE_HSM
// openssl
#include <openssl/sha.h>
#include <openssl/x509.h>
#include "cr_generate_id.h"
#include "cr_generate_id_private.h"
#include "cr_alloc.h"
// ビルド時の日時記録
static struct
{
const u8 *title; const u8 *date; const u8 *time;
}
buildInfo = { "LIBGENID_BUILD_INFO:", __DATE__, __TIME__ };
static u64 generatingCount = 0; // 現在生成中のID(起動時からの通算)
int cr_print_flag = 0;
// generate_id関数のイニシャライズ
int cr_generate_id_initialize( u8 err_buf[CR_ID_BUF_SIZE] )
{
int ret_code = CR_GENID_SUCCESS;
// ビルド情報がデッドストリップされないよう参照
const u8 *dummyPtr = NULL;
dummyPtr = buildInfo.title;
dummyPtr = NULL;
// 生成カウンタの初期化
generatingCount = 0;
// init for error info
InitErrorInfo();
// OpenSSL のメモリリーク防止のため、オリジナルのアロケータを使用。
if ( CRYPTO_set_mem_functions( cr_mem_malloc, cr_mem_realloc, cr_mem_free ) != 1 )
{
CR_ERR_BUFFER *cr_err_buf = (CR_ERR_BUFFER *)err_buf;
memset( cr_err_buf, 0, sizeof( CR_ERR_BUFFER ) );
cr_err_buf->errorCode = CR_GENID_ERROR_SET_MEM_FUNCTIONS;
GetErrorInfo( cr_err_buf->callStack, &cr_err_buf->recordSize );
#ifdef DEBUG_PRINT
printf( "error(%d), CALL_STACK : %s\n", (int)cr_err_buf->errorCode, cr_err_buf->callStack );
#endif
return CR_GENID_FAILED;
}
#ifdef USE_HSM
ret_code = hsm_initialize();
if ( ret_code != CR_GENID_SUCCESS )
{
CR_ERR_BUFFER *cr_err_buf = (CR_ERR_BUFFER *)err_buf;
memset( cr_err_buf, 0, sizeof( CR_ERR_BUFFER ) );
cr_err_buf->errorCode = ret_code;
GetErrorInfo( cr_err_buf->callStack, &cr_err_buf->recordSize );
#ifdef DEBUG_PRINT
printf( "error(%d), CALL_STACK : %s\n", (int)cr_err_buf->errorCode, cr_err_buf->callStack );
#endif
return CR_GENID_FAILED;
}
#endif
return ret_code;
} // cr_generate_id_initialize
// generate_id関数のファイナライズ
int cr_generate_id_finalize( u8 err_buf[CR_ID_BUF_SIZE] )
{
int ret_code = CR_GENID_SUCCESS;
// init for error info
InitErrorInfo();
// HSM
#ifdef USE_HSM
ret_code = hsm_finalize();
if ( ret_code != CR_GENID_SUCCESS )
{
CR_ERR_BUFFER *cr_err_buf = (CR_ERR_BUFFER *)err_buf;
memset( cr_err_buf, 0, sizeof( CR_ERR_BUFFER ) );
cr_err_buf->errorCode = ret_code;
GetErrorInfo( cr_err_buf->callStack, &cr_err_buf->recordSize );
#ifdef DEBUG_PRINT
printf( "error(%d), CALL_STACK : %s\n", (int)cr_err_buf->errorCode, cr_err_buf->callStack );
#endif
}
#endif // USE_HSM
return ret_code;
} // cr_generate_id_finalize
// generate_id 関数
int cr_generate_id( u32 device_id[CR_NUM_OF_DEVICEID], u8 id_buf[CR_ID_BUF_SIZE], u8 bonding_option )
{
int i;
int ret_code = CR_GENID_SUCCESS;
CR_ID_BUFFER *cr_id_buf;
EC_KEY *deviceKeyPair = NULL;
// エラー発生時に備えて、エラーバッファの初期化とトータルのID生成カウントセット
InitErrorInfo();
generatingCount++;
#ifdef DEBUG_PRINT
if( sizeof(CR_ID_BUFFER) != 256 ) {
printf( "CR_ID_BUFFER size error. %d\n", sizeof(CR_ID_BUFFER) );
}
if( sizeof(CR_ERR_BUFFER) != 256 ) {
printf( "CR_ERR_BUFFER size error. %d\n", sizeof(CR_ERR_BUFFER) );
}
#endif
//--------------------------------------------------------------
// 暗号処理初期化
//--------------------------------------------------------------
cr_mem_bufmgr_initialize();
#ifdef MY_CRYPTO_DEBUG
ERR_load_crypto_strings();
#endif /* MY_CRYPTO_DEBUG */
// ダイジェストアルゴリズムを追加する
OpenSSL_add_all_digests();
//--------------------------------------------------------------
// FuseIDバッファに固定データセット
//--------------------------------------------------------------
memset(id_buf, 0, CR_ID_BUF_SIZE);
cr_id_buf = (CR_ID_BUFFER *)id_buf;
cr_id_buf->magic_number = CR_GEN_ID_MAGICCODE; // HSM使用未使用でマジックコードが変わる。
cr_id_buf->version = CR_GEN_ID_VERSION;
//--------------------------------------------------------------
// 引数のボンディングオプションをセット
//--------------------------------------------------------------
cr_id_buf->bonding_option = bonding_option;
//--------------------------------------------------------------
// device_id セット
//--------------------------------------------------------------
for( i = 0 ; i < CR_NUM_OF_DEVICEID ; i++ ) {
cr_id_buf->device_id[i] = device_id[i]; /* device_id[0] => ec priv key */
}
#ifdef DEBUG_PRINT
if( cr_print_flag ) {
printf("device_id:\n");
printf(" 0x%08x\n", (unsigned int)device_id[0] );
printf(" 0x%08x%08x\n", (unsigned int)device_id[2], (unsigned int)device_id[1] );
printf(" 0x%08x%08x\n", (unsigned int)device_id[4], (unsigned int)device_id[3] );
printf("\n");
}
#endif /* DEBUG_PRINT */
//--------------------------------------------------------------
// タイムスタンプセット
//--------------------------------------------------------------
ret_code = GetTimestamp( &cr_id_buf->year,
&cr_id_buf->month,
&cr_id_buf->mday,
&cr_id_buf->hour,
&cr_id_buf->min,
&cr_id_buf->sec,
&cr_id_buf->expiryDate ); // デバイス証明書期限の元データもついでにセットしておく
if ( ret_code != CR_GENID_SUCCESS ) {
SetErrorInfo( __FUNCTION__, __LINE__ );
goto end;
}
//--------------------------------------------------------------
// 乱数を生成してセット
//--------------------------------------------------------------
ret_code = GenerateRandom( cr_id_buf->random, CR_RANDOM_LENGTH );
if ( ret_code != CR_GENID_SUCCESS ) {
SetErrorInfo( __FUNCTION__, __LINE__ );
goto end;
}
DEBUG_PRINT_ARRAY( "rand:", (const char *)cr_id_buf->random, CR_RANDOM_LENGTH );
//--------------------------------------------------------------
// 楕円曲線鍵ペアを生成
//--------------------------------------------------------------
ret_code = GenarateECCKeyPair( &deviceKeyPair, cr_id_buf->devicePrivKey );
if ( ret_code != CR_GENID_SUCCESS ) {
SetErrorInfo( __FUNCTION__, __LINE__ );
goto end;
}
//--------------------------------------------------------------
// 生成した鍵ペアをECDSAで動作確認
//--------------------------------------------------------------
ret_code = TestECDSA( deviceKeyPair );
if ( ret_code != CR_GENID_SUCCESS ) {
goto end;
}
//--------------------------------------------------------------
// デバイス証明書生成 + 署名の付与 + 証明書期限セット
//--------------------------------------------------------------
ret_code = GenerateCTRDeviceCert( deviceKeyPair,
cr_id_buf->device_id[0],
cr_id_buf->bonding_option,
cr_id_buf->deviceCertSign,
&cr_id_buf->expiryDate );
if ( ret_code != CR_GENID_SUCCESS ) {
SetErrorInfo( __FUNCTION__, __LINE__ );
goto end;
}
#if 0
DEBUG_PRINT_ARRAY( "deviceCertSign:", (const char *)cr_id_buf->deviceCertSign, ECDSA_SIGN_LENGTH );
#endif
//--------------------------------------------------------------
// FuseIDバッファ全体のSHA256ハッシュを算出してセット
//--------------------------------------------------------------
SHA256(id_buf, CR_ID_BUF_SIZE - SHA256_DIGEST_LENGTH, cr_id_buf->hash);
DEBUG_PRINT_ARRAY( "SHA256 Digest:", (const char *)cr_id_buf->hash, SHA256_DIGEST_LENGTH );
//--------------------------------------------------------------
// FuseID RAWデータ完成
//--------------------------------------------------------------
DEBUG_PRINT_ARRAY( "RAW eFuseID:", (const char *)id_buf, CR_ID_BUF_SIZE );
#ifdef DEBUG_OUTPUT_FILE
DebugFileOutput( device_id[ 0 ], "raw", id_buf, CR_ID_BUF_SIZE );
#endif // DEBUG_OUTPUT_FILE
//--------------------------------------------------------------
// FuseIDバッファ全体をAES or RSAで暗号化
//--------------------------------------------------------------
ret_code = EncryptID( id_buf, id_buf, bonding_option );
if( ret_code != CR_GENID_SUCCESS ) {
SetErrorInfo( __FUNCTION__, __LINE__ );
goto end;
}
DEBUG_PRINT_ARRAY( "ENC eFuseID:", (const char *)id_buf, CR_ID_BUF_SIZE );
#ifdef DEBUG_OUTPUT_FILE
DebugFileOutput( device_id[ 0 ], "enc", id_buf, CR_ID_BUF_SIZE );
#endif // DEBUG_OUTPUT_FILE
//--------------------------------------------------------------
// 終了処理
//--------------------------------------------------------------
end:
/* id_buf[]にエラーログを書き込む。 */
if ( ret_code != CR_GENID_SUCCESS )
{
CR_ERR_BUFFER *cr_err_buf = (CR_ERR_BUFFER *)id_buf;
memset( cr_err_buf, 0, sizeof( CR_ERR_BUFFER ) );
cr_err_buf->totalCount = generatingCount;
cr_err_buf->magic_number = 0x01234567;
cr_err_buf->device_id0 = device_id[0];
cr_err_buf->errorCode = ret_code;
GetErrorInfo( cr_err_buf->callStack, &cr_err_buf->recordSize );
cr_err_buf->bonding_option = bonding_option;
#ifdef DEBUG_PRINT
printf( "CALL_STACK : %s\n", cr_err_buf->callStack );
#endif
}
// リソースの解放
if ( deviceKeyPair ) EC_KEY_free( deviceKeyPair );
ERR_remove_state(0);
EVP_cleanup();
CRYPTO_cleanup_all_ex_data();
#ifdef MY_CRYPTO_DEBUG
ERR_free_strings();
#endif /* MY_CRYPTO_DEBUG */
#if 0
if ( cr_print_flag )
{
printf( "hsm alloc counter : %d\n", my_hsm_get_alloc_counter() );
printf( "hsmbn alloc counter : %d\n", my_bignum_get_alloc_counter() );
printf( "miya alloc counter : %d\n", cr_mem_get_counter() );
}
#endif
return ret_code; /* success */
}
#ifdef DEBUG_PRINT
void DebugPrintArray( char *pStr, const u8 *pData, int length )
{
int i;
if( cr_print_flag ) {
printf( "%s", pStr );
for( i = 0 ; i < length; i++ ) {
if( (i % 16) == 0 ) printf("\n ");
printf("%02X ", pData[ i ] );
}
printf("\n");
}
}
#endif
void DebugFileOutput( u32 device_id, char *pSuffix, const u8 *pSrc, int length )
{
if ( cr_print_flag )
{
// 証明書の書き込みテスト
FILE *fp;
char fn[256];
sprintf( fn, "output/0x%08x.%s", (unsigned int)device_id, pSuffix );
fp = fopen( fn, "wb" );
fwrite( pSrc, length, 1, fp );
fclose( fp );
}
}

View File

@ -0,0 +1,160 @@
/* ====================================================================
* Copyright (c) 1998-2008 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#ifndef _CR_GENERATE_ID_H_
#define _CR_GENERATE_ID_H_
// 成功 or 失敗 (詳細はエラーバッファに格納される)
#define CR_GENID_SUCCESS ( 0)
#define CR_GENID_FAILED ( 1)
#ifdef __cplusplus
extern "C" {
#endif
typedef signed char s8;
typedef unsigned char u8;
typedef unsigned short u16;
typedef signed long s32;
typedef unsigned long u32;
typedef unsigned long long u64;
#define CR_ID_BUF_SIZE (2048/8)
#define CR_NUM_OF_DEVICEID 5
/*
device_id ID
ID0 = device_id[ 0 ]
ID1 = device_id[ 1 ] | ( device_id[ 2 ] << 32 )
ID2 = device_id[ 3 ] | ( device_id[ 4 ] << 32 )
*/
// eFuseID 仕様
#define CR_ID0_BIT_NUM 32
#define CR_ID1_BIT_NUM 34
#define CR_ID2_BIT_NUM 64
#define CR_ID0_MASK 0xFFFFFFFF // 32bit
#define CR_ID1_MASK 0x00000003FFFFFFFFll // 34bit
#define CR_ID2_MASK 0xFFFFFFFFFFFFFFFFll // 64bit
extern int cr_generate_id_initialize( u8 err_buf[CR_ID_BUF_SIZE] );
extern int cr_generate_id( u32 device_id[CR_NUM_OF_DEVICEID], u8 id[CR_ID_BUF_SIZE], u8 bonding_option );
extern int cr_generate_id_finalize( u8 err_buf[CR_ID_BUF_SIZE] );
extern int cr_print_flag;
#ifdef __cplusplus
}
#endif
#endif /* _CR_GENERATE_ID_H_ */

View File

@ -0,0 +1,234 @@
/* ====================================================================
* Copyright (c) 1998-2008 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#ifndef _CR_GENERATE_ID_PRIVATE_H_
#define _CR_GENERATE_ID_PRIVATE_H_
#ifdef __cplusplus
extern "C" {
#endif
#ifdef USE_HSM
// nShield
#include "nfastapp.h"
#include "nfkm.h"
#include "rqcard-applic.h"
#include "rqcard-fips.h"
#endif // USE_HSM
#include <openssl/err.h>
#include <openssl/sha.h>
#include <openssl/ec.h>
#include "ec_lcl.h" // EC_KEY (=ec_key_st) 構造体の参照に必要
#ifdef DEBUG_PRINT
#define DEBUG_PRINT_ARRAY DebugPrintArray
#else // !DEBUG_PRINT
#define DEBUG_PRINT_ARRAY( ... ) ((void)0)
#endif // DEBUG_PRINT
#define ENCRYPT_AES 1 // 定義を有効でFIX.これが未定義の場合、IDの暗号化がRSAになる。
#define CR_GEN_ID_VERSION 4 // シャープへのリリースごとにUPする。
// 2010/02/01 Release ver.4
#ifdef USE_HSM
#define CR_GEN_ID_MAGICCODE 0xdeadb00f; /* 最終的にはこちらで動作。0xdeadbeefにするとRSAでコケる。 */
#else // !USE_HSM
#define CR_GEN_ID_MAGICCODE 0xabadf00d;
#endif // USE_HSM
#define CR_RANDOM_LENGTH 0x50
#define EC_PRIVATE_KEY_LENGTH 0x20
#define ECDSA_SIGN_LENGTH 0x3C
#define CR_RSV_LENGTH 0x10
#define EC_CURVE_NAME NID_sect233r1
//---------------------------------------------------
// OpenSSLの処理結果によるエラーコード
//---------------------------------------------------
#define CR_GENID_ERROR_BN_NEW ( -1)
#define CR_GENID_ERROR_ECC_KEY_NEW ( -2)
#define CR_GENID_ERROR_ECC_GENERATE_PRIVATE_KEY ( -3)
#define CR_GENID_ERROR_ECC_GENERATE_PUBLIC_KEY ( -4)
#define CR_GENID_ERROR_ECC_READ_PRIVATE_KEY ( -5)
#define CR_GENID_ERROR_ECC_READ_PUBLIC_KEY ( -6)
#define CR_GENID_ERROR_ECDSA_SIGN ( -7)
#define CR_GENID_ERROR_ECDSA_DEC ( -8)
#define CR_GENID_ERROR_ECDSA_VERIFY ( -9)
#define CR_GENID_ERROR_AES_ENC (-10)
#define CR_GENID_ERROR_AES_DEC (-11)
#define CR_GENID_ERROR_AES_VERIFY (-12)
#define CR_GENID_ERROR_RSA_READ_PRIVATE_KEY (-13)
#define CR_GENID_ERROR_RSA_READ_PUBLIC_KEY (-14)
#define CR_GENID_ERROR_RSA_ENC (-15)
#define CR_GENID_ERROR_RSA_DEC (-16)
#define CR_GENID_ERROR_RSA_VERIFY (-17)
#define CR_GENID_ERROR_SET_MEM_FUNCTIONS (-18)
typedef struct {
u32 magic_number; /* 0x00 - 0x03 = 0xdeadb00f 確定!*/
u32 device_id[CR_NUM_OF_DEVICEID]; /* 0x04 - 0x07 32bit device ID
(32bit1
(IDrandomの先頭0x1C bytesを組み合わせて)
0x08 - 0x0F 64bit CTR番号 seed
(34bitのみ使用14)
0x10 - 0x17 64bit ID
(64bitフルに使用10x100000000)
*/
u8 version; /* 0x18 = CR_GEN_ID_VERSION */
u8 bonding_option; /* 0x19 ボンディングオプション */
u8 year; /* 0x1A デバイス証明書発行時間 HSMから取得 */
u8 month; /* 0x1B */
u8 mday; /* 0x1C */
u8 hour; /* 0x1D */
u8 min; /* 0x1E */
u8 sec; /* 0x1F */
u32 expiryDate; /* 0x20 - 0x23 デバイス証明書期限 seconds from the Epoch (Jan 1, 1970 00:00) as a 32 bit */
u8 devicePrivKey[ EC_PRIVATE_KEY_LENGTH ];
/* 0x24 - 0x43 ECC233 private key (big endian) ユニーク性保証なし */
u8 deviceCertSign[ ECDSA_SIGN_LENGTH ];
/* 0x44 - 0x7F ECC233 ECDSA signature (big endian) */
u8 reserved[ CR_RSV_LENGTH ]; /* 0x80 - 0x8F 予約 */
u8 random[ CR_RANDOM_LENGTH ]; /* 0x90 - 0xDF 乱数 */
u8 hash[ SHA256_DIGEST_LENGTH ]; /* 0xE0 - 0xFF "0x00-0xDF"領域のSHA256ハッシュ */
} CR_ID_BUFFER; /* 合計256bytes = 2048bit */
#define CALL_STACK_SIZE (234)
typedef struct {
u64 totalCount; /* 0x00 - 0x07 */
u32 magic_number; /* 0x08 - 0x0b 0x01234567 確定!*/
u32 device_id0; /* 0x0c - 0x0f */
s32 errorCode; /* 0x10 - 0x13 */
u8 bonding_option;
u8 recordSize; // コールスタックの記録サイズ
u8 callStack[ CALL_STACK_SIZE ];
} CR_ERR_BUFFER;
extern int GetTimestamp( u8 *pYear, u8 *pMonth, u8 *pMday, u8 *pHour, u8 *pMin, u8 *pSec, time_t *pTime);
extern int GenerateRandom( u8 *pDst, int length );
extern int GenarateECCKeyPair( EC_KEY **ppECkey, u8 *pECPrivkey );
extern void InitErrorInfo( void );
extern void SetErrorInfo( const char *funcName, u32 line );
extern void GetErrorInfo( char *stack, u8 *size );
extern int TestECDSA( EC_KEY *pECkey );
extern int GenerateCTRDeviceCert( EC_KEY *pECkey, u32 device_id, u8 bonding_option, u8 *pDevCertSign, u32 *pExpiryDate );
extern int EncryptID( unsigned char *dst_buf, unsigned char *org_buf, u8 bonding_option );
extern void DebugPrintArray( char *pStr, const u8 *pData, int length );
extern void DebugFileOutput( u32 device_id, char *pSuffix, const u8 *pSrc, int length );
#ifdef __cplusplus
}
#endif
#endif /* _CR_GENERATE_ID_PRIVATE_H_ */

View File

@ -0,0 +1,62 @@
/*
* my_hsm_alloc.c
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#ifdef USE_HSM
#include "nfastapp.h"
#include "nfutil.h"
#include "cr_hsm_alloc.h"
/* --------------------- */
static int alloc_counter = 0;
/* --------------------- */
const NFast_MallocUpcalls my_hsm_malloc_upcalls =
{
my_hsm_malloc, my_hsm_realloc, my_hsm_free
};
/* --------------------- */
void *my_hsm_malloc( size_t nbytes,
struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx )
{
alloc_counter++;
return malloc( nbytes );
}
/* --------------------- */
void *my_hsm_realloc( void *ptr, size_t nbytes,
struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx )
{
return realloc( ptr, nbytes );
}
/* --------------------- */
void my_hsm_free( void *ptr,
struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx )
{
free( ptr );
alloc_counter--;
}
/* --------------------- */
int my_hsm_get_alloc_counter( void )
{
return alloc_counter;
}
#endif // HSM

View File

@ -0,0 +1,32 @@
/*
* cr_hsm_alloc.h
*/
#ifndef CR_HSM_ALLOC_H
#define CR_HSM_ALLOC_H
#include "nfastapp.h"
#ifdef __cplusplus
extern "C" {
#endif
extern const NFast_MallocUpcalls my_hsm_malloc_upcalls;
void *my_hsm_malloc( size_t nbytes,
struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx );
void *my_hsm_realloc( void *ptr, size_t nbytes,
struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx );
void my_hsm_free( void *ptr,
struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx );
int my_hsm_get_alloc_counter( void );
#ifdef __cplusplus
}
#endif
#endif // CR_HSM_ALLOC_H

View File

@ -0,0 +1,416 @@
/*
* SIMPLEBIGNUM.C
*
* Simple bignumber upcalls
*
* This example source code is provided for your information and
* assistance. See the file LICENCE.TXT for details and the
* terms and conditions of the licence which governs the use of the
* source code. By using such source code you will be accepting these
* terms and conditions. If you do not wish to accept these terms and
* conditions, DO NOT OPEN THE FILE OR USE THE SOURCE CODE.
*
* Note that there is NO WARRANTY.
*
* Copyright 2001 - 2002 nCipher Corporation Limited.
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#ifdef USE_HSM
#include "nfastapp.h"
#include "nfutil.h"
#include "cr_hsm_bignum.h"
/* --------------------- */
// original : nfutil_copybytes ( nfutil.c )
static void my_bignum_copybytes ( unsigned char *dst, const unsigned char *src,
unsigned nbytes, int swapends, int swapwords )
{
int inc;
unsigned nwords;
/* Copies dst to src, swapping endianness and/or word order. dst and src mustn't overlap! */
assert( (nbytes & 3)==0 ); /* Must be whole number of M_Words */
if ( !swapends && !swapwords )
{
memcpy(dst, src, nbytes);
return;
}
if ( swapwords )
{
dst += (nbytes-4);
inc=-4;
}
else
inc=4;
nwords = nbytes>>2;
if ( swapends )
{
while ( nwords-- > 0 )
{
dst[0]=src[3];
dst[1]=src[2];
dst[2]=src[1];
dst[3]=src[0];
dst += inc;
src += 4;
}
}
else
{
while ( nwords-- > 0 )
{
dst[0]=src[0];
dst[1]=src[1];
dst[2]=src[2];
dst[3]=src[3];
dst += inc;
src += 4;
}
}
}
/* --------------------- */
int my_bignumreceiveupcall(struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx,
M_Bignum *bignum, int nbytes,
const void *source,
int msbitfirst, int mswordfirst)
{
struct NFast_Bignum *pBN;
if ( nbytes > MAXBIGNUMBITS/8 ) return Status_OutOfRange;
assert( (nbytes & 3)==0 );
pBN = (struct NFast_Bignum *)NFastApp_Malloc(app, sizeof(struct NFast_Bignum), cctx, tctx);
if ( !pBN ) return NOMEM;
my_bignum_copybytes(pBN->bytes, (const unsigned char *)source,
nbytes, 0, 0);
pBN->msb_first = msbitfirst;
pBN->msw_first = mswordfirst;
pBN->nbytes=nbytes;
*bignum=pBN;
return Status_OK;
}
/* --------------------- */
int my_bignumsendlenupcall(struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx,
const M_Bignum *bignum, int *nbytes_r)
{
assert( ((*bignum)->nbytes & 3)==0 );
*nbytes_r= (*bignum)->nbytes;
return Status_OK;
}
/* --------------------- */
int my_bignumsendupcall(struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx,
const M_Bignum *bignum, int nbytes,
void *dest, int msbitfirst, int mswordfirst)
{
int swapends, swapwords;
struct NFast_Bignum *pBN = *bignum;
assert( pBN->nbytes==nbytes );
/* Is format which we're sending in the same as that of the
bignumber?
(NB '!' used to constrain result to 0,1 range)
If not, work out which ends to swap.
*/
swapends = (!msbitfirst) ^ (!pBN->msb_first);
swapwords = (!mswordfirst) ^ (!pBN->msw_first);
my_bignum_copybytes( (unsigned char *)dest, (*bignum)->bytes, nbytes,
swapends, swapwords );
return Status_OK;
}
/* --------------------- */
void my_bignumfreeupcall(struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx,
M_Bignum *bignum)
{
NFastApp_Free(app, (*bignum), cctx, tctx);
*bignum=NULL;
}
/* --------------------- */
int my_bignumformatupcall(struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx,
int *msbitfirst_io, int *mswordfirst_io)
{
/* Send to the module in little-endian format.
(This is not officially necessary. However, some
versions of the monitor (Maintenance mode) don't accept
big-endian bignums due to a bug) */
*msbitfirst_io=0;
*mswordfirst_io=0;
return Status_OK;
}
NFast_BignumUpcalls my_upcalls = {
my_bignumreceiveupcall,
my_bignumsendlenupcall,
my_bignumsendupcall,
my_bignumfreeupcall,
my_bignumformatupcall
};
/* --------------------- */
static int char2hex ( char c )
{
if ( c >= '0' && c <= '9' ) return c-'0';
if ( c >= 'A' && c <= 'F' ) return c-'A'+10;
if ( c >= 'a' && c <= 'f' ) return c-'a'+10;
return -1;
}
/* --------------------- */
int my_char2bignum ( struct NFast_Bignum **ppBN_out,
const char *text,
struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx )
{
struct NFast_Bignum *pBN;
int d;
size_t len, i;
/* Strip leading whitespace */
while ( text[0] != 0 && isspace((unsigned char)text[0]) )
text++;
/* Strip trailing whitespace */
len=strlen(text);
while ( len > 0 && isspace((unsigned char)text[len-1]) )
len--;
if ( len > MAXBIGNUMBITS/4 ) return Status_OutOfRange;
pBN = (struct NFast_Bignum *)NFastApp_Malloc(app, sizeof(struct NFast_Bignum), cctx, tctx);
if ( !pBN ) return NOMEM;
pBN->msb_first = 0;
pBN->msw_first = 0;
/* Read in from the LS digit */
for ( i=0; i<len; i++ )
{
d = char2hex(text[len-1-i]);
if ( d < 0 ) return Status_Malformed;
if ( i & 1 )
pBN->bytes[i/2] |= (d << 4);
else
pBN->bytes[i/2] = d;
}
/* Pad to words if necessary */
i = (len+1)/2;
while ( (i & 3) != 0 )
pBN->bytes[i++] = 0;
assert(i <= INT_MAX);
pBN->nbytes=(int)i;
*ppBN_out=pBN;
return Status_OK;
}
/* --------------------- */
// bin データを NFast_Bignum データに変換する
int my_bin2bignum ( struct NFast_Bignum **ppBN_out,
struct NFast_Application *app,
const unsigned char *bin, const int size )
{
struct NFast_Bignum *pBN;
int len, i;
len = size;
if ( len > MAXBIGNUMBITS/4 ) return Status_OutOfRange;
pBN = (struct NFast_Bignum *)NFastApp_Malloc( app, sizeof(struct NFast_Bignum), NULL, NULL );
if ( !pBN ) return NOMEM;
pBN->msb_first = 0;
pBN->msw_first = 0;
for ( i = 0; i < len; i++ )
pBN->bytes[i] = bin[len-1-i];
while ( (i & 3) != 0 )
pBN->bytes[i++] = 0;
pBN->nbytes = i;
*ppBN_out = pBN;
return Status_OK;
} // my_bin2bignum
/* --------------------- */
static int getbyte ( const struct NFast_Bignum *pN, int pos )
{
/* Get a byte from a bignum, taking account of possible strange endianness */
if ( pos >= pN->nbytes ) return 0;
if ( pN->msb_first ) pos ^= 3; /* Big endian words */
if ( pN->msw_first )
{
pos = pN->nbytes-1-pos;
pos ^= 3;
}
return pN->bytes[pos];
}
/* --------------------- */
static int getbytelen ( const struct NFast_Bignum *pN )
{
int n=pN->nbytes-1;
while ( n >= 0 && getbyte(pN, n)==0 )
n--;
return n+1;
}
/* --------------------- */
int my_bignum2char ( char *buf, int buflen,
const struct NFast_Bignum *pBN,
struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx )
{
int i, d, pos, len;
static const char *hexdigits="0123456789ABCDEF";
len = pBN->nbytes;
pos = len*2+1;
if ( buflen < pos )
return Status_BufferFull;
buf[--pos] = 0;
for ( i=0; i<len; i++ )
{
d = getbyte(pBN,i);
buf[--pos] = hexdigits[d & 0xF];
buf[--pos] = hexdigits[(d>>4) & 0xF];
}
return Status_OK;
}
/* --------------------- */
int my_bignum2bin ( unsigned char *buf, int buflen,
struct NFast_Application *app,
const struct NFast_Bignum *pBN )
{
int i, pos, len;
len = pBN->nbytes;
pos = len;
if ( buflen < pos )
return Status_BufferFull;
for ( i = 0; i < len; i++ )
{
buf[--pos] = getbyte( pBN, i );
}
return Status_OK;
} // my_bignum2bin
/* --------------------- */
int my_bignumCopy( struct NFast_Bignum **dst,
const struct NFast_Bignum *src,
struct NFast_Application *app )
{
struct NFast_Bignum *pBN;
pBN = (struct NFast_Bignum *)NFastApp_Malloc( app, sizeof(struct NFast_Bignum), NULL, NULL );
if ( !pBN ) return NOMEM;
pBN->msb_first = src->msb_first;
pBN->msw_first = src->msw_first;
pBN->nbytes = src->nbytes;
memcpy( pBN->bytes, src->bytes, src->nbytes );
*dst = pBN;
return Status_OK;
}
/* --------------------- */
void my_printbignum ( FILE *f, const char *prefix, const struct NFast_Bignum *pBN )
{
char buf[MAXBIGNUMBITS/4+1];
int rc;
rc = my_bignum2char(buf, sizeof(buf), pBN, NULL, NULL, NULL);
if ( rc != Status_OK ) strcpy(buf, "<invalid length>");
fprintf( f, "%s=\n %s\n", prefix, buf );
}
/* --------------------- */
int my_compare ( const struct NFast_Bignum *pA,
const struct NFast_Bignum *pB )
{
int i, aa, bb;
aa=getbytelen(pA);
bb=getbytelen(pB);
if ( aa != bb ) return (aa > bb) ? 1 : -1;
i=aa;
while ( i-- > 0 )
{
aa=getbyte(pA,i);
bb=getbyte(pB,i);
if ( aa != bb ) return (aa > bb) ? 1 : -1;
}
return 0;
}
/* --------------------- */
#endif // HSM

View File

@ -0,0 +1,177 @@
/** \file simplebignum.h Simple bignum support
*
* Illustrates simple easy-to-use bignumber format. This provides a
* definition of the \ref NFast_Bignum structure which can be used
* in applications which do not already have an equivalent structure
* defined.
*
* See also:
* - \ref nfastapp.h
* - \ref gsbignum
*/
/* Copyright 1999-2002 nCipher Corporation Limited.
*
* This example source code is provided for your information and
* assistance. See the file LICENCE.TXT for details and the
* terms and conditions of the licence which governs the use of the
* source code. By using such source code you will be accepting these
* terms and conditions. If you do not wish to accept these terms and
* conditions, DO NOT OPEN THE FILE OR USE THE SOURCE CODE.
*
* Note that there is NO WARRANTY.
*
*/
#ifndef CR_HSM_BIGNUM_H
#define CR_HSM_BIGNUM_H
#include "nfastapp.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifndef MAXBIGNUMBITS
/** Maximum size of a bignum in bits */
#define MAXBIGNUMBITS 16384
#endif
/** Structure of a bignum
*
* \ref M_Bignum will be a pointer to this structure. */
struct NFast_Bignum {
/** Byte order
*
* If this is set then each 32-bit word in the bignum is big-endian
* (most-significant byte first); otherwise it is little-endian
* (least-significant byte first). */
int msb_first;
/** Word order
*
* If this is set then 32-bit words in the bignum are in big-endian order
* (most-significant word first); otherwise they are in little-endian
* order (least-significant words first).
*/
int msw_first;
/** Number of bytes */
int nbytes;
/** Bignum data
*
* Only the first \a nbytes are used. */
unsigned char bytes[MAXBIGNUMBITS/8];
};
/* Bignum send & receive upcalls -------------------------- */
/* As well as being used directly as upcalls,
these can be used to create bignums from data blocks and
extract data from bignums.
*/
/** Bignum receive upcall
*
* See \ref NFast_BignumReceiveUpcall_t */
extern int my_bignumreceiveupcall(struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx,
M_Bignum *bignum, int nbytes,
const void *source,
int msbitfirst, int mswordfirst);
/** Bignum send-length upcall
*
* See \ref NFast_BignumSendLenUpcall_t */
extern int my_bignumsendlenupcall(struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx,
const M_Bignum *bignum, int *nbytes_r);
/** Bignum send upcall
*
* See \ref NFast_BignumSendUpcall_t */
extern int my_bignumsendupcall(struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx,
const M_Bignum *bignum, int nbytes,
void *dest, int msbitfirst, int mswordfirst);
/** Free bignum upcall
*
* See \ref NFast_BignumFreeUpcall_t */
extern void my_bignumfreeupcall(struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx,
M_Bignum *bignum);
/** Bignum format upcall
*
* See \ref NFast_BignumFormatUpcall_t */
extern int my_bignumformatupcall(struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx,
int *msbitfirst_io, int *mswordfirst_io);
/** Structure containing bignum upcalls
*
* See \ref NFastAppInitArgs and \ref NFAPP_IF_BIGNUM */
extern NFast_BignumUpcalls my_upcalls;
/* Bignum utility functions ----------------------------- */
/** Convert a hex string to a bignum
*
* \return Status code
*/
extern int my_char2bignum ( struct NFast_Bignum **ppBN_out,
const char *text,
struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx );
// convert binary to NFast_Bignum
extern int my_bin2bignum ( struct NFast_Bignum **ppBN_out,
struct NFast_Application *app,
const unsigned char *bin, const int size );
/** Convert a bignum to a hex string
*
* \return Status code
*/
extern int my_bignum2char ( char *buf, int buflen,
const struct NFast_Bignum *pBN,
struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx );
// convert NFast_Bignum to binary
int my_bignum2bin ( unsigned char *buf, int buflen,
struct NFast_Application *app,
const struct NFast_Bignum *pBN );
// NFast_Bignum copy
int my_bignumCopy( struct NFast_Bignum **dst,
const struct NFast_Bignum *src,
struct NFast_Application *app );
/** Print a bignum in hex to a file
*
* Call ferror() to test for output errors.
*/
extern void my_printbignum ( FILE *f,
const char *prefix, const struct NFast_Bignum *pBN );
/** Compare two bignums
*
* \return -1, 0 or 1 if A\<B, A=B or A\>B
*/
extern int my_compare ( const struct NFast_Bignum *pA,
const struct NFast_Bignum *pB );
#ifdef __cplusplus
}
#endif
#endif // CR_HSM_BIGNUM_H

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,141 @@
/* ====================================================================
* Copyright (c) 1998-2008 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#ifndef _CR_GENERATE_ID_HSM_CODE_H_
#define _CR_GENERATE_ID_HSM_CODE_H_
#include "cr_hsm_bignum.h"
#ifdef __cplusplus
extern "C" {
#endif
#define HSM_MODULE_ID ( 1)
// functions
int hsm_initialize( void );
int hsm_finalize( void );
int hsm_reset_module( void );
int hsm_generate_random( unsigned char *buf, int bytes );
int hsm_get_rtc( time_t *time );
int hsm_aes_encrypt( unsigned char *dst_buf, unsigned char *org_buf, int size, unsigned char bonding_option, unsigned char *pIV );
int hsm_aes_decrypt( unsigned char *dst_buf, unsigned char *org_buf, int size, unsigned char bonding_option, unsigned char *pIV );
int hsm_rsa_encrypt( unsigned char *dst_buf, unsigned char *org_buf, int size, unsigned char bonding_option );
int hsm_rsa_decrypt( unsigned char *dst_buf, unsigned char *org_buf, int size, unsigned char bonding_option );
int hsm_ecdsa_sign( unsigned char *sign_buf, unsigned char *data_buf, unsigned char bonding_option );
#ifdef __cplusplus
}
#endif
#endif /* _CR_GENERATE_ID_HSM_CODE_H_ */

View File

@ -0,0 +1,281 @@
/* ====================================================================
* Copyright (c) 1998-2008 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <time.h>
#include <sys/time.h>
#include <string.h>
#ifdef USE_HSM
#include "cr_hsm_code.h"
#endif // USE_HSM
#include "cr_generate_id.h"
#include "cr_generate_id_private.h"
typedef struct
{
u8 stop;
u8 position;
u8 emptySize;
u8 stack[ CALL_STACK_SIZE ];
}
errorInfoStruct;
static errorInfoStruct errorInfo;
// タイムスタンプを取得してセット
int GetTimestamp( u8 *pYear, u8 *pMonth, u8 *pMday, u8 *pHour, u8 *pMin, u8 *pSec, time_t *pTime)
{
int ret_code = CR_GENID_SUCCESS;
struct tm *tm_time;
struct timeval tv;
#ifdef USE_HSM
ret_code = hsm_get_rtc( &tv.tv_sec );
if( ret_code != CR_GENID_SUCCESS ) {
SetErrorInfo( __FUNCTION__, __LINE__ );
return ret_code;
}
#else // !USE_HSM
gettimeofday( &tv, NULL );
#endif // USE_HSM
tm_time = gmtime( &tv.tv_sec );
*pYear = (u8)tm_time->tm_year;
*pMonth = (u8)tm_time->tm_mon + 1;
*pMday = (u8)tm_time->tm_mday;
*pHour = (u8)tm_time->tm_hour;
*pMin = (u8)tm_time->tm_min;
*pSec = (u8)tm_time->tm_sec;
*pTime = tv.tv_sec;
#if 0
{
struct tm tm2;
time_t t2;
memset( &tm2, 0, sizeof(tm2) );
tm2.tm_year = *pYear;
tm2.tm_mon = *pMonth - 1;
tm2.tm_mday = *pMday;
tm2.tm_hour = *pHour;
tm2.tm_min = *pMin;
tm2.tm_sec = *pSec;
tm2.tm_isdst = 0; // 夏時間 ここでは0無効にする。
t2 = gmt_mktime( &tm2 );
printf( "time_t = %08x\n", (int)t );
printf( "mktime = %08x\n", (int)t2 );
}
#endif
#ifdef DEBUG_PRINT
if( cr_print_flag ) {
printf("GMT:%d-%02d-%02d %02d:%02d:%02d\n",
*pYear+1900,
*pMonth,
*pMday,
*pHour,
*pMin,
*pSec
);
}
#endif /* DEBUG_PRINT */
return ret_code;
}
#if 0
static time_t gmt_mktime( struct tm *tm_time )
{
time_t ret;
char *tz;
tz = getenv("TZ");
setenv("TZ", "", 1); // setenv, unsetenv はcygwinでは見つからない
tzset();
ret = mktime(tm_time); // mktime は、localtimeでの変換になるため、timezoneの処理が必要
if (tz)
setenv("TZ", tz, 1);
else
unsetenv("TZ");
tzset();
return ret;
}
#endif
// 乱数を生成してセット
int GenerateRandom( u8 *pDst, int length )
{
int ret_code = CR_GENID_SUCCESS;
#ifdef USE_HSM
ret_code = hsm_generate_random( pDst, CR_RANDOM_LENGTH );
if ( ret_code != CR_GENID_SUCCESS )
{
SetErrorInfo( __FUNCTION__, __LINE__ );
}
#else // !USE_HSM
int i;
for( i = 0 ; i < length; i++ ) {
*pDst++ = (u8)rand();
}
#endif // USE_HSM
return ret_code;
}
void InitErrorInfo( void )
{
memset( &errorInfo, 0, sizeof( errorInfo ) );
errorInfo.emptySize = CALL_STACK_SIZE;
} // InitErrorInfo
// エラー情報の記録
void SetErrorInfo( const char *funcName, u32 line )
{
if ( !errorInfo.stop )
{
int len;
char str[64];
snprintf( str, sizeof( str ), "%s:%d ", funcName, (int)line );
len = strlen( str );
if ( len > errorInfo.emptySize )
{
errorInfo.stop = 1;
len = errorInfo.emptySize;
}
memcpy( &errorInfo.stack[ errorInfo.position ], str, len );
errorInfo.position += len;
errorInfo.emptySize -= len;
}
#if 0
else
{
printf( "Stack is full!\n" );
}
#endif
} // StoreErrorInfo
// エラー情報の取得
void GetErrorInfo( char *stack, u8 *size )
{
memcpy( stack, errorInfo.stack, CALL_STACK_SIZE );
*size = CALL_STACK_SIZE - errorInfo.emptySize;
} // GetErrorInfo

View File

@ -0,0 +1,310 @@
/* ====================================================================
* Copyright (c) 1998-2008 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <time.h>
#include <sys/time.h>
#include <string.h>
#include <openssl/err.h>
#include <openssl/ec.h>
#include <openssl/ecdsa.h>
#include "cr_generate_id.h"
#include "cr_generate_id_private.h"
static int generate_EC_private_key( EC_KEY *eckey, u8 *privKey );
static int generate_EC_public_key( EC_KEY *eckey );
// ECCキーペアの生成
int GenarateECCKeyPair( EC_KEY **ppECkey, u8 *pECPrivkey )
{
int openssl_result = 0;
// 楕円を選択 ( NID_X9_62_prime256v1 -> 32bytesまで、 NID_sect571r1 -> 71bytesまで 署名にデータを含められる )
*ppECkey = EC_KEY_new_by_curve_name( NID_sect233r1 );
if( *ppECkey == NULL )
{
SetErrorInfo( __FUNCTION__, __LINE__ );
return CR_GENID_ERROR_ECC_KEY_NEW;
}
// 秘密鍵生成
openssl_result = generate_EC_private_key( *ppECkey, pECPrivkey );
if( openssl_result != 0 )
{
SetErrorInfo( __FUNCTION__, __LINE__ );
return CR_GENID_ERROR_ECC_GENERATE_PRIVATE_KEY;
}
// 公開鍵生成
openssl_result = generate_EC_public_key( *ppECkey );
if ( openssl_result == 0 )
{
SetErrorInfo( __FUNCTION__, __LINE__ );
return CR_GENID_ERROR_ECC_GENERATE_PUBLIC_KEY;
}
// ASN.1 形式指定フラグをセットする
// (これをセットしないと色々変なフィールドが入ってしまうため)
EC_KEY_set_asn1_flag( *ppECkey, 1 );
return CR_GENID_SUCCESS;
}
// EC秘密鍵を生成
static int generate_EC_private_key( EC_KEY *eckey, u8 *privKey )
{
int ret_code = CR_GENID_SUCCESS;
BIGNUM *bn_privkey = NULL;
// 乱数を取得して、秘密鍵にする。
ret_code = GenerateRandom( privKey, EC_PRIVATE_KEY_LENGTH );
if ( ret_code != CR_GENID_SUCCESS ) {
SetErrorInfo( __FUNCTION__, __LINE__ );
return ret_code;
}
// ECC233 で30バイトだけ利用するので、後ろ2バイトは0で埋める
// (DER(BER) が big endian なので、ここでは先頭2byte)
// 最後に3バイト目の7ビットをクリアする
privKey[ 0 ] = 0;
privKey[ 1 ] = 0;
privKey[ 2 ] &= 0x01;
// 生成した秘密鍵をBNに変換して、eckeyにセット
// ※bn_privkeyは、生成に成功した場合、ここではBN_freeされずにeckey要素の一つになって引き渡されます。
bn_privkey = BN_new();
if( bn_privkey == NULL )
{
SetErrorInfo( __FUNCTION__, __LINE__ );
return CR_GENID_ERROR_BN_NEW;
}
BN_init( bn_privkey ); /* memset(a,0,sizeof(BIGNUM)); */
(void)BN_bin2bn( privKey, EC_PRIVATE_KEY_LENGTH, bn_privkey );
eckey->priv_key = bn_privkey;
DEBUG_PRINT_ARRAY( "ec private key:", (const char *)privKey, EC_PRIVATE_KEY_LENGTH );
return ret_code;
} // generate_EC_private_key
// EC公開鍵を生成 ※opensslコードから抜粋し、一部改変
static int generate_EC_public_key( EC_KEY *eckey )
{
int ok = 0;
BN_CTX *ctx = NULL;
BIGNUM *priv_key = NULL, *order = NULL;
EC_POINT *pub_key = NULL;
if (!eckey || !eckey->group)
{
ECerr(EC_F_EC_KEY_GENERATE_KEY, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if ((order = BN_new()) == NULL) goto err;
if ((ctx = BN_CTX_new()) == NULL) goto err;
if (eckey->priv_key == NULL)
{
priv_key = BN_new();
if (priv_key == NULL) {
goto err;
}
}
else {
priv_key = eckey->priv_key;
}
if (!EC_GROUP_get_order(eckey->group, order, ctx)) {
goto err;
}
#if 0 // 2009.09.25 これが実行されると、秘密鍵が乱数化されてしまい、指定した秘密鍵と変わってしまうためコメントアウトする。
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
// 鍵ペアをECDSAで検証
int TestECDSA( EC_KEY *pECkey )
{
#define CR_ECDSA_BUF_SIZE 29
#define CR_ECDSA_SIGN_BUF_SIZE 256
unsigned char ecdsa_test_buf[CR_ECDSA_BUF_SIZE];
unsigned char ecdsasig[CR_ECDSA_SIGN_BUF_SIZE];
unsigned int ecdsasiglen = 0;
int openssl_result = 0;
int i;
// ダミー署名データ作成
for( i = 0 ; i < CR_ECDSA_BUF_SIZE ; i++ ) {
ecdsa_test_buf[i] = (u8)(0xff & i );
}
memset( ecdsasig, 0, CR_ECDSA_SIGN_BUF_SIZE );
openssl_result = ECDSA_sign( 0, ecdsa_test_buf, CR_ECDSA_BUF_SIZE, ecdsasig,
&ecdsasiglen, pECkey );
if (openssl_result == 0) {
SetErrorInfo( __FUNCTION__, __LINE__ );
return CR_GENID_ERROR_ECDSA_SIGN;
}
openssl_result = ECDSA_verify( 0, ecdsa_test_buf, CR_ECDSA_BUF_SIZE, ecdsasig, ecdsasiglen, pECkey );
if( openssl_result != 1) {
SetErrorInfo( __FUNCTION__, __LINE__ );
return CR_GENID_ERROR_ECDSA_VERIFY;
}
return CR_GENID_SUCCESS;
}

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,4 @@
-----BEGIN PUBLIC KEY-----
MFIwEAYHKoZIzj0CAQYFK4EEABsDPgAEANkB/eVVYNkyMyWTUwq6Y6MUUJYtTHLy
muag+2u/Ab7Ww4xkEaJs06yqMZr1Z6SFZ9aTZwSL8KCeLSU1
-----END PUBLIC KEY-----

View File

@ -0,0 +1 @@
űćŁúp)v$ ëůFݸě

View File

@ -0,0 +1 @@
eMHë{ôéÜ<C3A9>:°˙<C2B0>D

View File

@ -0,0 +1,8 @@
-----BEGIN EC PARAMETERS-----
BgUrgQQAGw==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MG0CAQEEHSzzSTwenLOaRVfl0j29t4tzFtMIOu4hzZC27rpnoAcGBSuBBAAboUAD
PgAEAGJ0KjqVxyg9Hp40gCb+CiP6LjmqBafdqrIZ4hw+AHBz9/5KU9VoehZfyyPk
2xCYrrrOlursxJwI8tUg
-----END EC PRIVATE KEY-----

Binary file not shown.

View File

@ -0,0 +1,4 @@
-----BEGIN PUBLIC KEY-----
MFIwEAYHKoZIzj0CAQYFK4EEABsDPgAEAGJ0KjqVxyg9Hp40gCb+CiP6LjmqBafd
qrIZ4hw+AHBz9/5KU9VoehZfyyPk2xCYrrrOlursxJwI8tUg
-----END PUBLIC KEY-----

View File

@ -0,0 +1 @@
<EFBFBD>拀惯耄}Wp~n煯<

View File

@ -0,0 +1 @@
<EFBFBD><EFBFBD><EFBFBD><1D><>L<EFBFBD>C<EFBFBD>k4m<34><6D><EFBFBD>

View File

@ -0,0 +1,128 @@
# Simple makefile for example programs under gcc
#
# Build these with 'make -f Makefile-examples'
#
# Copyright 1997-2008 nCipher Corporation Limited.
#
# This file is example source code. It is provided for your
# information and assistance. See the file LICENCE.TXT for details and the
# terms and conditions of the licence which governs the use of the
# source code. By using such source code you will be accepting these
# terms and conditions. If you do not wish to accept these terms and
# conditions, DO NOT OPEN THE FILE OR USE THE SOURCE CODE.
#
# Note that there is NO WARRANTY.
#
# -------------------------------
#
# Set NFAST_PATH to installation directory of the headers and libraries
NFAST_PATH= /opt/nfast
# Developer tools installation
NFAST_DEV_PATH= $(NFAST_PATH)/c/ctd/gcc
NFAST_EXAMPLES_PATH= $(NFAST_PATH)/c/ctd/examples
# We now have a single library directory, not one per component, in an
# installation, but may be using different paths per component in
# testing.
LIBPATH_SWORLD= $(NFAST_DEV_PATH)/lib
LIBPATH_HILIBS= $(NFAST_DEV_PATH)/lib
LIBPATH_NFLOG= $(NFAST_DEV_PATH)/lib
LIBPATH_CUTILS= $(NFAST_DEV_PATH)/lib
INC_SWORLD= $(NFAST_DEV_PATH)/include/sworld
INC_HILIBS= $(NFAST_DEV_PATH)/include/hilibs
INC_NFLOG= $(NFAST_DEV_PATH)/include/nflog
INC_CUTILS= $(NFAST_DEV_PATH)/include/cutils
EXAMPLES_SWORLD= $(NFAST_EXAMPLES_PATH)/sworld
EXAMPLES_HILIBS= $(NFAST_EXAMPLES_PATH)/hilibs
EXAMPLES_NFLOG= $(NFAST_EXAMPLES_PATH)/nflog
EXAMPLES_CUTILS= $(NFAST_EXAMPLES_PATH)/cutils
# openssl
OPENSSL_DIR = ../openssl-0.9.8k
# Where the source lives
SRCPATH = .
REFPATH = $(NFAST_PATH)/c/ctd/examples/nfuser/build-gcc-lib
CC = gcc
CPPFLAGS= -I$(SRCPATH) \
-I$(INC_SWORLD) \
-I$(INC_HILIBS) \
-I$(INC_NFLOG) \
-I$(INC_CUTILS) \
-I$(EXAMPLES_SWORLD) \
-I$(EXAMPLES_HILIBS) \
-I$(EXAMPLES_NFLOG) \
-I$(EXAMPLES_CUTILS) \
$(XCPPFLAGS) \
-I$(OPENSSL_DIR)/include \
-I$(OPENSSL_DIR)/crypto/ec \
CFLAGS= -g -O2 -Wall -Wwrite-strings -Wstrict-prototypes -Wmissing-prototypes -D_GNU_SOURCE -Wno-nonnull -O2 -fPIC -Wno-nonnull $(XCFLAGS)
# -Werror -> N/A
LINK= gcc
LDFLAGS= $(XLDFLAGS) -L$(OPENSSL_DIR)
LDFLAGS_THREADED= $(LDFLAGS) $(XLDFLAGS_THREADED)
LDLIBS= $(XLDLIBS) -lcrypto -lssl -ldl -lnsl
LDLIBS_THREADED= $(XLDLIBS_THREADED) -lpthread $(LDLIBS)
# Targets ------------------------
all: simple
XLDLIBS= $(LIBPATH_SWORLD)/librqcard.a \
$(LIBPATH_SWORLD)/libnfkm.a \
$(LIBPATH_HILIBS)/libnfstub.a \
$(LIBPATH_NFLOG)/libnflog.a \
$(LIBPATH_CUTILS)/libcutils.a -lm
COMMON_OBJECTS = $(REFPATH)/nfutil.o $(REFPATH)/nfopt.o $(REFPATH)/getdate.o $(REFPATH)/report.o $(REFPATH)/report-usage.o $(REFPATH)/nftypes.o $(REFPATH)/tokenise.o
EXTRA_OBJECTS = my_hsm_bignum.o my_hsm_alloc.o
COMMON_HEADERS= $(REFPATH)/nfutil.h $(REFPATH)/nfopt.h $(REFPATH)/nftypes.h $(REFPATH)/tokenise.h
# We supply an up-to-date getdate.c in the cutils component. Prevent it
# from being automatically rebuilt in the case where getdate.y's mtime
# is (usually accidentally) newer; if you want to modify it, do so in
# cutils.
$(SRCPATH)/getdate.c: ;
# Simple (non-threaded) programs ------------
my_hsm_bignum.o: my_hsm_bignum.c
$(CC) $(CFLAGS) $(CPPFLAGS) -o my_hsm_bignum.o -c my_hsm_bignum.c
my_hsm_alloc.o: my_hsm_alloc.c
$(CC) $(CFLAGS) $(CPPFLAGS) -o my_hsm_alloc.o -c my_hsm_alloc.c
import_aes_key: import_aes_key.c $(EXTRA_OBJECTS)
$(CC) $(CFLAGS) $(CPPFLAGS) -o import_aes_key import_aes_key.c $(COMMON_OBJECTS) $(EXTRA_OBJECTS) $(LDLIBS)
import_rsa_keypair: import_rsa_keypair.c $(EXTRA_OBJECTS)
$(CC) $(CFLAGS) $(CPPFLAGS) -o import_rsa_keypair import_rsa_keypair.c $(COMMON_OBJECTS) $(EXTRA_OBJECTS) $(LDLIBS)
import_ecdsa_keypair: import_ecdsa_keypair.c $(EXTRA_OBJECTS)
$(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) -o import_ecdsa_keypair import_ecdsa_keypair.c $(COMMON_OBJECTS) $(EXTRA_OBJECTS) $(LDLIBS)
# All single-threaded targets
TARGETS_SIMPLE= \
import_aes_key \
import_rsa_keypair \
import_ecdsa_keypair \
simple: $(TARGETS_SIMPLE)
# Secondary targets ------------------------
clean:
rm -f *.o
rm -f $(TARGETS_SIMPLE)

View File

@ -0,0 +1,468 @@
// import key (+ encrypt, decrypt) test for nShield
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "nfastapp.h"
#include "nfkm.h"
#include "rqcard-applic.h"
#include "rqcard-fips.h"
#include "my_hsm_bignum.h"
#include "my_hsm_alloc.h"
#define MODULE_ID 1
#define DATA_LEN 256 // bytes
#define KEY_FILE "/opt/nfast/work/ctr_eFuse/hsm_utils/real_key/dev/eFuse_aesKey.bin"
const NFKM_KeyIdent keyident = { (char*)"simple", (char*)"efuse-aes-dev" };
//#define CARD_PROTECT
//#define EXPORT_KEY
//#define STRICT_FIPS
unsigned char aes_key_data[32];
typedef struct _NFast_Call_Context
{
int notused;
}
NFast_Call_Context;
NFast_Call_Context context;
typedef struct NFast_Transaction_Context
{
M_Command cmd;
M_Reply reply;
}
NFast_Transaction_Context;
NFast_Transaction_Context tc;
int main( int argc, char *argv[] )
{
int i;
int result = 0;
NFast_AppHandle handle;
NFastApp_Connection nc;
NFKM_WorldInfo *world = NULL;
RQCard card;
RQCard_FIPS fips;
M_KeyID ltid = 0; // the cardset loaded into the module
M_KeyID keyid;
NFKM_Key *keyinfo;
NFKM_CardSet *cardset = NULL;
FILE *fp;
unsigned char aesData[16];
// key data open & read
printf( "filename : %s\n", KEY_FILE );
fp = fopen( KEY_FILE, "rb" );
if ( !fp )
{
printf( "error : fopen\n" );
return 0;
}
fread( aesData, 16, 1, fp );
for( i = 0; i < 16; i++ )
printf( "%02X ", aesData[i] );
printf( "\n" );
// init nFast
result = NFastApp_InitEx( &handle, NULL, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFastApp_InitEx\n", result );
return 0;
}
// connecting to hardserver
result = NFastApp_Connect( handle, &nc, 0, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFastApp_Connect\n", result );
return 0;
}
// set bignum upcalls setting
result = NFastApp_SetBignumUpcalls(
handle,
my_bignumreceiveupcall,
my_bignumsendlenupcall,
my_bignumsendupcall,
my_bignumfreeupcall,
my_bignumformatupcall,
NULL );
// NFKM getinfo
result = NFKM_getinfo( handle, &world, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_getinfo\n", result );
return 0;
}
// init card-loading lib
result = RQCard_init( &card, handle, nc, world, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : RQCard_init\n", result );
return 0;
}
// init FIPS state
result = RQCard_fips_init( &card, &fips );
if ( result != Status_OK )
{
printf( "error(%d) : RQCard_fips_init\n", result );
return 0;
}
// ui select
//result = RQCard_ui_default( &card );
result = RQCard_ui_scroll( &card );
if ( result != Status_OK )
{
printf( "error(%d) : RQCard_ui_xxx\n", result );
return 0;
}
// get strict-FIPS authorization
#ifdef STRICT_FIPS
NFKM_FIPS140AuthHandle fipsHandle;
M_SlotID slotId;
result = RQCard_fips_get( &fips, 1, &fipsHandle, &slotId );
if ( result != Status_OK )
{
printf( "error(%d) : RQCard_fips_get\n", result );
return 0;
}
if ( fipsHandle == NULL )
{
printf( "this sworld isn't strict-FIPS.\n" );
}
#endif
#ifdef CARD_PROTECT
// list cardsets
int card_num;
NFKM_CardSetIdent *cardident = NULL;
result = NFKM_listcardsets( handle, &card_num, &cardident, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_listcardsets\n", result );
return 0;
}
// find cardsets
result = NFKM_findcardset( handle, cardident, &cardset, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_findcardset\n", result );
return 0;
}
// load cardset
result = RQCard_logic_ocs_specific( &card, &(cardset->hkltu), "Load Cardset" );
if ( result != Status_OK )
{
printf( "error(%d) : RQCard_logic_ocs_specific\n", result );
return 0;
}
// use specific module : #1
// important!! : if you set resultplace=NULL, abort. (possibility is 100%)
result = RQCard_whichmodule_specific( &card, world->modules[0]->module, &ltid );
if ( result != Status_OK )
{
printf( "error(%d) : RQCard_whichmodule_specific\n", result );
return 0;
}
// wait event loop
result = card.uf->eventloop( &card );
if ( result != Status_OK )
{
printf( "error(%d) : card module event loop\n", result );
return 0;
}
#endif
// get usable module
NFKM_ModuleInfo *moduleinfo = world->modules[0];
result = NFKM_getusablemodule( world, MODULE_ID, &moduleinfo );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_getusablemodule\n", result );
return 0;
}
// make ACL
NFKM_MakeACLParams map;
NFKM_MakeBlobsParams mbp;
memset( &map, 0, sizeof( map ) );
if ( cardset != NULL )
map.f = NFKM_NKF_RecoveryEnabled | NFKM_NKF_ProtectionCardSet;
else
map.f = NFKM_NKF_RecoveryEnabled | NFKM_NKF_ProtectionModule;
map.op_base = ( NFKM_DEFOPPERMS_ENCRYPT | NFKM_DEFOPPERMS_DECRYPT );
map.cs = cardset;
result = NFKM_newkey_makeaclx( handle, nc, world, &map,
&(tc.cmd.args.import.acl), NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_newkey_makeaclx\n", result );
return 0;
}
// import key
tc.cmd.cmd = Cmd_Import;
tc.cmd.args.import.module = MODULE_ID;
tc.cmd.args.import.data.type = KeyType_Rijndael;
tc.cmd.args.import.data.data.random.k.len = 16;
tc.cmd.args.import.data.data.random.k.ptr = aesData;
result = NFastApp_Transact( nc, NULL, &(tc.cmd), &(tc.reply), NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_newkey_makeaclx\n", result );
return 0;
}
// make blobs
NFKM_Key reg_key;
memset( &mbp, 0, sizeof( mbp ) );
memset( &reg_key, 0, sizeof( reg_key ) );
mbp.f = map.f;
mbp.kpriv = tc.reply.reply.import.key;
mbp.lt = ltid;
mbp.cs = cardset;
reg_key.v = Key__maxversion; // TORIAEZU Version Max (8)
reg_key.name = keyident.ident;
reg_key.appname = keyident.appname;
reg_key.ident = keyident.ident;
time( &(reg_key.gentime) );
result = NFKM_newkey_makeblobsx( handle, nc, world, &mbp, &reg_key, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_newkey_makeblobsx\n", result );
return 0;
}
// record key to disk
result = NFKM_recordkey( handle, &reg_key, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_recordkey\n", result );
return 0;
}
printf( "record key success : appname=%s, ident=%s\n",
keyident.appname, keyident.ident );
// destroy key
result = NFKM_cmd_destroy( handle, nc, 0, tc.reply.reply.import.key,
"import.key", NULL );
// list key
#if 0
int key_num;
NFKM_KeyIdent *keylist = NULL;
result = NFKM_listkeys( handle, &key_num, &keylist, "simple", NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_listkeys\n", result );
return 0;
}
NFKM_KeyIdent **tkp = &keylist;
for ( i = 0; i < key_num; i++ )
{
printf( "appname : %s, ident : %s\n", tkp[i]->appname, tkp[i]->ident );
}
#endif
// find key
result = NFKM_findkey( handle, keyident, &keyinfo, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_findkey\n", result );
}
// load blob
M_ByteBlock *blobptr;
if ( keyinfo->pubblob.len)
blobptr = &keyinfo->pubblob;
else
{
printf( "aes is symmetric key!\n" );
blobptr = &keyinfo->privblob;
}
result = NFKM_cmd_loadblob( handle, nc,
moduleinfo->module, blobptr, ltid, &keyid, "loading key blob", NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_cmd_loadblob\n", result );
return 0;
}
#if 0
// get key info
tc.cmd.cmd = Cmd_GetKeyInfo;
tc.cmd.args.getkeyinfo.key = keyid;
result = NFastApp_Transact( nc, NULL, &(tc.cmd), &(tc.reply), NULL );
if ( result != Status_OK )
{
printf( "error(%d) : FastApp_Transact(Cmd_GetKeyInfo)\n", result );
}
// if type == 30 then Rijndael(AES)
printf( "keytype : %d\n", tc.reply.reply.getkeyinfo.type );
#endif
// encrypt & dectypt test
{
M_ByteBlock enc_input, dec_input;
M_ByteBlock enc_output, dec_output;
M_IV base_iv, enc_iv, dec_iv;
// data setting
enc_input.len = DATA_LEN;
enc_input.ptr = (unsigned char*)malloc( DATA_LEN );
for ( i = 0; i < enc_input.len; i++ )
enc_input.ptr[i] = i;
base_iv.mech = Mech_RijndaelmCBCpNONE;
for ( i = 0; i < 16; i++ )
base_iv.iv.generic128.iv.bytes[i] = i;
enc_iv = base_iv;
dec_iv = base_iv;
// encrypt : my ver
tc.cmd.cmd = Cmd_Encrypt;
tc.cmd.args.encrypt.key = keyid;
tc.cmd.args.encrypt.mech = Mech_RijndaelmCBCpNONE;
tc.cmd.args.encrypt.plain.type = PlainTextType_Bytes;
tc.cmd.args.encrypt.plain.data.bytes.data = enc_input;
tc.cmd.args.encrypt.flags = Cmd_Encrypt_Args_flags_given_iv_present;
tc.cmd.args.encrypt.given_iv = &enc_iv;
result = NFastApp_Transact( nc, NULL, &(tc.cmd), &(tc.reply), NULL );
if ( result != Status_OK )
{
printf( "error(%d) : FastApp_Transact(Cmd_Encrypt)\n", result );
return 0;
}
result = tc.reply.status;
if ( result != Status_OK )
{
printf( "error(%d) : reply.status(Cmd_Encrypt)\n", result );
return 0;
}
enc_output.len = tc.reply.reply.encrypt.cipher.data.generic128.cipher.len;
if ( enc_output.len != DATA_LEN )
{
printf( "error : output data size isn't %d bytes(Cmd_Encrypt)\n", (int)enc_output.len );
return 0;
}
enc_output.ptr = (unsigned char*)malloc( enc_output.len );
memcpy( enc_output.ptr,
tc.reply.reply.encrypt.cipher.data.generic128.cipher.ptr,
enc_output.len );
printf( "encrypt ok.\n" );
dec_input.len = enc_output.len;
dec_input.ptr = (unsigned char*)malloc( dec_input.len );
memcpy( dec_input.ptr, enc_output.ptr, DATA_LEN );
NFastApp_Free_Reply( handle, NULL, NULL, &(tc.reply) );
// decrypt : my ver
tc.cmd.cmd = Cmd_Decrypt;
tc.cmd.args.decrypt.flags = 0;
tc.cmd.args.decrypt.key = keyid;
tc.cmd.args.decrypt.mech = Mech_RijndaelmCBCpNONE;
tc.cmd.args.decrypt.cipher.mech = Mech_RijndaelmCBCpNONE;
tc.cmd.args.decrypt.cipher.data.generic128.cipher = dec_input;
tc.cmd.args.decrypt.cipher.iv = dec_iv.iv;
tc.cmd.args.decrypt.reply_type = PlainTextType_Bytes;
result = NFastApp_Transact( nc, NULL, &(tc.cmd), &(tc.reply), NULL );
if ( result != Status_OK )
{
printf( "error(%d) : FastApp_Transact(Cmd_Decrypt)\n", result );
return 0;
}
result = tc.reply.status;
if ( result != Status_OK )
{
printf( "error(%d) : reply.status(Cmd_Decrypt)\n", result );
return 0;
}
dec_output.len = tc.reply.reply.decrypt.plain.data.bytes.data.len;
if ( dec_output.len != DATA_LEN )
{
printf( "error : output size isn't %d bytes(Cmd_Decrypt)\n", (int)enc_output.len );
return 0;
}
dec_output.ptr = (unsigned char*)malloc( dec_output.len );
memcpy( dec_output.ptr,
tc.reply.reply.decrypt.plain.data.bytes.data.ptr,
dec_output.len );
printf( "decrypt ok.\n" );
NFastApp_Free_Reply( handle, NULL, NULL, &(tc.reply) );
// key destroy
memset( &(tc.cmd), 0, sizeof( tc.cmd ) ); // fail if NFastApp_Free_Command
tc.cmd.cmd = Cmd_Destroy;
tc.cmd.args.destroy.key = keyid;
result = NFastApp_Transact( nc, NULL, &(tc.cmd), &(tc.reply), NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFastApp_Transact(Cmd_Destroy)\n", result );
return 0;
}
NFastApp_Free_Reply( handle, NULL, NULL, &(tc.reply) );
// data show
printf( "enc_input : (%d bytes)", (int)enc_input.len );
for ( i = 0; i < enc_input.len; i++ )
{
if ( i % 16 == 0 )
printf( "\n" );
printf( "%02X ", enc_input.ptr[i] );
}
printf( "\n" );
printf( "\nenc_output : (%d bytes)", (int)enc_output.len );
for ( i = 0; i < enc_output.len; i++ )
{
if ( i % 16 == 0 )
printf( "\n" );
printf( "%02X ", enc_output.ptr[i] );
}
printf( "\n" );
printf( "\ndec_output : (%d bytes)", (int)dec_output.len );
for ( i = 0; i < dec_output.len; i++ )
{
if ( i % 16 == 0 )
printf( "\n" );
printf( "%02X ", dec_output.ptr[i] );
}
printf( "\n" );
} // encrypt & decrypt
// end processing
RQCard_fips_free( &card, &fips );
RQCard_destroy( &card );
NFKM_freekey( handle, keyinfo, NULL );
NFKM_freeinfo( handle, &world, NULL );
NFastApp_Disconnect( nc, NULL );
NFastApp_Finish( handle, NULL );
return 0;
} // main

View File

@ -0,0 +1,968 @@
// import key (+ encrypt, decrypt) test for nShield
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// openssl
#include <openssl/err.h>
#include <openssl/bn.h>
#include <openssl/sha.h>
#include <openssl/ec.h>
#include "ec_lcl.h"
#include <openssl/x509.h>
#include <openssl/aes.h>
#include <openssl/pem.h>
#include "nfastapp.h"
#include "nfkm.h"
#include "rqcard-applic.h"
#include "rqcard-fips.h"
#include "my_hsm_bignum.h"
#include "my_hsm_alloc.h"
#define PRIV_KEY_FILE "/opt/nfast/work/ctr_eFuse/hsm_utils/real_key/hoge/NintendoCTR2_privkey_prod.der"
#define PUB_KEY_FILE "/opt/nfast/work/ctr_eFuse/hsm_utils/real_key/hoge/NintendoCTR2_pubkey_prod.der"
#define MODULE_ID 1
#define DATA_LEN 256 // bytes
#define SIGN_MECH Mech_ECDSA
#define CROSS_VERIFY
//#define CARD_PROTECT
//#define EXPORT_KEY
//#define STRICT_FIPS
// ECDSA private key data
typedef struct
{
struct NFast_Bignum *d;
}
ECDSAPrivateKeyDataBn;
// ECDSA public key data
typedef struct
{
struct NFast_Bignum *qx;
struct NFast_Bignum *qy;
}
ECDSAPublicKeyDataBn;
// global variable
NFast_AppHandle handle;
NFastApp_Connection nc;
NFKM_WorldInfo *world = NULL;
RQCard card;
RQCard_FIPS fips;
M_KeyID ltid = 0; // the cardset loaded into the module
NFKM_CardSet *cardset = NULL;
NFKM_ModuleInfo *moduleinfo = NULL;
const NFKM_KeyIdent priv_keyident = { (char*)"simple", (char*)"nct2-priv-hoge" };
const NFKM_KeyIdent pub_keyident = { (char*)"simple", (char*)"nct2-pub-hoge" };
unsigned char save_enc[DATA_LEN];
// global var
EC_KEY *ecPriv = NULL;
EC_KEY *ecPub = NULL;
// function
int importECDSAPrivate( NFKM_KeyIdent keyident );
int importECDSAPublic( NFKM_KeyIdent keyident );
int verifyECDSAKeyPair( NFKM_KeyIdent priv_keyident, NFKM_KeyIdent pub_keyident );
void PrintArray( char *pStr, const unsigned char *pData, int length );
int importECDSAPrivate( NFKM_KeyIdent keyident )
{
int result = Status_OK;
FILE *fp;
unsigned char *dPtr = NULL;
int dLen = 0;
M_Command cmd;
M_Reply reply;
NFKM_MakeACLParams map;
NFKM_MakeBlobsParams mbp;
NFKM_Key reg_key;
ECDSAPrivateKeyDataBn privBn;
memset( &cmd, 0, sizeof( cmd ) );
memset( &reply, 0, sizeof( reply ) );
memset( &map, 0, sizeof( map ) );
memset( &mbp, 0, sizeof( mbp ) );
memset( &reg_key, 0, sizeof( reg_key ) );
memset( &privBn, 0, sizeof( privBn ) );
// key data open
printf( "priv key file : %s\n", PRIV_KEY_FILE );
fp = fopen( PRIV_KEY_FILE, "rb" );
if ( !fp )
{
printf( "error : open %s file\n", PRIV_KEY_FILE );
return 1;
}
ecPriv = d2i_ECPrivateKey_fp( fp, NULL );
if ( !ecPriv )
{
printf( "error : d2i_ECPrivateKey_fp\n" );
return 1;
}
fclose( fp );
#if 1
printf( "\nEC(d) = " );
BN_print_fp( stdout, ecPriv->priv_key );
printf( "\n" );
#endif
#if 0
printf( "EC bignum(Openssl) size\n" );
printf( "EC(d) : %d bytes\n", BN_num_bytes( privkey->priv_key ) );
#endif
// ECDSA priv key の構成要素をバイナリに変換
{
// d
dLen = BN_num_bytes( ecPriv->priv_key );
dPtr = (unsigned char *)malloc( dLen );
if ( dLen != BN_bn2bin( ecPriv->priv_key, dPtr ) )
{
printf( "BN_bn2bin failed!(d)\n" );
return 1;
}
} // ec bignum(openssl) -> bin
#if 0
printf( "EC bin addr\n" );
printf( "EC(d) : 0x%08X\n", (unsigned int)dPtr );
#endif
// バイナリをHSMのBignumに変換
{
my_bin2bignum( &(privBn.d), handle, dPtr, dLen );
free( dPtr );
}
#if 0
my_printbignum ( stdout, "EC(d)", privBn.d );
#endif
#if 0
printf( "EC bn addr\n" );
printf( "EC(d) : 0x%08X\n", (unsigned int)privBn.d );
#endif
// make ACL
if ( cardset != NULL )
map.f = NFKM_NKF_RecoveryEnabled | NFKM_NKF_ProtectionCardSet;
else
map.f = NFKM_NKF_RecoveryEnabled | NFKM_NKF_ProtectionModule;
// 秘密鍵には DECRYPT と SIGN
// 公開鍵には ENCRYPT と VERIFY しかセットできない??
#ifdef EXPORT_KEY
map.op_base = NFKM_DEFOPPERMS_SIGN | Act_OpPermissions_Details_perms_ExportAsPlain; // for debug
#else
map.op_base = NFKM_DEFOPPERMS_SIGN; // ECDSA priv key : sign only
#endif // EXPORT_KEY
map.cs = cardset;
result = NFKM_newkey_makeaclx( handle, nc, world, &map, &(cmd.args.import.acl), NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_newkey_makeaclx\n", result );
return result;
}
// import key
cmd.cmd = Cmd_Import;
cmd.args.import.module = MODULE_ID;
cmd.args.import.data.type = KeyType_ECDSAPrivate;
cmd.args.import.data.data.ecprivate.curve.name = ECName_NISTB233; // 名前を指定することで
cmd.args.import.data.data.ecprivate.d = privBn.d; // d だけ設定すれば良い
result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : Cmd_Import\n", result );
return 1;
}
result = reply.status;
if ( result != Status_OK )
{
printf( "error(%d) : Cmd_Import(reply)\n", result );
return 1;
}
// make blobs
//reg_key.v = Key__maxversion; // TORIAEZU : Key__maxversion = 8
reg_key.name = keyident.ident;
reg_key.appname = keyident.appname;
reg_key.ident = keyident.ident;
time( &(reg_key.gentime) );
mbp.f = map.f;
mbp.kpriv = reply.reply.import.key;
mbp.lt = ltid;
mbp.cs = cardset;
result = NFKM_newkey_makeblobsx( handle, nc, world, &mbp, &reg_key, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_newkey_makeblobsx\n", result );
return 1;
}
// record key to disk
result = NFKM_recordkey( handle, &reg_key, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_recordkey\n", result );
return 1;
}
// destroy key
result = NFKM_cmd_destroy( handle, nc, 0, reply.reply.import.key, "destroy import key", NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_cmd_destroy\n", result );
return 1;
}
printf( "priv key record success : appname=%s, ident=%s\n",
priv_keyident.appname, priv_keyident.ident );
return result;
} // importECDSAPrivate
int importECDSAPublic( NFKM_KeyIdent keyident )
{
int result = Status_OK;
FILE *fp;
unsigned char *qxPtr, *qyPtr;
int qxLen, qyLen;
M_Command cmd;
M_Reply reply;
NFKM_MakeACLParams map;
NFKM_MakeBlobsParams mbp;
NFKM_Key reg_key;
ECDSAPublicKeyDataBn pubBn;
qxPtr = qyPtr = NULL;
qxLen = qyLen = 0;
memset( &cmd, 0, sizeof( cmd ) );
memset( &reply, 0, sizeof( reply ) );
memset( &map, 0, sizeof( map ) );
memset( &mbp, 0, sizeof( mbp ) );
memset( &reg_key, 0, sizeof( reg_key ) );
memset( &pubBn, 0, sizeof( pubBn ) );
// key data open
printf( "pub key file : %s\n", PUB_KEY_FILE );
fp = fopen( PUB_KEY_FILE, "rb" );
if ( !fp )
{
printf( "error : open %s file\n", PUB_KEY_FILE );
return 1;
}
ecPub = d2i_EC_PUBKEY_fp( fp, NULL );
if ( !ecPub )
{
printf( "error : d2i_EC_PUBKEY_fp\n" );
return 1;
}
fclose( fp );
#if 1
printf( "\nEC(Q->x) = " );
BN_print_fp( stdout, &(ecPub->pub_key->X) );
printf( "\nEC(Q->y) = " );
BN_print_fp( stdout, &(ecPub->pub_key->Y) );
printf( "\n" );
#endif
#if 0
printf( "EC bignum(Openssl) size\n" );
printf( "EC(qx) : %d bytes\n", BN_num_bytes( &pubkey->pub_key->X ) );
printf( "EC(qy) : %d bytes\n", BN_num_bytes( &pubkey->pub_key->Y ) );
#endif
// ECDSA public key の構成要素をそれぞれバイナリに変換
{
// qx
qxLen = BN_num_bytes( &ecPub->pub_key->X );
qxPtr = (unsigned char *)malloc( qxLen );
if ( qxLen != BN_bn2bin( &ecPub->pub_key->X, qxPtr ) )
{
printf( "BN_bn2bin failed!(qx)\n" );
return 1;
}
// qy
qyLen = BN_num_bytes( &ecPub->pub_key->Y );
qyPtr = (unsigned char *)malloc( qyLen );
if ( qyLen != BN_bn2bin( &ecPub->pub_key->Y, qyPtr ) )
{
printf( "BN_bn2bin failed!(qy)\n" );
return 1;
}
} // ECDSA bignum(openssl) -> bin
#if 0
printf( "EC bin addr\n" );
printf( "EC(qx) : 0x%08X\n", (unsigned int)qxPtr );
printf( "EC(qy) : 0x%08X\n", (unsigned int)qyPtr );
#endif
// バイナリをHSMのBignumに変換
{
my_bin2bignum( &(pubBn.qx), handle, qxPtr, qxLen );
my_bin2bignum( &(pubBn.qy), handle, qyPtr, qyLen );
free( qxPtr );
free( qyPtr );
}
#if 0
printf( "EC bn addr\n" );
printf( "EC(qx) : 0x%08X\n", (unsigned int)pubBn.qx );
printf( "EC(qy) : 0x%08X\n", (unsigned int)pubBn.qy );
#endif
// make ACL
if ( cardset != NULL )
map.f = NFKM_NKF_RecoveryEnabled | NFKM_NKF_ProtectionCardSet | NFKM_NKF_PublicKey;
else
map.f = NFKM_NKF_RecoveryEnabled | NFKM_NKF_ProtectionModule | NFKM_NKF_PublicKey;
// 秘密鍵には DECRYPT と SIGN
// 公開鍵には ENCRYPT と VERIFY しかセットできない??
#ifdef EXPORT_KEY
map.op_base = NFKM_DEFOPPERMS_VERIFY | Act_OpPermissions_Details_perms_ExportAsPlain; // for debug (maybe, pub key has an export permission as default.)
#else
map.op_base = NFKM_DEFOPPERMS_VERIFY; // ECDSA public key : verify only
#endif // EXPORT_KEY
map.cs = cardset;
result = NFKM_newkey_makeaclx( handle, nc, world, &map, &(cmd.args.import.acl), NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_newkey_makeaclx\n", result );
return result;
}
// import key
cmd.cmd = Cmd_Import;
cmd.args.import.module = MODULE_ID;
cmd.args.import.data.type = KeyType_ECDSAPublic;
cmd.args.import.data.data.ecpublic.curve.name = ECName_NISTB233; // 名前を指定することで
cmd.args.import.data.data.ecpublic.Q.x = pubBn.qx; // qx
cmd.args.import.data.data.ecpublic.Q.y = pubBn.qy; // qy だけを指定すればよい?
result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : Cmd_Import\n", result );
return 1;
}
result = reply.status;
if ( result != Status_OK )
{
printf( "error(%d) : Cmd_Import(reply)\n", result );
return 1;
}
// make blobs
//reg_key.v = Key__maxversion; // TORIAEZU : Key__maxversion = 8
reg_key.name = keyident.ident;
reg_key.appname = keyident.appname;
reg_key.ident = keyident.ident;
time( &(reg_key.gentime) );
mbp.f = map.f;
mbp.kpub = reply.reply.import.key;
mbp.lt = ltid;
mbp.cs = cardset;
result = NFKM_newkey_makeblobsx( handle, nc, world, &mbp, &reg_key, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_newkey_makeblobsx\n", result );
return 1;
}
// record key to disk
result = NFKM_recordkey( handle, &reg_key, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_recordkey\n", result );
return 1;
}
// destroy key
result = NFKM_cmd_destroy( handle, nc, 0, reply.reply.import.key, "destroy import key", NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_cmd_destroy\n", result );
return 1;
}
printf( "pub key record success : appname=%s, ident=%s\n",
pub_keyident.appname, pub_keyident.ident );
return result;
} // importECDSAPublic
int verifyECDSAKeyPair( NFKM_KeyIdent priv_ident, NFKM_KeyIdent pub_ident )
{
int i;
int result = Status_OK;
M_ByteBlock *blobptr = NULL;
M_KeyID priv_keyid, pub_keyid;
NFKM_Key *keyinfo = NULL;
M_Command cmd;
M_Reply reply;
priv_keyid = pub_keyid = 0;
memset( &cmd, 0, sizeof( cmd ) );
memset( &reply, 0, sizeof( reply ) );
// find priv key
result = NFKM_findkey( handle, priv_ident, &keyinfo, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_findkey(priv)\n", result );
return result;
}
// load priv key blob
blobptr = &(keyinfo->privblob);
result = NFKM_cmd_loadblob( handle, nc,
moduleinfo->module, blobptr, ltid, &priv_keyid, "loading priv key blob", NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_cmd_loadblob(priv)\n", result );
return result;
}
NFKM_freekey( handle, keyinfo, NULL );
keyinfo = NULL;
#if 0
// get priv key info
cmd.cmd = Cmd_GetKeyInfo;
cmd.args.getkeyinfo.key = priv_keyid;
result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : FastApp_Transact(Cmd_GetKeyInfo)\n", result );
return result;
}
printf( "priv key ID : %08X\n", (unsigned int)priv_keyid );
printf( "priv keytype : %d\n", reply.reply.getkeyinfo.type );
NFastApp_Free_Command( handle, NULL, NULL, &cmd );
NFastApp_Free_Reply( handle, NULL, NULL, &reply );
memset( &cmd, 0, sizeof( cmd ) );
memset( &reply, 0, sizeof( reply ) );
#endif
// find pub key
result = NFKM_findkey( handle, pub_ident, &keyinfo, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_findkey(pub)\n", result );
return result;
}
// load pub key blob
blobptr = &(keyinfo->pubblob); // pub dakedo privblob
result = NFKM_cmd_loadblob( handle, nc,
moduleinfo->module, blobptr, ltid, &pub_keyid, "loading pub key blob", NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_cmd_loadblob(pub)\n", result );
return result;
}
NFKM_freekey( handle, keyinfo, NULL );
keyinfo = NULL;
#if 0
// get priv key info
cmd.cmd = Cmd_GetKeyInfo;
cmd.args.getkeyinfo.key = pub_keyid;
result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : FastApp_Transact(Cmd_GetKeyInfo)\n", result );
return result;
}
printf( "pub key ID : %08X\n", (unsigned int)pub_keyid );
printf( "pub keytype : %d\n", reply.reply.getkeyinfo.type );
NFastApp_Free_Command( handle, NULL, NULL, &cmd );
NFastApp_Free_Reply( handle, NULL, NULL, &reply );
memset( &cmd, 0, sizeof( cmd ) );
memset( &reply, 0, sizeof( reply ) );
keyinfo = NULL;
#endif
// export key pair
#ifdef EXPORT_KEY
// priv key export
cmd.cmd = Cmd_Export;
cmd.args.export.key = priv_keyid;
result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : FastApp_Transact(Cmd_Export)\n", result );
return 1;
}
result = reply.status;
if ( result != Status_OK )
{
printf( "error(%d) : reply.status(Cmd_Export)\n", result );
return 1;
}
printf( "----- export : priv key -----\n" );
printf( "key type : %d\n", reply.reply.export.data.type );
printf( "curve namee : %d\n", reply.reply.export.data.data.ecprivate.curve.name );
my_printbignum( stdout, "d", reply.reply.export.data.data.ecprivate.d );
printf( "-----------------------------\n" );
NFastApp_Free_Reply( handle, NULL, NULL, &reply );
memset( &cmd, 0, sizeof( cmd ) );
memset( &reply, 0, sizeof( reply ) );
// pub key export
cmd.cmd = Cmd_Export;
cmd.args.export.key = pub_keyid;
result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : FastApp_Transact(Cmd_Export)\n", result );
return 1;
}
result = reply.status;
if ( result != Status_OK )
{
printf( "error(%d) : reply.status(Cmd_Export)\n", result );
return 1;
}
printf( "----- export : priv key -----\n" );
printf( "key type : %d\n", reply.reply.export.data.type );
printf( "curve namee : %d\n", reply.reply.export.data.data.ecpublic.curve.name );
my_printbignum( stdout, "Q->x", reply.reply.export.data.data.ecpublic.Q.x );
my_printbignum( stdout, "Q->y", reply.reply.export.data.data.ecpublic.Q.y );
printf( "-----------------------------\n" );
NFastApp_Free_Reply( handle, NULL, NULL, &reply );
memset( &cmd, 0, sizeof( cmd ) );
memset( &reply, 0, sizeof( reply ) );
#endif // EXPORT_KEY
// sign & verify test
{
M_Hash hash;
struct NFast_Bignum *rBn, *sBn;
unsigned char *rPtr, *sPtr;
int rLen, sLen;
rBn = sBn = NULL;
rPtr = sPtr = NULL;
rLen = sLen = 0;
// hash data
for ( i = 0; i < 20; i++ )
hash.bytes[i] = i+1;
#if 1
PrintArray( (char*)"hash", hash.bytes, 20 );
#endif
// sign transact
cmd.cmd = Cmd_Sign;
cmd.args.sign.flags = 0; // Cmd_Sign_Args_flags_given_iv_present;
cmd.args.sign.key = priv_keyid;
cmd.args.sign.mech = SIGN_MECH;
cmd.args.sign.plain.type = PlainTextType_Hash;
cmd.args.sign.plain.data.hash.data = hash;
result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : FastApp_Transact(Cmd_Sign)\n", result );
return 1;
}
result = reply.status;
if ( result != Status_OK )
{
printf( "error(%d) : reply.status(Cmd_Sign)\n", result );
return 1;
}
if ( SIGN_MECH != reply.reply.sign.sig.mech )
{
printf( "error : reply mech isn't match %d!\n", SIGN_MECH );
return 1;
}
printf( "ECDSA sign ok\n" );
// signature bignum -> bin
printf ( "sig mech : %d\n", reply.reply.sign.sig.mech );
rLen = reply.reply.sign.sig.data.ecdsa.r->nbytes;
rPtr = (unsigned char*)malloc( rLen );
my_bignum2bin ( rPtr, rLen, handle, reply.reply.sign.sig.data.ecdsa.r );
sLen = reply.reply.sign.sig.data.ecdsa.s->nbytes;
sPtr = (unsigned char*)malloc( sLen );
my_bignum2bin ( sPtr, sLen, handle, reply.reply.sign.sig.data.ecdsa.s );
my_bignumCopy( &rBn, reply.reply.sign.sig.data.ecdsa.r, handle );
my_bignumCopy( &sBn, reply.reply.sign.sig.data.ecdsa.s, handle );
#if 1
PrintArray( (char*)"sig r", rPtr, rLen );
PrintArray( (char*)"sig s", sPtr, sLen );
#endif
//NFastApp_Free_Command( handle, NULL, NULL, &cmd );
NFastApp_Free_Reply( handle, NULL, NULL, &reply );
memset( &cmd, 0, sizeof( cmd ) );
memset( &reply, 0, sizeof( reply ) );
// verify transact
cmd.cmd = Cmd_Verify;
cmd.args.verify.flags = 0;
cmd.args.verify.key = pub_keyid;
cmd.args.verify.mech = SIGN_MECH;
cmd.args.verify.plain.type = PlainTextType_Hash;
cmd.args.verify.plain.data.hash.data = hash;
cmd.args.verify.sig.mech = SIGN_MECH;
cmd.args.verify.sig.data.ecdsa.r = rBn;
cmd.args.verify.sig.data.ecdsa.s = sBn;
result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : FastApp_Transact(Cmd_Decrypt)\n", result );
return 1;
}
result = reply.status;
if ( result != Status_OK )
{
printf( "error(%d) : reply.status(Cmd_Decrypt)\n", result );
return 1;
}
printf( "ECDSA verify ok!\n" );
NFastApp_Free_Command( handle, NULL, NULL, &cmd );
NFastApp_Free_Reply( handle, NULL, NULL, &reply );
#ifdef CROSS_VERIFY
unsigned char compareBuf[0x80];
int sigLen = 0;
const unsigned char *pECDSAsig = compareBuf;
ECDSA_SIG *sig = NULL;
unsigned char *rOPtr, *sOPtr;
int rOLen, sOLen;
struct NFast_Bignum *rBnO, *sBnO;
memset( compareBuf, 0, sizeof( compareBuf ) );
result = ECDSA_sign( 0, hash.bytes, 20, compareBuf, &sigLen, ecPriv );
if ( result == 0)
{
printf( "error : ECDSA_sign(by OpenSSL)!\n" );
return 1;
}
sig = d2i_ECDSA_SIG( NULL, &pECDSAsig, sigLen );
if( sig == NULL )
{
printf( "error : d2i_ECDSA_SIG(by OpenSSL)!\n" );
return 1;
}
#if 0
PrintArray( (char*)"OpenSSL:sig r", (const char*)sig->r->d, sig->r->dmax*4 );
PrintArray( (char*)"OpenSSL:sig s", (const char*)sig->s->d, sig->s->dmax*4 );
#endif
// OpenSSL r&S -> bin -> HSM r&s
rOLen = BN_num_bytes( sig->r );
rOPtr = (unsigned char *)malloc( rOLen );
if ( rOLen != BN_bn2bin( sig->r, rOPtr ) )
{
printf( "BN_bn2bin failed!(sig->r)\n" );
return 1;
}
sOLen = BN_num_bytes( sig->s );
sOPtr = (unsigned char *)malloc( sOLen );
if ( sOLen != BN_bn2bin( sig->s, sOPtr ) )
{
printf( "BN_bn2bin failed!(sig->s)\n" );
return 1;
}
my_bin2bignum( &rBnO, handle, rOPtr, rOLen );
my_bin2bignum( &sBnO, handle, sOPtr, sOLen );
// verify sign for HSM hash
//NFastApp_Free_Command( handle, NULL, NULL, &cmd );
NFastApp_Free_Reply( handle, NULL, NULL, &reply );
memset( &cmd, 0, sizeof( cmd ) );
memset( &reply, 0, sizeof( reply ) );
// verify transact
cmd.cmd = Cmd_Verify;
cmd.args.verify.flags = 0;
cmd.args.verify.key = pub_keyid;
cmd.args.verify.mech = SIGN_MECH;
cmd.args.verify.plain.type = PlainTextType_Hash;
cmd.args.verify.plain.data.hash.data = hash;
cmd.args.verify.sig.mech = SIGN_MECH;
cmd.args.verify.sig.data.ecdsa.r = rBnO;
cmd.args.verify.sig.data.ecdsa.s = sBnO;
result = NFastApp_Transact( nc, NULL, &cmd, &reply, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : FastApp_Transact(Cmd_Decrypt)\n", result );
return 1;
}
result = reply.status;
if ( result != Status_OK )
{
printf( "error(%d) : reply.status(Cmd_Decrypt)\n", result );
return 1;
}
printf( "OpenSSL sign(r&s) verified by HSM!\n" );
// verify HSM signature by OpenSSL
{
unsigned char tempSign[70];
tempSign[0] = 0x30;
tempSign[1] = 0x3E;
tempSign[2] = 0x02;
tempSign[3] = 0x1D;
memcpy( &tempSign[4], &rPtr[3], 0x1D );
tempSign[0x21] = 0x02;
tempSign[0x22] = 0x1D;
memcpy( &tempSign[0x23], &sPtr[3], 0x1D );
PrintArray( (char*)"tempSign(HSM)", (const char *)tempSign, 0x3E + 2 );
result = ECDSA_verify( 0, hash.bytes, 20, tempSign, 0x3E + 2, ecPub );
if( result != 1)
{
printf( "error : ECDSA_verify(by OpenSSL)!\n" );
return 1;
}
}
printf( "HSM sign(r&s) verified by OpenSSL!\n" );
result = 0;
#endif // CROSS_VERIFY
} // encrypt & decrypt
return result;
} // verifyECDSAkeypair
void PrintArray( char *pStr, const unsigned char *pData, int length )
{
int i;
printf( "%s(%d bytes)", pStr, length );
for ( i = 0; i < length; i++ )
{
if ( (i % 16) == 0 ) printf( "\n" );
printf( "%02X ", pData[ i ] );
}
printf( "\n" );
} // PrintArray
int main( int argc, char *argv[] )
{
int result = Status_OK;
M_Command cmd;
M_Reply reply;
memset( &cmd, 0, sizeof( cmd ) );
memset( &reply, 0, sizeof( reply ) );
// init nFast
result = NFastApp_InitEx( &handle, NULL, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFastApp_InitEx\n", result );
return 1;
}
// connecting to hardserver
result = NFastApp_Connect( handle, &nc, 0, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFastApp_Connect\n", result );
return 1;
}
// set bignum upcalls setting
result = NFastApp_SetBignumUpcalls(
handle,
my_bignumreceiveupcall,
my_bignumsendlenupcall,
my_bignumsendupcall,
my_bignumfreeupcall,
my_bignumformatupcall,
NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFastApp_SetBignumUpcalls\n", result );
return 1;
}
// NFKM getinfo
result = NFKM_getinfo( handle, &world, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_getinfo\n", result );
return 1;
}
// init card-loading lib
result = RQCard_init( &card, handle, nc, world, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : RQCard_init\n", result );
return 1;
}
// init FIPS state
result = RQCard_fips_init( &card, &fips );
if ( result != Status_OK )
{
printf( "error(%d) : RQCard_fips_init\n", result );
return 1;
}
// ui select
result = RQCard_ui_default( &card );
if ( result != Status_OK )
{
printf( "error(%d) : RQCard_ui_default\n", result );
return 1;
}
// get strict-FIPS authorization
#ifdef STRICT_FIPS
NFKM_FIPS140AuthHandle fipsHandle;
M_SlotID slotId;
result = RQCard_fips_get( &fips, 1, &fipsHandle, &slotId );
if ( result != Status_OK )
{
printf( "error(%d) : RQCard_fips_get\n", result );
return 0;
}
if ( fipsHandle == NULL )
{
printf( "this sworld isn't strict-FIPS.\n" );
}
#endif
#ifdef CARD_PROTECT
// list cardsets
int card_num;
NFKM_CardSetIdent *cardident = NULL;
result = NFKM_listcardsets( handle, &card_num, &cardident, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_listcardsets\n", result );
return 0;
}
// find cardsets
result = NFKM_findcardset( handle, cardident, &cardset, NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_findcardset\n", result );
return 0;
}
// load cardset
result = RQCard_logic_ocs_specific( &card, &(cardset->hkltu), "Load Cardset" );
if ( result != Status_OK )
{
printf( "error(%d) : RQCard_logic_ocs_specific\n", result );
return 0;
}
// use specific module : #1
// important!! : if you set resultplace=NULL, abort. (possibility is 100%)
result = RQCard_whichmodule_specific( &card, world->modules[0]->module, &ltid );
if ( result != Status_OK )
{
printf( "error(%d) : RQCard_whichmodule_specific\n", result );
}
// wait event loop
result = card.uf->eventloop( &card );
if ( result != Status_OK )
{
printf( "error(%d) : card module event loop\n", result );
}
#endif // CARD_PROTECT
// get usable module
moduleinfo = world->modules[0];
result = NFKM_getusablemodule( world, MODULE_ID, &moduleinfo );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_getusablemodule\n", result );
return 1;
}
// ECDSA privkey のインポート
result = importECDSAPrivate( priv_keyident );
if ( result != Status_OK )
{
printf( "error : importECDSAPrivate\n" );
return 1;
}
printf( "ECDSA privkey import success.\n" );
// ECDSA pubkey
result = importECDSAPublic( pub_keyident );
if ( result != Status_OK )
{
printf( "error : importECDSAPublic\n" );
return 1;
}
printf( "ECDSA pubkey import success.\n" );
// list key
#if 0
int key_num;
NFKM_KeyIdent *keylist = NULL;
result = NFKM_listkeys( handle, &key_num, &keylist, "simple", NULL );
if ( result != Status_OK )
{
printf( "error(%d) : NFKM_listkeys\n", result );
}
NFKM_KeyIdent **tkp = &keylist;
for ( i = 0; i < key_num; i++ )
{
printf( "appname : %s, ident : %s\n", tkp[i]->appname, tkp[i]->ident );
}
#endif
// verify key pair
result = verifyECDSAKeyPair( priv_keyident, pub_keyident );
if ( result != Status_OK )
{
printf( "error : verifyECDSAKeyPair\n" );
return 1;
}
printf( "ECDSA keypair verify success.\n" );
// end processing
RQCard_fips_free( &card, &fips );
RQCard_destroy( &card );
NFKM_freeinfo( handle, &world, NULL );
NFastApp_Disconnect( nc, NULL );
NFastApp_Finish( handle, NULL );
return 0;
} // main

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,45 @@
/*
* my_hsm_alloc.c
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include "nfastapp.h"
#include "nfutil.h"
#include "my_hsm_alloc.h"
/* --------------------- */
const NFast_MallocUpcalls my_hsm_malloc_upcalls =
{
my_hsm_malloc, my_hsm_realloc, my_hsm_free
};
/* --------------------- */
void *my_hsm_malloc( size_t nbytes,
struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx )
{
return malloc( nbytes );
}
/* --------------------- */
void *my_hsm_realloc( void *ptr, size_t nbytes,
struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx )
{
return realloc( ptr, nbytes );
}
/* --------------------- */
void my_hsm_free( void *ptr,
struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx )
{
free( ptr );
}

View File

@ -0,0 +1,30 @@
/*
* my_hsm_alloc.h
*/
#ifndef MY_HSM_ALLOC_H
#define MY_HSM_ALLOC_H
#include "nfastapp.h"
#ifdef __cplusplus
extern "C" {
#endif
extern const NFast_MallocUpcalls my_hsm_malloc_upcalls;
void *my_hsm_malloc( size_t nbytes,
struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx );
void *my_hsm_realloc( void *ptr, size_t nbytes,
struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx );
void my_hsm_free( void *ptr,
struct NFast_Call_Context *cctx, struct NFast_Transaction_Context *tctx );
#ifdef __cplusplus
}
#endif
#endif // MY_HSM_ALLOC_H

View File

@ -0,0 +1,357 @@
/*
* SIMPLEBIGNUM.C
*
* Simple bignumber upcalls
*
* This example source code is provided for your information and
* assistance. See the file LICENCE.TXT for details and the
* terms and conditions of the licence which governs the use of the
* source code. By using such source code you will be accepting these
* terms and conditions. If you do not wish to accept these terms and
* conditions, DO NOT OPEN THE FILE OR USE THE SOURCE CODE.
*
* Note that there is NO WARRANTY.
*
* Copyright 2001 - 2002 nCipher Corporation Limited.
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include "nfastapp.h"
#include "nfutil.h"
#include "my_hsm_bignum.h"
/* --------------------- */
int my_bignumreceiveupcall(struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx,
M_Bignum *bignum, int nbytes,
const void *source,
int msbitfirst, int mswordfirst)
{
struct NFast_Bignum *pBN;
if ( nbytes > MAXBIGNUMBITS/8 ) return Status_OutOfRange;
assert( (nbytes & 3)==0 );
pBN = (struct NFast_Bignum *)NFastApp_Malloc(app, sizeof(struct NFast_Bignum), cctx, tctx);
if ( !pBN ) return NOMEM;
nfutil_copybytes(pBN->bytes, (const unsigned char *)source,
nbytes, 0, 0);
pBN->msb_first = msbitfirst;
pBN->msw_first = mswordfirst;
pBN->nbytes=nbytes;
*bignum=pBN;
return Status_OK;
}
/* --------------------- */
int my_bignumsendlenupcall(struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx,
const M_Bignum *bignum, int *nbytes_r)
{
assert( ((*bignum)->nbytes & 3)==0 );
*nbytes_r= (*bignum)->nbytes;
return Status_OK;
}
/* --------------------- */
int my_bignumsendupcall(struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx,
const M_Bignum *bignum, int nbytes,
void *dest, int msbitfirst, int mswordfirst)
{
int swapends, swapwords;
struct NFast_Bignum *pBN = *bignum;
assert( pBN->nbytes==nbytes );
/* Is format which we're sending in the same as that of the
bignumber?
(NB '!' used to constrain result to 0,1 range)
If not, work out which ends to swap.
*/
swapends = (!msbitfirst) ^ (!pBN->msb_first);
swapwords = (!mswordfirst) ^ (!pBN->msw_first);
nfutil_copybytes( (unsigned char *)dest, (*bignum)->bytes, nbytes,
swapends, swapwords );
return Status_OK;
}
/* --------------------- */
void my_bignumfreeupcall(struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx,
M_Bignum *bignum)
{
NFastApp_Free(app, (*bignum), cctx, tctx);
*bignum=NULL;
}
/* --------------------- */
int my_bignumformatupcall(struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx,
int *msbitfirst_io, int *mswordfirst_io)
{
/* Send to the module in little-endian format.
(This is not officially necessary. However, some
versions of the monitor (Maintenance mode) don't accept
big-endian bignums due to a bug) */
*msbitfirst_io=0;
*mswordfirst_io=0;
return Status_OK;
}
NFast_BignumUpcalls my_upcalls = {
my_bignumreceiveupcall,
my_bignumsendlenupcall,
my_bignumsendupcall,
my_bignumfreeupcall,
my_bignumformatupcall
};
/* --------------------- */
static int char2hex ( char c )
{
if ( c >= '0' && c <= '9' ) return c-'0';
if ( c >= 'A' && c <= 'F' ) return c-'A'+10;
if ( c >= 'a' && c <= 'f' ) return c-'a'+10;
return -1;
}
/* --------------------- */
int my_char2bignum ( struct NFast_Bignum **ppBN_out,
const char *text,
struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx )
{
struct NFast_Bignum *pBN;
int d;
size_t len, i;
/* Strip leading whitespace */
while ( text[0] != 0 && isspace((unsigned char)text[0]) )
text++;
/* Strip trailing whitespace */
len=strlen(text);
while ( len > 0 && isspace((unsigned char)text[len-1]) )
len--;
if ( len > MAXBIGNUMBITS/4 ) return Status_OutOfRange;
pBN = (struct NFast_Bignum *)NFastApp_Malloc(app, sizeof(struct NFast_Bignum), cctx, tctx);
if ( !pBN ) return NOMEM;
pBN->msb_first = 0;
pBN->msw_first = 0;
/* Read in from the LS digit */
for ( i=0; i<len; i++ )
{
d = char2hex(text[len-1-i]);
if ( d < 0 ) return Status_Malformed;
if ( i & 1 )
pBN->bytes[i/2] |= (d << 4);
else
pBN->bytes[i/2] = d;
}
/* Pad to words if necessary */
i = (len+1)/2;
while ( (i & 3) != 0 )
pBN->bytes[i++] = 0;
assert(i <= INT_MAX);
pBN->nbytes=(int)i;
*ppBN_out=pBN;
return Status_OK;
}
/* --------------------- */
// bin データを NFast_Bignum データに変換する
int my_bin2bignum ( struct NFast_Bignum **ppBN_out,
struct NFast_Application *app,
const unsigned char *bin, const int size )
{
struct NFast_Bignum *pBN;
int len, i;
len = size;
if ( len > MAXBIGNUMBITS/4 ) return Status_OutOfRange;
pBN = (struct NFast_Bignum *)NFastApp_Malloc( app, sizeof(struct NFast_Bignum), NULL, NULL );
if ( !pBN ) return NOMEM;
pBN->msb_first = 0;
pBN->msw_first = 0;
for ( i = 0; i < len; i++ )
pBN->bytes[i] = bin[len-1-i];
while ( (i & 3) != 0 )
pBN->bytes[i++] = 0;
pBN->nbytes = i;
*ppBN_out = pBN;
return Status_OK;
} // my_bin2bignum
/* --------------------- */
static int getbyte ( const struct NFast_Bignum *pN, int pos )
{
/* Get a byte from a bignum, taking account of possible strange endianness */
if ( pos >= pN->nbytes ) return 0;
if ( pN->msb_first ) pos ^= 3; /* Big endian words */
if ( pN->msw_first )
{
pos = pN->nbytes-1-pos;
pos ^= 3;
}
return pN->bytes[pos];
}
/* --------------------- */
static int getbytelen ( const struct NFast_Bignum *pN )
{
int n=pN->nbytes-1;
while ( n >= 0 && getbyte(pN, n)==0 )
n--;
return n+1;
}
/* --------------------- */
int my_bignum2char ( char *buf, int buflen,
const struct NFast_Bignum *pBN,
struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx )
{
int i, d, pos, len;
static const char *hexdigits="0123456789ABCDEF";
len = pBN->nbytes;
pos = len*2+1;
if ( buflen < pos )
return Status_BufferFull;
buf[--pos] = 0;
for ( i=0; i<len; i++ )
{
d = getbyte(pBN,i);
buf[--pos] = hexdigits[d & 0xF];
buf[--pos] = hexdigits[(d>>4) & 0xF];
}
return Status_OK;
}
/* --------------------- */
int my_bignum2bin ( unsigned char *buf, int buflen,
struct NFast_Application *app,
const struct NFast_Bignum *pBN )
{
int i, pos, len;
len = pBN->nbytes;
pos = len;
if ( buflen < pos )
return Status_BufferFull;
for ( i = 0; i < len; i++ )
{
buf[--pos] = getbyte( pBN, i );
}
return Status_OK;
} // my_bignum2bin
/* --------------------- */
int my_bignumCopy( struct NFast_Bignum **dst,
const struct NFast_Bignum *src,
struct NFast_Application *app )
{
struct NFast_Bignum *pBN;
pBN = (struct NFast_Bignum *)NFastApp_Malloc( app, sizeof(struct NFast_Bignum), NULL, NULL );
if ( !pBN ) return NOMEM;
pBN->msb_first = src->msb_first;
pBN->msw_first = src->msw_first;
pBN->nbytes = src->nbytes;
memcpy( pBN->bytes, src->bytes, src->nbytes );
*dst = pBN;
return Status_OK;
}
/* --------------------- */
void my_printbignum ( FILE *f, const char *prefix, const struct NFast_Bignum *pBN )
{
char buf[MAXBIGNUMBITS/4+1];
int rc;
rc = my_bignum2char(buf, sizeof(buf), pBN, NULL, NULL, NULL);
if ( rc != Status_OK ) strcpy(buf, "<invalid length>");
fprintf( f, "%s=\n %s\n", prefix, buf );
}
/* --------------------- */
int my_compare ( const struct NFast_Bignum *pA,
const struct NFast_Bignum *pB )
{
int i, aa, bb;
aa=getbytelen(pA);
bb=getbytelen(pB);
if ( aa != bb ) return (aa > bb) ? 1 : -1;
i=aa;
while ( i-- > 0 )
{
aa=getbyte(pA,i);
bb=getbyte(pB,i);
if ( aa != bb ) return (aa > bb) ? 1 : -1;
}
return 0;
}

View File

@ -0,0 +1,178 @@
/** \file simplebignum.h Simple bignum support
*
* Illustrates simple easy-to-use bignumber format. This provides a
* definition of the \ref NFast_Bignum structure which can be used
* in applications which do not already have an equivalent structure
* defined.
*
* See also:
* - \ref nfastapp.h
* - \ref gsbignum
*/
/* Copyright 1999-2002 nCipher Corporation Limited.
*
* This example source code is provided for your information and
* assistance. See the file LICENCE.TXT for details and the
* terms and conditions of the licence which governs the use of the
* source code. By using such source code you will be accepting these
* terms and conditions. If you do not wish to accept these terms and
* conditions, DO NOT OPEN THE FILE OR USE THE SOURCE CODE.
*
* Note that there is NO WARRANTY.
*
*/
#ifndef MY_ALLOC_H
#define MY_ALLOC_H
#include "nfastapp.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifndef MAXBIGNUMBITS
/** Maximum size of a bignum in bits */
#define MAXBIGNUMBITS 16384
#endif
/** Structure of a bignum
*
* \ref M_Bignum will be a pointer to this structure. */
struct NFast_Bignum {
/** Byte order
*
* If this is set then each 32-bit word in the bignum is big-endian
* (most-significant byte first); otherwise it is little-endian
* (least-significant byte first). */
int msb_first;
/** Word order
*
* If this is set then 32-bit words in the bignum are in big-endian order
* (most-significant word first); otherwise they are in little-endian
* order (least-significant words first).
*/
int msw_first;
/** Number of bytes */
int nbytes;
/** Bignum data
*
* Only the first \a nbytes are used. */
unsigned char bytes[MAXBIGNUMBITS/8];
};
/* Bignum send & receive upcalls -------------------------- */
/* As well as being used directly as upcalls,
these can be used to create bignums from data blocks and
extract data from bignums.
*/
/** Bignum receive upcall
*
* See \ref NFast_BignumReceiveUpcall_t */
extern int my_bignumreceiveupcall(struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx,
M_Bignum *bignum, int nbytes,
const void *source,
int msbitfirst, int mswordfirst);
/** Bignum send-length upcall
*
* See \ref NFast_BignumSendLenUpcall_t */
extern int my_bignumsendlenupcall(struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx,
const M_Bignum *bignum, int *nbytes_r);
/** Bignum send upcall
*
* See \ref NFast_BignumSendUpcall_t */
extern int my_bignumsendupcall(struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx,
const M_Bignum *bignum, int nbytes,
void *dest, int msbitfirst, int mswordfirst);
/** Free bignum upcall
*
* See \ref NFast_BignumFreeUpcall_t */
extern void my_bignumfreeupcall(struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx,
M_Bignum *bignum);
/** Bignum format upcall
*
* See \ref NFast_BignumFormatUpcall_t */
extern int my_bignumformatupcall(struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx,
int *msbitfirst_io, int *mswordfirst_io);
/** Structure containing bignum upcalls
*
* See \ref NFastAppInitArgs and \ref NFAPP_IF_BIGNUM */
extern NFast_BignumUpcalls my_upcalls;
/* Bignum utility functions ----------------------------- */
/** Convert a hex string to a bignum
*
* \return Status code
*/
extern int my_char2bignum ( struct NFast_Bignum **ppBN_out,
const char *text,
struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx );
// convert binary to NFast_Bignum
extern int my_bin2bignum ( struct NFast_Bignum **ppBN_out,
struct NFast_Application *app,
const unsigned char *bin, const int size );
/** Convert a bignum to a hex string
*
* \return Status code
*/
extern int my_bignum2char ( char *buf, int buflen,
const struct NFast_Bignum *pBN,
struct NFast_Application *app,
struct NFast_Call_Context *cctx,
struct NFast_Transaction_Context *tctx );
// convert NFast_Bignum to binary
int my_bignum2bin ( unsigned char *buf, int buflen,
struct NFast_Application *app,
const struct NFast_Bignum *pBN );
// NFast_Bignum copy
int my_bignumCopy( struct NFast_Bignum **dst,
const struct NFast_Bignum *src,
struct NFast_Application *app );
/** Print a bignum in hex to a file
*
* Call ferror() to test for output errors.
*/
extern void my_printbignum ( FILE *f,
const char *prefix, const struct NFast_Bignum *pBN );
/** Compare two bignums
*
* \return -1, 0 or 1 if A\<B, A=B or A\>B
*/
extern int my_compare ( const struct NFast_Bignum *pA,
const struct NFast_Bignum *pB );
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,371 @@
#define RAND_MAX 0xffffffff
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#ifdef DEV_CYGWIN
#include <conio.h>
#else // Cygwin
#include <termios.h>
#include <unistd.h>
#endif // Linux
#include "cr_generate_id.h"
#define BONDING_OPTION_PROD 0 // 製品用ID
#define BONDING_OPTION_DEV 1 // 開発用ID
// extern const int isDummyPrivateKey;
/*
gen_id.exe 0x01 0x02
gen_id.exe 0x01 0x02 ctrid090716.dat
gen_id.exe 0x01 0x03 ctrid090728.dat
*/
#ifndef DEV_CYGWIN
static struct termios initial_setting, new_setting;
static int peek_character = -1;
void keyboard_initialize( void )
{
tcgetattr( 0, &initial_setting );
new_setting = initial_setting;
new_setting.c_lflag &= ~ICANON;
new_setting.c_lflag &= ~ECHO;
new_setting.c_lflag &= ~ISIG;
new_setting.c_cc[VMIN] = 0;
new_setting.c_cc[VTIME] = 0;
tcsetattr( 0, TCSANOW, &initial_setting );
} // keyboard_initialize
void keyboard_finalize( void )
{
tcsetattr( 0, TCSANOW, &initial_setting );
} // keyboard_finalize
int kbhit( void )
{
char ch;
int nread;
if ( peek_character != -1 )
return 1;
new_setting.c_cc[VMIN] = 0;
tcsetattr( 0, TCSANOW, &new_setting );
nread = read( 0, &ch, 1 );
new_setting.c_cc[VMIN] = 1;
tcsetattr( 0, TCSANOW, &new_setting );
if ( nread == 1 )
{
peek_character = ch;
return 1;
}
return 0;
} // kbhit
int getch( void )
{
char ch;
if ( peek_character != -1 )
{
ch = peek_character;
peek_character = -1;
return ch;
}
read( 0, &ch, 1 );
return ch;
} // readch
#endif // DEV_CYGWIN
// char *str = "0x11111111";
static int str_to_u32(u32 *num, const char *str)
{
u32 c;
int shift = 0;
char *s;
int hex_mode = 0;
*num = 0;
if( *str == '0' && *(str+1) == 'x' ) {
hex_mode = 1;
s = (char *)(str + 2);
}
else {
s = (char *)str;
}
while( *s != '\0' ) {
if( shift > 8 ) {
return -1; /* error */
}
if( hex_mode ) {
if( '0' <= *s && *s <= '9' ) {
c = (u32)(*s - '0');
}
else if( 'a' <= *s && *s <= 'f' ) {
c = (u32)(*s - 'a') + 10;
}
else if( 'A' <= *s && *s <= 'F' ) {
c = (u32)(*s - 'A') + 10;
}
else {
return -1; /* error */
}
*num <<= 4;
*num |= c;
}
else {
if( '0' <= *s && *s <= '9' ) {
c = (u32)(*s - '0');
}
else {
return -1; /* error */
}
*num *= 10;
*num += c;
}
shift++;
s++;
}
return 0;
}
static double gettimeofday_sec(void)
{
struct timeval tv;
#if 0
struct timeval {
time_t tv_sec; /* 秒 */
suseconds_t tv_usec; /* マイクロ秒 */
};
struct timezone {
int tz_minuteswest; /* グリニッジ標準時との差 (西方に分単位) */
int tz_dsttime; /* 夏時間調整の型 */
};
int gettimeofday(struct timeval *tv, struct timezone *tz);
#endif
gettimeofday(&tv, NULL);
return tv.tv_sec + (double)tv.tv_usec*1e-6;
}
int main(int ac, char *argv[])
{
u8 bonding_option = BONDING_OPTION_PROD;
u32 device_id[CR_NUM_OF_DEVICEID];
u8 id[CR_ID_BUF_SIZE]; /* 256byte(2048bit) */
int ret_code;
int c;
FILE *fp;
double time_start,time_end;
long double time_total = 0;
int time_count = 0;
int myseed;
time_t tloc;
u32 counter0, counter0_bak;
u64 counter1, counter1_bak;
u64 counter2, counter2_bak;
u32 i;
#ifndef DEV_CYGWIN
keyboard_initialize();
#endif
#ifdef USE_DUMMY_KEY
printf( "[TEST MODE] Use dummy key.\n");
#endif
time(&tloc);
myseed = tloc;
srand(myseed);
// ID生成前にカウンタ加算をするなら、初期値は 0 で OK
counter0 = 0x00000000;
counter1 = 0x0000000000000000ll;
counter2 = 0x0000000000000000ll;
// cr_generate_id を使用する前に呼び出す
ret_code = cr_generate_id_initialize( id );
if ( ret_code != CR_GENID_SUCCESS )
{
printf( "error : cr_generate_id_initialize\n" );
return 0; // error
}
if( ac == 1 ) {
for( i = 1 ; i < 0xffffffff; i++ ) {
u64 unit;
counter0_bak = counter0;
counter1_bak = counter1;
counter2_bak = counter2;
// counter0 は、1 ずつ加算
counter0 = i;
if( counter0 == 0 ) {
counter0 = 1;
}
// counter1 は、"14 の乱数値" を加算
unit = (u64)( ( rand() & 0x03 ) + 1 );
counter1 += unit;
// counter2 は、"0 以外の 32bit 乱数値" を加算
do {
unit = ((u64)rand() & 0xffff) | ( ((u64)rand() & 0xffff) << 16 );
}while( unit == 0 );
counter2 += unit;
// カウンタオーバーフローチェック
if( counter0 < counter0_bak ) {
fprintf(stderr,"counter0 overflow : %08x\n", (unsigned int)counter0 );
}
if( counter1 < counter1_bak ) {
fprintf(stderr,"counter1 overflow : %08x%08x\n", (unsigned int)( counter1 >> 32 ), (unsigned int)counter2 );
}
if( counter2 < counter2_bak ) {
fprintf(stderr,"counter2 overflow : %08x%08x\n", (unsigned int)( counter2 >> 32 ), (unsigned int)counter2 );
}
device_id[0] = counter0;
device_id[1] = (u32)(counter1 & 0xffffffff);
device_id[2] = (u32)((counter1 >> 32) & 0xffffffff);
device_id[3] = (u32)(counter2 & 0xffffffff);
device_id[4] = (u32)((counter2 >> 32) & 0xffffffff);
// id[0] が 0x100 毎に鍵を換える
if ( (counter0 % 0x100) == 0 )
{
if ( bonding_option == BONDING_OPTION_PROD )
bonding_option = BONDING_OPTION_DEV;
else
bonding_option = BONDING_OPTION_PROD;
}
time_start = gettimeofday_sec();
ret_code = cr_generate_id( device_id, id, bonding_option );
if( ret_code != 0 ) {
fprintf(stderr,"generate_id failed\n");
}
else {
time_end = gettimeofday_sec();
time_total += (long double)(time_end - time_start);
time_count++;
/* printf("generate_id success\n"); */
}
if (kbhit())
{
c = getch();
if( 'p' == c ) {
printf("ID[0] = 0x%08x\n", (unsigned int)device_id[0]);
printf("ID[1] = 0x%08x%08x\n", (unsigned int)device_id[2], (unsigned int)device_id[1] );
printf("ID[2] = 0x%08x%08x\n", (unsigned int)device_id[4], (unsigned int)device_id[3] );
printf("time av. = %8.8f sec\n", (double)(time_total/(long double)time_count));
cr_print_flag = 1;
}
else if( c == 'q' ) {
goto end;
}
}
else
{
cr_print_flag = 0;
}
}
}
else if( ac == 3 ) {
if( 0 == str_to_u32(&device_id[0], argv[1]) && 0 == str_to_u32(&device_id[1], argv[2]) ) {
printf("ID[0] = 0x%08x\n", (unsigned int)device_id[0]);
printf("ID[1] = 0x%08x%08x\n", (unsigned int)device_id[2], (unsigned int)device_id[1] );
printf("ID[2] = 0x%08x%08x\n", (unsigned int)device_id[4], (unsigned int)device_id[3] );
time_start = gettimeofday_sec();
cr_print_flag = 1;
if( 0 != cr_generate_id( device_id, id, bonding_option ) )
{
fprintf(stderr,"cr_generate_id failed s1=0x%08x s2_lo=0x%08x s2_hi=0x%08x\n",
(int)device_id[0], (int)device_id[1], (int)device_id[2]);
}
else {
time_end = gettimeofday_sec();
time_total += (long double)(time_end - time_start);
time_count++;
printf("time av. = %8.8f sec\n", (double)(time_total/(long double)time_count));
}
cr_print_flag = 0;
}
else {
goto err_print;
}
}
else if( ac == 4 ) {
if( 0 == str_to_u32(&device_id[0], argv[1]) && 0 == str_to_u32(&device_id[1], argv[2]) ) {
printf("ID[0] = 0x%08x\n", (unsigned int)device_id[0]);
printf("ID[1] = 0x%08x%08x\n", (unsigned int)device_id[2], (unsigned int)device_id[1] );
printf("ID[2] = 0x%08x%08x\n", (unsigned int)device_id[4], (unsigned int)device_id[3] );
fp = fopen( argv[3], "wb" );
if( fp == NULL ) {
fprintf(stderr, "failed to fopen %s\n",argv[3]);
}
else {
time_start = gettimeofday_sec();
if( 0 != cr_generate_id( device_id, id, bonding_option ) )
{
fprintf(stderr,"cr_generate_id failed s1=0x%08x s2_lo=0x%08x s2_hi=0x%08x\n",
(int)device_id[0], (int)device_id[1], (int)device_id[2]);
}
else {
time_end = gettimeofday_sec();
fwrite(id, CR_ID_BUF_SIZE, 1, fp);
}
fclose(fp);
}
}
else {
goto err_print;
}
}
else {
err_print:
fprintf(stderr,"Invalid argument!\n");
fprintf(stderr,"Usage: %s\n", argv[0]);
fprintf(stderr,"Usage: %s device_id(32bit) filename.dat\n", argv[0]);
}
end:
// cr_generate_id を使用した後に呼び出す
ret_code = cr_generate_id_finalize( id );
if ( ret_code != CR_GENID_SUCCESS )
{
printf( "error : cr_generate_id_finalize\n" );
return 0; // error
}
#ifndef DEV_CYGWIN
keyboard_finalize();
#endif
printf("end of main\n");
return 0;
}

View File

@ -0,0 +1,25 @@
OPENSSL = openssl-1.0.0-beta5
# OPENSSL = openssl-0.9.8k
ifeq ($(DEV_CYGWIN),TRUE)
OPENSSL_CONFIG_TARGET = mingw
else
OPENSSL_CONFIG_TARGET =
endif
OUT_DIR = ../
.SUFFIXES:
.PHONY: all clobber
all: $(OUT_DIR)/$(OPENSSL)/libssl.a
$(OUT_DIR)/$(OPENSSL)/libssl.a : $(OPENSSL).tar.gz
tar xzvf $< -C $(OUT_DIR)
cd $(OUT_DIR)/$(OPENSSL);./Configure $(OPENSSL_CONFIG_TARGET);make build_libs;
clobber:
$(RM) -r $(OUT_DIR)/$(OPENSSL)

View File

@ -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();
}
}

View File

@ -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 を特定する必要があります。これは、プログラム始動時に、またはこのパッケージと一緒に提供される資料 (オンラインまたはテキスト) にテキスト形式のメッセージとして含めることができます。

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,2 @@
ºOY
á,€á?heÄúI

View File

@ -0,0 +1,94 @@
#!/usr/bin/perl -w
use strict;
use File::Basename;
# バイナリファイルをCソースに変換
my $KEY_VER = 1;
my $srcfname = $ARGV[0];
my $dstfname_c;
my $dstfname_h;
my $arrayname;
my $size;
if( !$ARGV[0] || !$ARGV[1] ) {
die "parameter error.\n";
}
$_ = "cr_" . basename($srcfname, "");
s/(\..*)/_$ARGV[1]\.c/;
$dstfname_c = $_;
#s/(\..*)/\.h/;
#$dstfname_h = $_;
s/(\..*)//;
$arrayname = $_;
$size = -s $srcfname;
open SRC, "< $srcfname"
or die "Cannot open file $srcfname : $!";
open DST, "> $dstfname_c"
or die "Cannot open file temp : $!";
#open DST2, "> $dstfname_h"
# or die "Cannot open file temp : $!";
binmode( SRC );
# $sizeが16byte超(AES鍵でないなら、配列サイズを + magic_code(8) + keyLen(2) + padding(6) し、16bytesでROUNDUP
my $array_size = ( $size + 16 + 15) & 0xfffffff0;
# .c ファイルに変換して出力
printf DST "#include <stdio.h>\n\n";
printf DST "\/\/下記配列は、KEYデータの前に magic_code[8] + keyLen[2] + keyVer[1] + padding[5] のデータが挿入されています。\n\n";
printf DST "const unsigned char %s[ 0x%x ] = {\n\t", $arrayname, $array_size;
# magic code
my $magic_priv = "REDCODER";
my $magic_pub = "REDCODEU";
my @magic_list;
if( $srcfname =~ m/priv/ ) {
@magic_list = unpack( "H2H2H2H2H2H2H2H2", $magic_priv );
}else {
@magic_list = unpack( "H2H2H2H2H2H2H2H2", $magic_pub );
}
foreach my $elem ( @magic_list ) {
printf DST "0x%s, ", $elem;
}
# サイズ
printf DST "0x%02x, ", $size % 256;
printf DST "0x%02x, ", $size / 256;
# KEYバージョン
printf DST "0x%02x, ", $KEY_VER;
# パディング
my $i;
for ( $i = 0; $i < 5; $i++) {
printf DST "0x%02x, ", rand(255);
}
# KEY実体
my $buff;
my $count = 0;
while( sysread( SRC, $buff, 1 ) ) {
my $src = unpack( "C", $buff );
print DST "\n\t" if( ( $count & 0x0f ) == 0 );
printf DST "0x%02x, ", $src;
$count++;
}
print DST "\n};\n";
close SRC;
close DST;
# .h ファイルも出力
#printf DST2 "extern const unsigned char %s[ 0x%x ];\n", $arrayname, $array_size;
#close DST2;

View File

@ -0,0 +1,36 @@
#!/usr/bin/perl -w
use strict;
my $lib_name = "../libgenid.a";
my @lib_list =
(
"../openssl-1.0.0-beta5/libcrypto.a",
"../openssl-1.0.0-beta5/libssl.a",
);
# move work directory
print "cd dep_objs/\n";
chdir 'dep_objs';
# merge lib
foreach ( @lib_list )
{
print "ar x $_\n";
system "ar", "x", $_;
if ( /libnf(.*)\.a/ )
{
print "mv sys-unix.o sys-unix-$1.o\n";
system "mv", "sys-unix.o", "sys-unix-$1.o";
}
&merge_obj;
}
sub merge_obj
{
my @object_files = glob "*.o";
print "ar rcs $lib_name @object_files\n";
system "ar", "rcs", $lib_name, @object_files;
print "rm *.o\n";
system "rm", @object_files;
}

View File

@ -0,0 +1,40 @@
#!/usr/bin/perl -w
use strict;
my $lib_name = "../libgenid.a";
my @lib_list =
(
"../openssl-1.0.0-beta5/libcrypto.a",
"../openssl-1.0.0-beta5/libssl.a",
"/opt/nfast/c/ctd/gcc/lib/libnflog.a",
"/opt/nfast/c/ctd/gcc/lib/libcutils.a",
"/opt/nfast/c/ctd/gcc/lib/libnfstub.a",
"/opt/nfast/c/ctd/gcc/lib/libnfkm.a"
);
# move work directory
print "cd dep_objs/\n";
chdir 'dep_objs';
# merge lib
foreach ( @lib_list )
{
print "ar x $_\n";
system "ar", "x", $_;
if ( /libnf(.*)\.a/ )
{
print "mv sys-unix.o sys-unix-$1.o\n";
system "mv", "sys-unix.o", "sys-unix-$1.o";
}
&merge_obj;
}
sub merge_obj
{
my @object_files = glob "*.o";
print "ar rcs $lib_name @object_files\n";
system "ar", "rcs", $lib_name, @object_files;
print "rm *.o\n";
system "rm", @object_files;
}