Пример #1
0
static void
aes_xts_crypt(struct aes_xts_ctx *ctx, u_int8_t *data, u_int do_encrypt)
{
	u_int8_t block[AES_XTS_BLOCKSIZE];
	u_int i, carry_in, carry_out;

	for (i = 0; i < AES_XTS_BLOCKSIZE; i++)
		block[i] = data[i] ^ ctx->tweak[i];

	if (do_encrypt)
		rijndael_encrypt(&ctx->key1, block, data);
	else
		rijndael_decrypt(&ctx->key1, block, data);

	for (i = 0; i < AES_XTS_BLOCKSIZE; i++)
		data[i] ^= ctx->tweak[i];

	/* Exponentiate tweak */
	carry_in = 0;
	for (i = 0; i < AES_XTS_BLOCKSIZE; i++) {
		carry_out = ctx->tweak[i] & 0x80;
		ctx->tweak[i] = (ctx->tweak[i] << 1) | (carry_in ? 1 : 0);
		carry_in = carry_out;
	}
	if (carry_in)
		ctx->tweak[0] ^= AES_XTS_ALPHA;
	bzero(block, sizeof(block));
}
Пример #2
0
int
aes_key_unwrap(aes_key_wrap_ctx *ctx, const u_int8_t *C, u_int8_t *P, size_t n)
{
	u_int64_t B[2], t;
	u_int8_t A[8], *R;
	size_t i;
	int j;

	memcpy(A, C, 8);		/* A = C[0] */
	memmove(P, C + 8, n * 8);	/* P and C may overlap */

	for (j = 5, t = 6 * n; j >= 0; j--) {
		R = P + (n - 1) * 8;
		for (i = n; i >= 1; i--, t--) {
			/* MSB(64, B) = A */
			memcpy(&B[0], A, 8);
			/* MSB(64, B) = MSB(64, B) ^ t */
			B[0] ^= htobe64(t);
			/* B = MSB(64, B) | R[i] */
			memcpy(&B[1], R, 8);
			/* B = AES-1(K, B) */
			rijndael_decrypt(&ctx->ctx, (caddr_t)B, (caddr_t)B);
			/* A = MSB(64, B) */
			memcpy(A, &B[0], 8);
			/* R[i] = LSB(64, B) */
			memcpy(R, &B[1], 8);

			R -= 8;
		}
	}
	explicit_bzero(B, sizeof B);

	/* check that A is an appropriate initial value */
	return timingsafe_bcmp(A, IV, 8) != 0;
}
Пример #3
0
void aes_cbc_decrypt(rijndaelCtx *ctx, uint8_t *iva, uint8_t *data,
                     unsigned len)
{
	uint32_t *d = (uint32_t *)data;
	unsigned bs = 16;
	uint32_t buf[4], iv[4];

	memcpy(iv, iva, bs);
	while (len >= bs) {
		buf[0] = d[0];
		buf[1] = d[1];
		buf[2] = d[2];
		buf[3] = d[3];

		rijndael_decrypt(ctx, buf, d);

		d[0] ^= iv[0];
		d[1] ^= iv[1];
		d[2] ^= iv[2];
		d[3] ^= iv[3];

		iv[0] = buf[0];
		iv[1] = buf[1];
		iv[2] = buf[2];
		iv[3] = buf[3];
		d += 4;
		len -= bs;
	}
}
Пример #4
0
static void
pefs_aesni_decrypt(const struct pefs_session *xses,
    const struct pefs_ctx *xctx, const uint8_t *in, uint8_t *out)
{
	const struct pefs_aesni_ses *ses = &xses->o.ps_aesni;
	const struct pefs_aesni_ctx *ctx = &xctx->o.pctx_aesni;

	if (ses->fpu_saved >= 0)
		aesni_decrypt_ecb(ctx->rounds, ctx->dec_schedule, AES_BLOCK_LEN,
		    in, out);
	else
		rijndael_decrypt(&ctx->sw, in, out);
}
Пример #5
0
void aes_ecb_decrypt(rijndaelCtx *ctx, uint8_t *data, unsigned len)
{
	unsigned bs = 16;
	uint32_t *d;

	while (len >= bs) {
		d = (uint32_t *)data;
		rijndael_decrypt(ctx, d, d);

		len -= bs;
		data += bs;
	}
}
Пример #6
0
/* Based on RFC 3394 and NIST AES Key Wrap Specification pseudo-code.

This function is used to unwrap an encrypted AES key.  One example of its use is
in the WPA-2 protocol to get the group key.
*/
UCHAR *
AES_unwrap(UCHAR *kek, UINT16 key_len, UCHAR *cipher_text, UINT16 cipher_len)
{
    UCHAR *output;
    UCHAR a[8], b[16];
    UCHAR *r;
    gint16 i, j, n;
    rijndael_ctx  ctx;

    if (kek == NULL || cipher_len < 16 || cipher_text == NULL) {
        return NULL; /* "should not happen" */
    }

    /* Allocate buffer for the unwrapped key */

    output = (guint8 *)wmem_alloc(wmem_packet_scope(), cipher_len);

    /* Initialize variables */

    n = (cipher_len/8)-1;  /* the algorithm works on 64-bits at a time */
    memcpy(a, cipher_text, 8);
    r = output;
    memcpy(r, cipher_text+8, cipher_len - 8);

    /* Compute intermediate values */

    for (j=5; j >= 0; --j) {
        r = output + (n - 1) * 8;
        /* DEBUG_DUMP("r1", (r-8), 8); */
        /* DEBUG_DUMP("r2", r, 8); */
        for (i = n; i >= 1; --i) {
            UINT16 t = (n*j) + i;
            /* DEBUG_DUMP("a", a, 8); */
            memcpy(b, a, 8);
            b[7] ^= t;
            /* DEBUG_DUMP("a plus t", b, 8); */
            memcpy(b+8, r, 8);
            rijndael_set_key(&ctx, kek, key_len*8 /*bits*/);
            rijndael_decrypt(&ctx, b, b);  /* NOTE: we are using the same src and dst buffer. It's ok. */
            /* DEBUG_DUMP("aes decrypt", b, 16) */
            memcpy(a,b,8);
            memcpy(r, b+8, 8);
            r -= 8;
        }
    }

    /* DEBUG_DUMP("a", a, 8); */
    /* DEBUG_DUMP("output", output, cipher_len - 8); */

    return output;
}
Пример #7
0
/* Based on RFC 3394 and NIST AES Key Wrap Specification pseudo-code.

This function is used to unwrap an encrypted AES key.  One example of its use is
in the WPA-2 protocol to get the group key.
*/
UCHAR
AES_unwrap(UCHAR *kek, UINT16 key_len, UCHAR *cipher_text, UINT16 cipher_len, UCHAR *output)
{
	UCHAR a[8], b[16];
	UCHAR *r;
	UCHAR *c;
	gint16 i, j, n;
	rijndael_ctx  ctx;

	if (! kek || cipher_len < 16 || ! cipher_text || ! output) {
		return 1; /* We don't do anything with the return value */
	}

	/* Initialize variables */

	n = (cipher_len/8)-1;  /* the algorithm works on 64-bits at a time */
	memcpy(a, cipher_text, 8);
	r = output;
	c = cipher_text;
	memcpy(r, c+8, cipher_len - 8);

	/* Compute intermediate values */

	for (j=5; j >= 0; --j){
		r = output + (n - 1) * 8;
		/* DEBUG_DUMP("r1", (r-8), 8); */
		/* DEBUG_DUMP("r2", r, 8); */
		for (i = n; i >= 1; --i){
			UINT16 t = (n*j) + i;
			/* DEBUG_DUMP("a", a, 8); */
			memcpy(b, a, 8);
			b[7] ^= t;
			/* DEBUG_DUMP("a plus t", b, 8); */
			memcpy(b+8, r, 8);
			rijndael_set_key(&ctx, kek, key_len*8 /*bits*/);
			rijndael_decrypt(&ctx, b, b);  /* NOTE: we are using the same src and dst buffer. It's ok. */
			/* DEBUG_DUMP("aes decrypt", b, 16) */
			memcpy(a,b,8);
			memcpy(r, b+8, 8);
			r -= 8;
		}
	}

	/* DEBUG_DUMP("a", a, 8); */
	/* DEBUG_DUMP("output", output, cipher_len - 8); */

	return 0;
}
Пример #8
0
static int
docrypt(const unsigned char *key, size_t klen, const unsigned char *in,
    unsigned char *out, size_t len, int do_encrypt)
{
	rijndael_ctx ctx;
	int error = 0;

	memset(&ctx, 0, sizeof(ctx));
	error = rijndael_set_key(&ctx, key, klen * 8);
	if (error)
		return -1;
	if (do_encrypt)
		rijndael_encrypt(&ctx, in, out);
	else
		rijndael_decrypt(&ctx, in, out);
	return 0;
}
Пример #9
0
static int
ssh_rijndael_cbc(EVP_CIPHER_CTX *ctx, u_char *dest, const u_char *src,
    LIBCRYPTO_EVP_INL_TYPE len)
{
	struct ssh_rijndael_ctx *c;
	u_char buf[RIJNDAEL_BLOCKSIZE];
	u_char *cprev, *cnow, *plain, *ivp;
	int i, j, blocks = len / RIJNDAEL_BLOCKSIZE;

	if (len == 0)
		return (1);
	if (len % RIJNDAEL_BLOCKSIZE)
		fatal("ssh_rijndael_cbc: bad len %d", len);
	if ((c = EVP_CIPHER_CTX_get_app_data(ctx)) == NULL) {
		error("ssh_rijndael_cbc: no context");
		return (0);
	}
	if (ctx->encrypt) {
		cnow  = dest;
		plain = (u_char *)src;
		cprev = c->r_iv;
		for (i = 0; i < blocks; i++, plain+=RIJNDAEL_BLOCKSIZE,
		    cnow+=RIJNDAEL_BLOCKSIZE) {
			for (j = 0; j < RIJNDAEL_BLOCKSIZE; j++)
				buf[j] = plain[j] ^ cprev[j];
			rijndael_encrypt(&c->r_ctx, buf, cnow);
			cprev = cnow;
		}
		memcpy(c->r_iv, cprev, RIJNDAEL_BLOCKSIZE);
	} else {
		cnow  = (u_char *) (src+len-RIJNDAEL_BLOCKSIZE);
		plain = dest+len-RIJNDAEL_BLOCKSIZE;

		memcpy(buf, cnow, RIJNDAEL_BLOCKSIZE);
		for (i = blocks; i > 0; i--, cnow-=RIJNDAEL_BLOCKSIZE,
		    plain-=RIJNDAEL_BLOCKSIZE) {
			rijndael_decrypt(&c->r_ctx, cnow, plain);
			ivp = (i == 1) ? c->r_iv : cnow-RIJNDAEL_BLOCKSIZE;
			for (j = 0; j < RIJNDAEL_BLOCKSIZE; j++)
				plain[j] ^= ivp[j];
		}
		memcpy(c->r_iv, buf, RIJNDAEL_BLOCKSIZE);
	}
	return (1);
}
Пример #10
0
int ns_decrypt(u_char *key, u_char *src, u_char *dst, size_t length, size_t key_length) {
  
  if(key_length != 16) {
    ns_log_warning("rijndael key_length != 16 which will likely lead to an Bus error or "
        "segmentation fault!");
  }
  
  if(length % NS_BLOCK_SIZE != 0) {
    ns_log_warning("The length of the src must be a multiple of NS_BLOCK_SIZE "
    "(which is %d) but is %d.", NS_BLOCK_SIZE, length);
  }
  
  rijndael_ctx ctx;
  rijndael_set_key(&ctx, key, 8 * key_length);
  
  int j;
  
  // Decrypt blockwise from src to dst.
  for(j = 0; j < length; j += NS_BLOCK_SIZE) { 
    rijndael_decrypt(&ctx, &(src[j]), &(dst[j])); 
  }
  
  return 0;
}
Пример #11
0
static void
rijndael128_decrypt(caddr_t key, u_int8_t *blk)
{
	rijndael_decrypt(((rijndael_ctx *) key), (u_char *) blk,
	    (u_char *) blk);
}
Пример #12
0
static void
rijndael128_decrypt(void *key, u_int8_t *blk)
{
	rijndael_decrypt((rijndael_ctx *) key, (u_char *) blk,
	    (u_char *) blk);
}
//===========================================================================
// バッファの入力
//===========================================================================
__int64 __fastcall TAttacheCaseFileDecrypt2::InputBuffer
	(int &buff_size, char *source_buffer, char *chain_buffer,
	 TFileStream *fsIn, bool &fOpen, __int64 TotalSize)
{

char i;
int len;

char paddingNum;
char temp_buffer[BUF_SIZE];

// 入力ファイルが開かれていない
if ( fOpen == false ) {
	buff_size = 0;
	return(TotalSize);
}

// 読み出しバッファの初期化
for (i = 0; i < BUF_SIZE; i++) {
	source_buffer[i] = 0;
}

// 暗号化されたデータブロックの読み出し
len = fsIn->Read(source_buffer, BUF_SIZE);
if ( len == 0 ) {
	buff_size = 0;
	return(TotalSize);
}

TotalSize += len;

for (i = 0; i < BUF_SIZE; i++) {
	// あとのxorのためによけておく
	temp_buffer[i] = source_buffer[i];
}

// 復号処理
rijndael_decrypt(source_buffer);

// xor
for (i = 0; i < BUF_SIZE; i++) {
	source_buffer[i] ^= chain_buffer[i];
	chain_buffer[i] = temp_buffer[i]; // CBC
}

//-----------------------------------
// 最後の入力ブロック
//-----------------------------------
if (fsIn->Position+1 > fsIn->Size) {

	// Check PKCS #7 pading num
	paddingNum = source_buffer[BUF_SIZE - 1];

	if (paddingNum > -1) {

		for (i = 0; i < BUF_SIZE; i++) {
			if (source_buffer[BUF_SIZE - 1 - i] != paddingNum) {
				break;
			}
		}

		if (paddingNum == i) {
			buff_size = BUF_SIZE - (int)i;  //パディングを除いた分だけ補充
			return(TotalSize);
		}

	}

}

//static __int64 pos = 0;

//TFileStream *fsDebug = new TFileStream("C:\\Users\\eb\\Desktop\\debug.dat", fmOpenWrite);
//fsDebug->Seek(0,soFromEnd);
//ShowMessage(IntToStr(fsDebug->Position));
//pos += fsDebug->Write(source_buffer, BUF_SIZE);

//ShowMessage(fsDebug->Size);
//delete fsDebug;

buff_size = BUF_SIZE;
return(TotalSize);

}
//===========================================================================
//スレッド実行
//===========================================================================
void __fastcall TAttacheCaseFileDecrypt2::Execute()
{

int i, c, len;
float ProgressPercentNumF;  //進捗パーセンテージ(浮動小数点)

// バッファ
char source_buffer[BUF_SIZE];
char temp_buffer[BUF_SIZE];
char chain_buffer[BUF_SIZE];
char output_buffer[LARGE_BUF_SIZE];
char *headerbuffer;

//パスワード
bool fPasswordOk;
//const int KeyArrayNum = sizeof(key)/sizeof(key[0]);

String FilePath, FileName;

// ファイルストリーム
TFileStream *fsIn;
TFileStream *fsOut;

bool fInputFileOpen = false;
bool fOutputFileOpen = false;

float free_space_required;
__int64 CurrentPos, TotalSize;
__int64 CurrentDriveFreeSpaceSize;

//処理する合計サイズ
AllTotalSize = 0;

int ret;	//バッファ出力の返値
int FileIndex = 0;

char token[17] = {0, };
const char charTokenString[17] = "_AttacheCaseData";         //復号の正否に使う
const char charBrokenToken[17] = "_Atc_Broken_Data";         //ファイルが破壊されていることを示すトークン
String AtcFileTokenString;                                   //暗号化ファイルのトークン(文字列)
String AtcFileCreateDateString;                              //暗号化ファイルの生成日時(文字列)

//「復号したファイルを関連付けされたソフトで開く」一時的な設定
fTempOpenFile = fOpenFile;
//フォルダーを一度開いたか(深いフォルダーすべてを開かないように)
fOpenFolderOnce = false;

// 出力するディレクトリ
OutDirPath = IncludeTrailingPathDelimiter(OutDirPath);

String TempRelativePath;


// 平文ヘッダサイズ(データサブバージョン、破壊設定など)
int PlainHeaderSize = 0;
// 暗号化部分のヘッダサイズ
int EncryptHeaderSize = 0;

int DataVersion;        // ver.2.00~は "5", ver.2.70~は "6"
int AlgorismType;

char reserved;          // 0
//int TypeLimits;       // ミスタイプ回数 0~10  (グローバル:public宣言とした)
//bool fDestroy;        // 破壊するか否か 0 or 1 (グローバル:public宣言とした)

String PrefixString;	  //ファイルリストの接頭辞(Fn_*, U_*)

int flush, status;      // zlib
z_stream z;             // zlibライブラリとやりとりするための構造体
bool fInputEnd = false; // 入力ストリームの終了

//ヘッダデータから必要情報を取り出すための
TMemoryStream *pms;     // メモリストリーム

int idx;
TStringList *DataList;
TStringList *tsv;

TStringList *FileList = new TStringList();  // 0: ファイル名
__int64 *FileSizeList = 0;               // 1: ファイルサイズ(フォルダは-1)
int *FileAttrList     = 0;               // 2: 属性
int *FileDtChangeList = 0;               // 3: 更新日
int *FileTmChangeList = 0;               // 4: 更新時
int *FileDtCreateList = 0;               // 5: 作成日
int *FileTmCreateList = 0;               // 6: 作成時

int rest;
int buf_size;

//----------------------------------------------------------------------
// 平文のヘッダ内容チェック

try {
	fsIn = new TFileStream(AtcFilePath, fmOpenRead | fmShareDenyNone);
}
catch(...) {
	//'復号するファイルを開けません。他のアプリケーションが使用中の可能性があります。'
	MsgText = LoadResourceString(&Msgdecrypt::_MSG_ERROR_FILE_OPEN);
	MsgType = mtError;
	MsgButtons = TMsgDlgButtons() << mbOK;
	MsgDefaultButton = mbOK;
	Synchronize(&PostConfirmMessageForm);
	goto LabelError;
}

fInputFileOpen = true;

// 平文ヘッダサイズを取得
fsIn->Read(&PlainHeaderSize, sizeof(int));
// トークンを取得
fsIn->Read(token, 16);

if (StrComp(token, charTokenString) != 0 ) {
	//--------------------------------------------------------
	//実は自己実行形式ファイル?(拡張子偽装されている場合も)
	//--------------------------------------------------------
	// サイズを再取得
	fsIn->Seek(-(__int64)sizeof(__int64), TSeekOrigin::soEnd);
	fsIn->Read(&AllTotalSize, sizeof(__int64));
	// 位置を戻す
	fsIn->Seek(-(AllTotalSize + sizeof(__int64)), TSeekOrigin::soEnd);
	// もう一度、平文ヘッダサイズを読み込む
	fsIn->Read(&PlainHeaderSize, sizeof(int));
	// もう一度、トークンを取得
	fsIn->Read(token, 16);

	// トークンを再チェック
	if (StrComp(token, charTokenString) != 0 ) {

		if ( StrComp(token, charBrokenToken) == 0 ) {
			//'復号するファイルを開けません。この暗号化ファイルは破壊されています。'
			MsgText = LoadResourceString(&Msgdecrypt::_MSG_ERROR_FILE_BROKEN);
			MsgType = mtError;
			MsgButtons = TMsgDlgButtons() << mbOK;
			MsgDefaultButton = mbOK;
			Synchronize(&PostConfirmMessageForm);
		}
		else {
			// '暗号化ファイルではありません。アタッシェケースによって暗号化されたファイルでないか、'+#13+
			// 'ファイルが壊れている可能性があります。'
			MsgText = LoadResourceString(&Msgdecrypt::_MSG_ERROR_FILE_NOT_ATC);
			MsgType = mtError;
			MsgButtons = TMsgDlgButtons() << mbOK;
			MsgDefaultButton = mbOK;
			Synchronize(&PostConfirmMessageForm);
		}
		goto LabelError;
	}

}

//-----------------------------------
// データバージョンチェック
//-----------------------------------
DataVersion = -1;
fsIn->Read(&DataVersion, sizeof(int));

if (DataVersion > ATC_DATA_FILE_VERSION && DataVersion < 200) {
	//'データバージョンがちがいます。復号できません。'+#13+
	//'ファイルは上位バージョンのアタッシェケースで暗号化されています。'+#13+
	//'最新版を入手して復号を試みてください。';
	MsgText = LoadResourceString(&Msgdecrypt::_MSG_ERROR_FILE_HIGHER_VERSION);
	MsgType = mtError;
	MsgButtons = TMsgDlgButtons() << mbOK;
	MsgDefaultButton = mbOK;
	Synchronize(&PostConfirmMessageForm);
	goto LabelError;
}
else if (DataVersion <= 103) {

	// Blowfishで暗号化されたファイル
	// 正式版では正常に復号されるが、ここではエラーとする

	//'データバージョンがちがいます。復号できません。'+#13+
	//'ファイルはver.1のアタッシェケースで暗号化されています。'+#13+
	//'古いバージョン(ver.2.75以前)か正式版を入手して復号を試みてください。';
	MsgText = LoadResourceString(&Msgdecrypt::_MSG_ERROR_FILE_LOWER_VERSION);
	MsgType = mtError;
	MsgButtons = TMsgDlgButtons() << mbOK;
	MsgDefaultButton = mbOK;
	Synchronize(&PostConfirmMessageForm);
	goto LabelError;

}
else {

	// 104 ~
	// Rijndaelで暗号化されている

	// アルゴリズムタイプ
	fsIn->Read(&AlgorismType, sizeof(int));
	// ヘッダサイズを読み込む
	fsIn->Read(&EncryptHeaderSize, sizeof(int));
	// int型からポインタキャストでchar配列を取り出す
	headerbuffer = (char*) & PlainHeaderSize;
	// データサブバージョンチェック(ver.2.70~)
	if (headerbuffer[0] >= 6) {
		TypeLimits = (int)headerbuffer[2];
		fDestroy = (bool)headerbuffer[3];
		// 有効範囲(1~10)かチェック
		if (TypeLimits < 1 || 10 < TypeLimits) {
			TypeLimits = 3; // デフォルト
		}
	}
	else { // headerbuffer[0] == 5            //旧バージョン
		TypeLimits = 3;
		fDestroy = false;
	}
}


//-----------------------------------
// 復号の準備
//-----------------------------------

// テーブル生成
gentables();

// パスワードのセット
gkey(8, 8, key);

//-----------------------------------
// 暗号部ヘッダの復号
//-----------------------------------

pms = new TMemoryStream;

// IVの読み込み
fsIn->Read(chain_buffer, BUF_SIZE);

len = 0;

while (len < EncryptHeaderSize) {

	// 読み出しバッファ
	for (c = 0; c < BUF_SIZE; c++) {
		source_buffer[c] = 0;
	}
	// 暗号化されたデータブロックの読み出し
	len += fsIn->Read(source_buffer, BUF_SIZE);

	for (c = 0; c < BUF_SIZE; c++) {
		// あとのxorのためによけておく
		temp_buffer[c] = source_buffer[c];
	}

	// 復号処理
	rijndael_decrypt(source_buffer);

	// xor
	for (c = 0; c < BUF_SIZE; c++) {
		source_buffer[c] ^= chain_buffer[c];
		chain_buffer[c] = temp_buffer[c]; // CBC
	}

	pms->Write(source_buffer, BUF_SIZE);

}

pms->Seek((__int64)0, TSeekOrigin::soBeginning);  //ポインタを先頭へ戻す
DataList = new TStringList;
DataList->LoadFromStream(pms, TEncoding::GetEncoding(932));  // shift-jis

//-----------------------------------
// 復号正否(復号できたか)
//-----------------------------------

//MsgText = DataList->Strings[0];
//MsgType = mtError;
//MsgButtons = TMsgDlgButtons() << mbOK;
//MsgDefaultButton = mbOK;
//Synchronize(&PostConfirmMessageForm);

if (DataList->Count == 0 || DataList->Strings[0].Pos("AttacheCase") == 0) {
	fPasswordOk = false;
}
else{
	fPasswordOk = true;   //パスワード合致
}

if ( fPasswordOk == false ) {
	//'パスワードがちがいます。復号できません。'+#13+
	//'場合によってはファイルが壊れている可能性もあります。';
	MsgText = LoadResourceString(&Msgdecrypt::_MSG_ERROR_PASSWORD_WRONG);
	if ( fCompare == true ) {
		//メッセージに'コンペアに失敗しました。'を追加
		MsgText += "\n" + LoadResourceString(&Msgdecrypt::_MSG_ERROR_COMPARE_FILE);
	}
	MsgType = mtError;
	MsgButtons = TMsgDlgButtons() << mbOK;
	MsgDefaultButton = mbOK;
	Synchronize(&PostConfirmMessageForm);
	delete DataList;
	goto LabelTypeMiss;
}

//-----------------------------------
// 復号時のエンコーディング判定
//-----------------------------------
pms->Position = 0;
//DataList->LoadFromStream(pms, TEncoding::UTF8);
DataList->LoadFromStream(pms, TEncoding::GetEncoding(65001));

PrefixString = "Fn_";
for (i = 0; i < DataList->Count; i++) {
	if ( DataList->Strings[i].Pos("U_0") == 1){
		PrefixString = "U_";	//新バージョン(ver.2.8.0~)で暗号化されているようだ
		break;
	}
}

// Unicodeではないので従来のShift-JISで再度読み直し
if (PrefixString == "Fn_") {
	pms->Position = 0;
	DataList->LoadFromStream(pms, TEncoding::GetEncoding(932));
}

//===================================
// デバッグ
//ShowMessage(DataList->Text);
//===================================

#ifdef _DEBUG
DataList->SaveToFile(OutDirPath + ExtractFileName(AtcFilePath) + ".txt");
#endif

delete pms;


//-----------------------------------
// 暗号化ファイルの生成日時
//-----------------------------------
//※特に今は使用していないが、将来的に
//  期限付きでファイルを復号できなくなる
//  などの機能を追加しても良いかも。
//-----------------------------------
AtcFileCreateDateString = DataList->Strings[1];

//-----------------------------------
// ヘッダデータからファイルリストや
// ファイル情報などを各変数を動的確保
//-----------------------------------

FileSizeList = new __int64[DataList->Count];  // 1: ファイルサイズ(フォルダは-1)
FileAttrList = new int[DataList->Count];      // 2: 属性
FileDtChangeList = new int[DataList->Count];  // 3: 更新日
FileTmChangeList = new int[DataList->Count];  // 4: 更新時
FileDtCreateList = new int[DataList->Count];  // 5: 作成日
FileTmCreateList = new int[DataList->Count];  // 6: 作成時

DataList->NameValueSeparator = ':';

tsv = new TStringList;
tsv->Delimiter = '\t';
tsv->StrictDelimiter = true;

char lpPath[MAX_PATH];

for (i = 0; i < DataList->Count; i++) {
	idx = DataList->IndexOfName(PrefixString+IntToStr(i));
	if (idx > 0) {
		tsv->DelimitedText = DataList->ValueFromIndex[idx];

		// ディレクトリ・トラバーサル対策(ver.2.8.5.0~)
		bool fDirectoryTraversal = false;
		AnsiString CanonicalizePath = AnsiString(OutDirPath + tsv->Strings[0]);

		if (CanonicalizePath.Length() < MAX_PATH) {
			// ファイルパスを正規化
			if (PathCanonicalize(lpPath, CanonicalizePath.c_str()) == true) {
				// 正規化したパスが保存先と一致するか
				if (AnsiString(lpPath).Pos(OutDirPath) != 1 ){
					fDirectoryTraversal = true;
				}
			}
			else{
				fDirectoryTraversal = true;
			}
		}
		else{
			fDirectoryTraversal = true;
		}

		if (fDirectoryTraversal == true) {
			//'不正なファイルパスが含まれています。復号できません。';
			MsgText = LoadResourceString(&Msgdecrypt::_MSG_ERROR_INVALID_FILE_PATH) +
								"\n" + CanonicalizePath;
			MsgType = mtError;
			MsgButtons = TMsgDlgButtons() << mbOK;
			MsgDefaultButton = mbOK;
			Synchronize(&PostConfirmMessageForm);
			delete DataList;
			goto LabelTypeMiss;
		}

		FileList->Add(tsv->Strings[0]);                        // 0: ファイルパス
		FileSizeList[i] = StrToIntDef(tsv->Strings[1], -1);    // 1: ファイルサイズ(フォルダは-1)
		FileAttrList[i] = StrToIntDef(tsv->Strings[2], -1);    // 2: 属性
		FileDtChangeList[i] = StrToIntDef(tsv->Strings[3], -1);// 3: 更新日
		FileTmChangeList[i] = StrToIntDef(tsv->Strings[4], -1);// 4: 更新時
		FileDtCreateList[i] = StrToIntDef(tsv->Strings[5], -1);// 5: 作成日
		FileTmCreateList[i] = StrToIntDef(tsv->Strings[6], -1);// 6: 作成時
	}

}

delete tsv;
delete DataList;


//-----------------------------------
//ディスクの空き容量チェック
//-----------------------------------

CurrentDriveFreeSpaceSize = GetDiskFreeSpaceNum(OutDirPath);

if (CurrentDriveFreeSpaceSize > -1 && fCompare == false) {
	if ( AllTotalSize > CurrentDriveFreeSpaceSize ) {
		//'復号する先のドライブの空き容量が足りません。'+#13+
		//'復号するには、約%dMBの空き容量が必要です。復号処理を中止します。';
		MsgText = LoadResourceString(&Msgdecrypt::_MSG_ERROR_DRIVE_NO_FREE_SPACE);
		free_space_required = (float)AllTotalSize/1024/1024;  // MB
		MsgText = String().sprintf(MsgText.c_str(), free_space_required);
		MsgType = mtError;
		MsgButtons = TMsgDlgButtons() << mbOK;
		MsgDefaultButton = mbOK;
		Synchronize(&PostConfirmMessageForm);
		goto LabelError;
	}
}
else{
	// OK!
	//
}

//-----------------------------------
//複数フォルダ/ファイルを開こうとしているので確認
//-----------------------------------

//復号したファイルを関連付けされたソフトで開くか
if ( fTempOpenFile == true && FileList->Count > 4 && fCompare == false) {

	//'5つ以上のファイルを復号後に開こうとしていますが、処理を続けますか?'+#13+
	//'「いいえ」を選択すると、開かず復号します。';
	MsgText = LoadResourceString(&Msgdecrypt::_MSG_CONFIRM_OPEN_DECRYPTED_FILES);
	MsgType = mtConfirmation;
	MsgButtons = TMsgDlgButtons() << mbYes << mbNo << mbCancel;
	MsgDefaultButton = mbCancel;
	Synchronize(&PostConfirmMessageForm);

	if ( MsgReturnVal == mrCancel ) {
		goto LabelStop;
	}
	else if ( MsgReturnVal == mrNo ) {
		fTempOpenFile = true;
	}

}

//-----------------------------------
// 復号開始
//-----------------------------------

if (fCompare == false) {
	//'復号しています...'
	ProgressStatusText = LoadResourceString(&Msgdecrypt::_LABEL_STATUS_TITLE_DECRYPTING);
	ProgressMsgText = ExtractFileName(AtcFilePath);
}
else{
	//'コンペアしています...'
	ProgressStatusText = LoadResourceString(&Msgdecrypt::_LABEL_STATUS_TITLE_COMPARING);
	ProgressMsgText = ExtractFileName(AtcFilePath);
}

// ファイル(データ本体)サイズを取得する
AllTotalSize = fsIn->Size - fsIn->Position + 1;
// 初期化ベクトルの読み出し
TotalSize = fsIn->Read(chain_buffer, BUF_SIZE);

// zlib 前準備
// 圧縮においてすべてのメモリ管理をライブラリに任せる
z.zalloc = Z_NULL;
z.zfree = Z_NULL;
z.opaque = Z_NULL;

if (inflateInit(&z) != Z_OK) {
	// エラー
	// zlibエラーは最後でまとめてメッセージ処理
	goto LabelError;
}

// 通常は deflate() の第2引数は Z_NO_FLUSH にして呼び出す
flush = Z_NO_FLUSH;

// 入出力バッファ
for (i = 0; i < LARGE_BUF_SIZE; i++) {
	output_buffer[i] = 0;
}

z.avail_in  = 0;               // 入力バッファ中のデータのバイト数
z.next_in   = Z_NULL;          // 入力バッファ中のデータのバイト数
z.next_out  = output_buffer;   // 出力バッファ残量
z.avail_out = LARGE_BUF_SIZE;  // 出力ポインタ(展開するので大きめに)
status      = Z_OK;

while (Terminated == false) {

	//-----------------------------------
	// 入力
	//-----------------------------------
	if (z.avail_in == 0) {

		TotalSize = InputBuffer(len, source_buffer, chain_buffer, fsIn, fInputFileOpen, TotalSize);
		z.avail_in = len;
		z.next_in = source_buffer;

		if ( len == 0 ) {  //入力ストリーム終了
			fInputEnd = true;
		}

	}

	//-----------------------------------
	// 展開
	//-----------------------------------
	status = inflate(&z, flush);


	//-----------------------------------
	// 処理ステータス
	//-----------------------------------
	if ( status == Z_OK ){

		if ( z.avail_out == 0 ) {

			ret = OutputBuffer(output_buffer, LARGE_BUF_SIZE,
												 fsOut, fOutputFileOpen,
												 FileList, FileIndex,
												 FileSizeList, FileAttrList,
												 FileDtChangeList, FileTmChangeList,
												 FileDtCreateList, FileTmCreateList);

			if ( ret == 0) {
				z.next_out = output_buffer;
				z.avail_out = LARGE_BUF_SIZE;
			}
			else if (ret == -1) {
				goto LabelError;
			}
			else{
				goto LabelStop;
			}

		}//end if (z.avail_out == 0);


	}
	//-----------------------------------
	// バッファエラー
	//-----------------------------------
	else if ( status == Z_BUF_ERROR ) { //出力バッファがいっぱいの可能性

		//出力バッファをクリアにして継続させる
		len = LARGE_BUF_SIZE - z.avail_out;
		ret = OutputBuffer(output_buffer, len,
											 fsOut, fOutputFileOpen,
											 FileList, FileIndex,
											 FileSizeList, FileAttrList,
											 FileDtChangeList, FileTmChangeList,
											 FileDtCreateList, FileTmCreateList);
		if (ret == 0) {
			z.next_out = output_buffer;
			z.avail_out = LARGE_BUF_SIZE;
		}
		else if ( ret == -1) {
			goto LabelError;
		}
		else{
			goto LabelStop;
		}

	}
	//-----------------------------------
	// 終了
	//-----------------------------------
	else if (status == Z_STREAM_END) {
		break;
	}
	//-----------------------------------
	// エラー
	//-----------------------------------
	else{
		// #define Z_OK              0
		// #define Z_STREAM_END      1
		// #define Z_NEED_DICT       2
		// #define Z_ERRNO         (-1)
		// #define Z_STREAM_ERROR  (-2)
		// #define Z_DATA_ERROR    (-3)
		// #define Z_MEM_ERROR     (-4)
		// #define Z_BUF_ERROR     (-5)
		// #define Z_VERSION_ERROR (-6)
		goto LabelError;
	}


	//-----------------------------------
	//進捗状況表示
	ProgressPercentNumF = (float)TotalSize/AllTotalSize;
	ProgressPercentNum = (int)(ProgressPercentNumF*100);
	if (AllTotalSize < 104857600) {	// 100MB未満
		ProgressPercentNumText = IntToStr(ProgressPercentNum)+"%";
	}
	else{
		ProgressPercentNumText = FloatToStrF(ProgressPercentNumF*100, ffNumber, 4, 1)+"%";
	}

	if ( fInputEnd == true) {
		break;
	}

}//while (!Terminated);

if (Terminated == true) {
	//ユーザーキャンセルで抜けてきた
	goto LabelStop;
}

//----------------------------------------------------------------------
// 万が一、出力バッファに余りがある場合
//----------------------------------------------------------------------

len = LARGE_BUF_SIZE - z.avail_out;
ret = OutputBuffer(output_buffer, len,
									 fsOut, fOutputFileOpen,
									 FileList, FileIndex,
									 FileSizeList, FileAttrList,
									 FileDtChangeList, FileTmChangeList,
									 FileDtCreateList, FileTmCreateList);
if ( ret == 0 ) {
}
else if ( ret == -1 ){
	goto LabelError;
}
else{
	goto LabelStop;
}


if (inflateEnd(&z) != Z_OK) {
	goto LabelError;
}

ProgressPercentNum = 100;
//'完了'
ProgressStatusText = LoadResourceString(&Msgdecrypt::_LABEL_STATUS_TITLE_COMPLETE);
ProgressMsgText = ExtractFileName(AtcFilePath);

if ( fInputFileOpen == true ) {
	delete fsIn;
	fInputFileOpen = false;
}
if ( fOutputFileOpen == true ) {
	delete fsOut;
	fOutputFileOpen = false;
}

delete FileList;
delete [] FileSizeList;      // 1: ファイルサイズ(フォルダは-1)
delete [] FileAttrList;      // 2: 属性
delete [] FileDtChangeList;  // 3: 更新日
delete [] FileTmChangeList;  // 4: 更新時
delete [] FileDtCreateList;  // 5: 作成日
delete [] FileTmCreateList;  // 6: 作成時

//復号成功
StatusNum = 1;
return;


//-----------------------------------
//パスワード入力ミスの後始末
//-----------------------------------
LabelTypeMiss:

	ProgressPercentNum = 0;

	//'エラー'
	ProgressStatusText = LoadResourceString(&Msgdecrypt::_LABEL_STATUS_TITLE_ERROR);
	//'復号に失敗しました。'
	ProgressMsgText = LoadResourceString(&Msgdecrypt::_LABEL_STATUS_DETAIL_FAILED);

	if ( fInputFileOpen == true ) {
		delete fsIn;
		fInputFileOpen = false;
	}
	if ( fOutputFileOpen == true ) {
		delete fsOut;
		fOutputFileOpen = false;
	}

	delete FileList;
	delete [] FileSizeList;
	delete [] FileAttrList;
	delete [] FileDtChangeList;
	delete [] FileTmChangeList;
	delete [] FileDtCreateList;
	delete [] FileTmCreateList;

	StatusNum = -1;
	return;


//-----------------------------------
//エラーの後始末
//-----------------------------------
LabelError:

	ProgressPercentNum = 0;

	if ( status < 0 ){
		//'zlibライブラリからエラーを返されました。'
		//'エラー番号:'
		MsgText = LoadResourceString(&Msgdecrypt::_MSG_ERROR_ZLIB) + IntToStr(status) + "\n" + z.msg;
		if ( fCompare == true ) {
			//メッセージに'コンペアに失敗しました。'を追加
			MsgText += "\n" + LoadResourceString(&Msgdecrypt::_MSG_ERROR_COMPARE_FILE);
		}
		MsgType = mtError;
		MsgButtons = TMsgDlgButtons() << mbOK;
		MsgDefaultButton = mbOK;
		Synchronize(&PostConfirmMessageForm);
	}

	//'エラー'
	ProgressStatusText = LoadResourceString(&Msgdecrypt::_LABEL_STATUS_TITLE_ERROR);

	if (fCompare == true) {
		//'コンペアで問題を見つけたようです。';
		ProgressMsgText = LoadResourceString(&Msgdecrypt::_LABEL_STATUS_DETAIL_COMPARE_FAILED);
	}
	else{
		//'復号に失敗しました。'
		ProgressMsgText = LoadResourceString(&Msgdecrypt::_LABEL_STATUS_DETAIL_FAILED);
	}

	if ( fInputFileOpen == true ) {
		delete fsIn;
		fInputFileOpen = false;
	}
	if ( fOutputFileOpen == true ) {
		delete fsOut;
		fOutputFileOpen = false;
	}

	delete FileList;
	delete [] FileSizeList;
	delete [] FileAttrList;
	delete [] FileDtChangeList;
	delete [] FileTmChangeList;
	delete [] FileDtCreateList;
	delete [] FileTmCreateList;

	StatusNum = -2;
	return;


//-----------------------------------
//ユーザーキャンセルの後始末
//-----------------------------------
LabelStop:

	ProgressPercentNum = 0;
	//'キャンセル'
	ProgressStatusText = LoadResourceString(&Msgdecrypt::_LABEL_STATUS_TITLE_USER_CANCEL);
	//'復号が中止されました。'
	ProgressMsgText = LoadResourceString(&Msgdecrypt::_LABEL_STATUS_DETAIL_STOPPED);

	if ( fInputFileOpen == true ) {
		delete fsIn;
		fInputFileOpen = false;
	}
	if ( fOutputFileOpen == true ) {
		delete fsOut;
		fOutputFileOpen = false;
	}

	delete FileList;
	delete [] FileSizeList;
	delete [] FileAttrList;
	delete [] FileDtChangeList;
	delete [] FileTmChangeList;
	delete [] FileDtCreateList;
	delete [] FileTmCreateList;

	StatusNum = 0;
	return;

}