bool StandardEncryption::EncryptFileEx2 (char *szSource, char *szDestination, char *szPassword, bool bEncrypt) {
	
	char szNewsource[SIZE_STRING];
	bool bEncres = false;
	DWORD dwLastError = 0;

	if (strcmp (szSource, szDestination) == 0) {
	
		ZeroMemory (szNewsource, SIZE_STRING);
		strcpy_s (szNewsource, SIZE_STRING, szSource);
		strcat_s (szNewsource, SIZE_STRING, "src");

		// Now move the source file to the new source file
		if (MoveFile (szSource, szNewsource) != 0) {

			bEncres = EncryptFile (szNewsource, szSource, szPassword, bEncrypt);

			if (bEncres == true) {
				if (DeleteFile (szNewsource) == 0) {
					dwLastError = GetLastError ();
					OutputInt ("EncryptFileEx2: DeleteFile FAILED! Err: ", dwLastError);
				}
			} else {

				if (DeleteFile (szSource) == 0) {
					dwLastError = GetLastError ();
					OutputInt ("EncryptFileEx2: DeleteFile (Recovery) FAILED! Err: ", dwLastError);
				} else {					
					if (MoveFile (szNewsource, szSource) == 0) {
						dwLastError = GetLastError ();
						OutputInt ("EncryptFileEx2: MoveFile (Recovery) FAILED! Err: ", dwLastError);
					}
				}
			}			

		} else {
			dwLastError = GetLastError ();
			OutputInt ("EncryptFileEx2: MoveFile FAILED! Err: ", dwLastError);
			return false;
		}

	} else {
		// The file paths are not the same, so just encrypt anyway.
		return EncryptFile (szSource, szDestination, szPassword, bEncrypt);
	}

	return bEncres;
}
Exemple #2
0
BOOL CEncryptFile::EncryptDir(CString strKey, CString strSrcDir, CString strDstDir,  CProgressCtrl *pCtal)
{
								 //AfxMessageBox("创建文件夹"+target);    
	CFileFind finder;
	CString stPath;
	BOOL re = FALSE;
	stPath.Format(_T("%s/*.*"), strSrcDir);
	BOOL bWorking = finder.FindFile(stPath);
	while (bWorking)
	{
		bWorking = finder.FindNextFile();
		if (finder.IsDirectory() && !finder.IsDots())//是文件夹 而且 名称不含 . 或 ..    
		{
			//递归解密+"/"+finder.GetFileName()  
			EncryptDir(strKey, finder.GetFilePath(), strDstDir + _T("\\") + finder.GetFileName(), pCtal);
		}
		else//是文件 则直接解密   
		{
			CString stSrcFile = finder.GetFilePath();
			BOOL result = (GetFileAttributes(stSrcFile) & FILE_ATTRIBUTE_DIRECTORY);
			if (!result)
			{
				re = EncryptFile(strKey, finder.GetFilePath(), strDstDir + _T("\\") + finder.GetFileName());
				pCtal->StepIt();
			}
		}
	}
	return TRUE;
}
Exemple #3
0
int main(int argc, char const *argv[])
{

	

	if (argc < 7)
	{
		std::cout << "Usage: " << argv[0] << " filename n e style p q\n n is the modulus\n e is the exponent\n style = 1 or 0 for encrypt and decrypt respecively\n p and q are the primes that compose n" << std::endl;
		return 0;
	}

	mpz_t modulus, exponent, p, q, pm1, qm1, pq, d;
	mpz_init_set_str(modulus, argv[2], 10);
	mpz_init_set_str(exponent, argv[3], 10);
	mpz_init_set_str(p, argv[5], 10);
	mpz_init_set_str(q, argv[6], 10);
	int style = atoi(argv[4]);


	std::cout << argv[0] << " " << argv[1] << " " << argv[2] << " " << argv[3] << " " << argv[4] << " " << std::endl;
	//std::vector<unsigned char> in = readfile(argv[1]);


if (style)
{
	/* code */
	EncryptFile(argv[1], modulus, exponent);
	std::cout << "encrypt complete" << std::endl;
}
else
{
	mpz_init(pm1);
	mpz_init(qm1);
	mpz_init(pq);
	mpz_init(d);
	mpz_sub_ui(pm1, p, 1);
	mpz_sub_ui(qm1, q, 1);
	mpz_mul(pq, pm1, qm1);
	
	MultInverse(exponent, pq, d);
	std::cout << "D calculation complete" << std::endl;

	EncryptFile(argv[1], modulus, d);
	std::cout << "Decrypt complete" << std::endl;
}
	return 0;
}
Exemple #4
0
void vmsFDMCustomizations::Save(HANDLE hFile)
{
	DWORD dw;
	
	vmsMemFile file;
	file.Use (hFile, FALSE);

	dw = m_iKey;	
	file.WriteFile (&dw, sizeof (dw));

	dw = 0;	
	file.WriteFile (&dw, sizeof (dw));

	WriteString (file, get_Customizer ());

	file.WriteFile (&m_dwAffiliateID, sizeof (DWORD));

	

	
	dw = m_vBanners.size ();
	file.WriteFile (&dw, sizeof (dw));

	for (int i = 0; i < m_vBanners.size (); i++)
	{
		

		vmsFDMBanner* banner = &m_vBanners [i];

		file.WriteFile (&banner->dwSize, sizeof (dw));
	
		file.WriteFile (banner->pbImage, banner->dwSize);

		WriteString (file, banner->pszLinksTo);
		file.WriteFile (banner->szType, 4);
	}

	

	file.WriteFile (&m_bUseBtn, sizeof (m_bUseBtn));

	if (m_bUseBtn)
	{
		WriteString (file, m_Btn.pszText);
		WriteString (file, m_Btn.pszLinksTo);
		
		file.WriteFile (&m_Btn.dwSize, sizeof (DWORD));

		file.WriteFile (m_Btn.pbIcon, m_Btn.dwSize);
	}

	
	file.WriteFile (&m_bShowFDMCustBtn, sizeof (BOOL));

	EncryptFile (file);
	file.Done ();
}
Exemple #5
0
bool Block::EncryptFile(Stream &stream, const BinaryString &key, const BinaryString &iv, Block &block)
{
	String fileName;
	if(!EncryptFile(stream, key, iv, block.mDigest, &fileName))
		return false;
	
	block.mFile = new File(fileName, File::Read);
	block.mOffset = 0;
	block.mSize = block.mFile->size();
	return true;
}
bool StandardEncryption::EncryptFileEx3 (char *szSource, char *szDestination, char *szPassword, bool bEncrypt) {

	char szDestpathonly[SIZE_STRING];
	ZeroMemory (szDestpathonly, SIZE_STRING);

	char szDestfileonly[SIZE_STRING];
	ZeroMemory (szDestfileonly, SIZE_STRING);

	// Get just the path of the destination specified
	m_Dirscanner.GetPathOnly (szDestination, szDestpathonly, szDestfileonly, "\\");

	// Now recursively create each folder of the destination path
	m_Dirscanner.CreateFolderEx (szDestpathonly);

	// Now encrypt as normal
	return EncryptFile (szSource, szDestination, szPassword, bEncrypt);

}
Exemple #7
0
static int encfs_create(const char* path, mode_t mode, struct fuse_file_info* fi) {

    (void) fi;
    
    char fpath[PATH_MAX]; // Full buffer to pass to static function
	char tpath[PATH_MAX];
	
	char *key = DJ_DATA->encfs_keyphrase;
	
	dj_fullpath(fpath, path);
	tmpFileName(fpath, tpath);
	

    int real, temp;
    temp = creat(tpath, mode);
    real = creat(fpath, mode);
    
    if(real == -1)
		return -errno;
	if(temp == -1)
		return -errno;
		
	FILE *realFile = fdopen(real, "wb");
	FILE *tmpFile = fdopen(temp, "wb");
	
	EncryptFile(tmpFile, realFile, key);

	fclose(realFile);
	fclose(tmpFile);
	
	remove(tpath);


	SetEncryptedFlag(fpath, true);

    return 0;
}
Exemple #8
0
int main(int argc, char **args) {
	if(argc != 4) {
		cout<<"Usage: ./scube <filename> <threshold> <nshares>"<<endl;
		return 1;
	}
	
	const char* filename = (const char*) args[1];
	int threshold = atoi(args[2]);
	int nshares = atoi(args[3]);
	char const *inFilenames[6] = {"test.cpp.000", "test.cpp.001", "test.cpp.002"};//,"test.cpp.003","test.cpp.004","test.cpp.005"};
	//SecretShareFile(threshold, nshares, filename, "x");
	//SecretShareFile(3, 5, "test.cpp", "x");
	//SecretRecoverFile(threshold, "lord.cpp", (char* const*) inFilenames);
	SecretRecoverFile(3, "recovered.cpp", (char* const*) inFilenames);
	FILE *fd = fopen("test.cpp", "r");
	char *in = (char *) malloc(512);
	fread(in, 1, 512, fd);
	char *out = (char *) malloc(512);
	fread(out, 1, 512, fd);
	EncryptFile("test.cpp", "test.cpp.enc", "passphrase");
	//cout<<out<<endl;
	//AES_CTR_Encrypt("abcd12345678ababababffffffffffff", "ababa", in, out);
	return 1;
}
bool StandardEncryption::EncryptFileEx (char *szSource, char *szDestination, char *szPassword, bool bEncrypt) {
	// This function will call the encryptfile function, but this function in particular will handle
	// same name source and destination files. - If the destination file is the same as the source file
	// then the destination filepath is renamed with -enc, and then after encryption the original file
	// is deleted and replaced with the encrypted file.

	char szNewdest[SIZE_STRING];
	bool bEncres = false;
	DWORD dwLastError = 0;
	//int retrcount = 0;

	if (strcmp (szSource, szDestination) == 0) {
		
		ZeroMemory (szNewdest, SIZE_STRING);
		strcpy_s (szNewdest, SIZE_STRING, szDestination);
		strcat_s (szNewdest, SIZE_STRING, "enc");

		// Now encrypt the old file to the new one
		bEncres = EncryptFile (szSource, szNewdest, szPassword, bEncrypt);

		// Now we delete the old file, first setting it's attributes to normal
		if (SetFileAttributes (szSource, FILE_ATTRIBUTE_NORMAL) == 0) {
			dwLastError = GetLastError ();
			OutputInt ("EncryptFileEx: SetFileAttributes FAILED! Err: ", dwLastError);
		}

		//retrcount = 0;
		if (DeleteFile (szSource) == 0) {
			dwLastError = GetLastError ();
			OutputInt ("EncryptFileEx: DeleteFile FAILED! Err: ", dwLastError);
			//retrcount++;

			//if (retrcount > 300) {
			//	break;
			//}
		}

		//retrcount = 0;
		// Now move the new file to the same path as the old one
		
		for (int i=0;i<50;i++) {
			if (MoveFile (szNewdest, szSource) == 0) {
				dwLastError = GetLastError ();
				OutputInt ("EncryptFileEx: MoveFile FAILED! Err: ", dwLastError);
				//retrcount++;

				//if (retrcount > 300) {
				//	break;
				//}
			} else {
				break;
			} 
		}
	
		return bEncres;
	} else {
		// The file paths are not the same, so just encrypt anyway.

		return EncryptFile (szSource, szDestination, szPassword, bEncrypt);
	}
}
Exemple #10
0
static int encfs_write(const char *path, const char *buf, size_t size,
		     off_t offset, struct fuse_file_info *fi)
{
	int res;

	(void) fi;
	
	char fpath[PATH_MAX]; // Full buffer to pass to static function
	dj_fullpath(fpath, path);
	
	char *key = DJ_DATA->encfs_keyphrase;
	
	bool is_encrypted = IsEncrypted(fpath);
	if (is_encrypted) {
		
		// The solution i see for now involves creating a new buf and size
		// Write to the tmp file, Encrypt it, and then read the new file
		// Finally, pwrite to the original file using the new buffer and size
		char tpath[PATH_MAX];
		char tpath01[PATH_MAX];

		// Write unencrypted file
		tmpFileName(fpath, tpath);
		FILE* dec_file = fopen(tpath, "wb");
		fprintf(dec_file, "%s", buf);
		fflush(dec_file);

		// Write encrypted file
		tmpFileName(fpath, tpath01);
		FILE* enc_file = fopen(tpath01, "wb");
		EncryptFile(dec_file, enc_file, key);
		
		fclose(dec_file);
		fclose(enc_file);
		// Set new buf and 
		remove(tpath);
		
		int td = open(tpath01, O_RDONLY);
		
		off_t new_size;
		new_size = lseek(td, 0, SEEK_END);
		lseek(td, 0, SEEK_SET);	
			
		char* new_buf = malloc(new_size + 1);
		read(td, new_buf, new_size);
		
		close(td);
		remove(tpath01);
					
		int fd = open(fpath, O_WRONLY);
		if(fd == -1)
			return -errno;	
		// This is where its broken :'(
		// In order for unencryption to work, we need to maintain entire blocks
		// By encrypting the file, reading the encrypted file, the rewriting to the actual file, we lose some block data
		// and thus render decryption impossible.	
		res = pwrite(fd, new_buf, new_size, offset);
		if(res == -1)
			return -errno;
			
		close(fd);
		
		//~ char tpath[PATH_MAX];
		//~ tmpFileName(fpath, tpath);
		
		//~ int td = open(tpath, O_WRONLY);
		
		//~ res = pwrite(td, buf, size, offset);
		//~ close(td);
	
		//~ FILE* tmp = fopen(tpath, "w");
		//~ fprintf(tmp, "%s", buf);
		//~ fflush(tmp);
		//FILE* real = fopen(fpath, "w");
		
		//~ EncryptFile(tmp, real, key);
		//fclose(real);
		//fclose(tmp);
		
	} else {

		int fd = open(fpath, O_WRONLY);
	
		if (fd == -1)
			return -errno;

		res = pwrite(fd, buf, size, offset);
		if (res == -1)
			res = -errno;
	
		close(fd);
	}

	return res;
}
Exemple #11
0
int
main(int argc, char **argv)
{
    char *progName;
    FILE *inFile, *outFile;
    char *certName;
    CERTCertDBHandle *certHandle;
    struct recipient *recipients, *rcpt;
    PLOptState *optstate;
    PLOptStatus status;
    SECStatus rv;

    progName = strrchr(argv[0], '/');
    progName = progName ? progName+1 : argv[0];

    inFile = NULL;
    outFile = NULL;
    certName = NULL;
    recipients = NULL;
    rcpt = NULL;

    /*
     * Parse command line arguments
     * XXX This needs to be enhanced to allow selection of algorithms
     * and key sizes (or to look up algorithms and key sizes for each
     * recipient in the magic database).
     */
    optstate = PL_CreateOptState(argc, argv, "d:i:o:r:");
    while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
	switch (optstate->option) {
	  case '?':
	    Usage(progName);
	    break;

	  case 'd':
	    SECU_ConfigDirectory(optstate->value);
	    break;

	  case 'i':
	    inFile = fopen(optstate->value, "r");
	    if (!inFile) {
		fprintf(stderr, "%s: unable to open \"%s\" for reading\n",
			progName, optstate->value);
		return -1;
	    }
	    break;

	  case 'o':
	    outFile = fopen(optstate->value, "wb");
	    if (!outFile) {
		fprintf(stderr, "%s: unable to open \"%s\" for writing\n",
			progName, optstate->value);
		return -1;
	    }
	    break;

	  case 'r':
	    if (rcpt == NULL) {
		recipients = rcpt = PORT_Alloc (sizeof(struct recipient));
	    } else {
		rcpt->next = PORT_Alloc (sizeof(struct recipient));
		rcpt = rcpt->next;
	    }
	    if (rcpt == NULL) {
		fprintf(stderr, "%s: unable to allocate recipient struct\n",
			progName);
		return -1;
	    }
	    rcpt->nickname = strdup(optstate->value);
	    rcpt->cert = NULL;
	    rcpt->next = NULL;
	    break;
	}
    }

    if (!recipients) Usage(progName);

    if (!inFile) inFile = stdin;
    if (!outFile) outFile = stdout;

    /* Call the NSS initialization routines */
    PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
    rv = NSS_Init(SECU_ConfigDirectory(NULL));
    if (rv != SECSuccess) {
    	SECU_PrintPRandOSError(progName);
	return -1;
    }

    /* open cert database */
    certHandle = CERT_GetDefaultCertDB();
    if (certHandle == NULL) {
	return -1;
    }

    /* find certs */
    for (rcpt = recipients; rcpt != NULL; rcpt = rcpt->next) {
	rcpt->cert = CERT_FindCertByNickname(certHandle, rcpt->nickname);
	if (rcpt->cert == NULL) {
	    SECU_PrintError(progName,
			    "the cert for name \"%s\" not found in database",
			    rcpt->nickname);
	    return -1;
	}
    }

    if (EncryptFile(outFile, inFile, recipients, progName)) {
	SECU_PrintError(progName, "problem encrypting data");
	return -1;
    }

    return 0;
}
Exemple #12
0
int main(int argc, char *argv[])
#endif
{
#ifdef _CRTDBG_LEAK_CHECK_DF
	// Turn on leak-checking
	int tempflag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
	tempflag |= _CRTDBG_LEAK_CHECK_DF;
	_CrtSetDbgFlag( tempflag );
#endif

#if defined(__MWERKS__) && defined(macintosh)
	argc = ccommand(&argv);
#endif

	try
	{
		std::string command, executableName, edcFilename;

		if (argc < 2)
			command = 'h';
		else
			command = argv[1];

		if (FIPS_140_2_ComplianceEnabled())
		{
			edcFilename = "edc.dat";

#ifdef CRYPTOPP_WIN32_AVAILABLE
			TCHAR filename[MAX_PATH];
			GetModuleFileName(GetModuleHandle(NULL), filename, sizeof(filename));
			executableName = filename;
			std::string::size_type pos = executableName.rfind('\\');
			if (pos != std::string::npos)
				edcFilename = executableName.substr(0, pos+1) + edcFilename;
#else
			executableName = argv[0];
#endif

			if (command.substr(0, 4) != "fips")
			{
				byte expectedModuleDigest[SHA1::DIGESTSIZE];
				FileSource(edcFilename.c_str(), true, new HexDecoder(new ArraySink(expectedModuleDigest, sizeof(expectedModuleDigest))));

				DoPowerUpSelfTest(executableName.c_str(), expectedModuleDigest);
			}
		}

		switch (command[0])
		{
		case 'g':
		  {
			char seed[1024], privFilename[128], pubFilename[128];
			unsigned int keyLength;

			cout << "Key length in bits: ";
			cin >> keyLength;

			cout << "\nSave private key to file: ";
			cin >> privFilename;

			cout << "\nSave public key to file: ";
			cin >> pubFilename;

			cout << "\nRandom Seed: ";
			ws(cin);
			cin.getline(seed, 1024);

			GenerateRSAKey(keyLength, privFilename, pubFilename, seed);
			return 0;
		  }
		case 'r':
		  {
			switch (argv[1][1])
			{
			case 's':
				RSASignFile(argv[2], argv[3], argv[4]);
				return 0;
			case 'v':
			  {
				bool verified = RSAVerifyFile(argv[2], argv[3], argv[4]);
				cout << (verified ? "valid signature" : "invalid signature") << endl;
				return 0;
			  }
			default:
			  {
				char privFilename[128], pubFilename[128];
				char seed[1024], message[1024];

				cout << "Private key file: ";
				cin >> privFilename;

				cout << "\nPublic key file: ";
				cin >> pubFilename;

				cout << "\nRandom Seed: ";
				ws(cin);
				cin.getline(seed, 1024);

				cout << "\nMessage: ";
				cin.getline(message, 1024);

				string ciphertext = RSAEncryptString(pubFilename, seed, message);
				cout << "\nCiphertext: " << ciphertext << endl;

				string decrypted = RSADecryptString(privFilename, ciphertext.c_str());
				cout << "\nDecrypted: " << decrypted << endl;

				return 0;
			  }
			}
		  }
		case 'm':
			DigestFile(argv[2]);
			return 0;
		case 't':
		  {
			if (command == "tv")
			{
				return !RunTestDataFile(argv[2]);
			}
			// VC60 workaround: use char array instead of std::string to workaround MSVC's getline bug
			char passPhrase[MAX_PHRASE_LENGTH], plaintext[1024];

			cout << "Passphrase: ";
			cin.getline(passPhrase, MAX_PHRASE_LENGTH);

			cout << "\nPlaintext: ";
			cin.getline(plaintext, 1024);

			string ciphertext = EncryptString(plaintext, passPhrase);
			cout << "\nCiphertext: " << ciphertext << endl;

			string decrypted = DecryptString(ciphertext.c_str(), passPhrase);
			cout << "\nDecrypted: " << decrypted << endl;

			return 0;
		  }
		case 'e':
		case 'd':
			if (command == "e64")
				Base64Encode(argv[2], argv[3]);
			else if (command == "d64")
				Base64Decode(argv[2], argv[3]);
			else if (command == "e16")
				HexEncode(argv[2], argv[3]);
			else if (command == "d16")
				HexDecode(argv[2], argv[3]);
			else
			{
				char passPhrase[MAX_PHRASE_LENGTH];
				cout << "Passphrase: ";
				cin.getline(passPhrase, MAX_PHRASE_LENGTH);
				if (command == "e")
					EncryptFile(argv[2], argv[3], passPhrase);
				else
					DecryptFile(argv[2], argv[3], passPhrase);
			}
			return 0;
		case 's':
			if (argv[1][1] == 's')
			{
				char seed[1024];
				cout << "\nRandom Seed: ";
				ws(cin);
				cin.getline(seed, 1024);
				SecretShareFile(atoi(argv[2]), atoi(argv[3]), argv[4], seed);
			}
			else
				SecretRecoverFile(argc-3, argv[2], argv+3);
			return 0;
		case 'i':
			if (argv[1][1] == 'd')
				InformationDisperseFile(atoi(argv[2]), atoi(argv[3]), argv[4]);
			else
				InformationRecoverFile(argc-3, argv[2], argv+3);
			return 0;
		case 'v':
			return !Validate(argc>2 ? atoi(argv[2]) : 0, argv[1][1] == 'v', argc>3 ? argv[3] : NULL);
		case 'b':
			if (argc<3)
				BenchMarkAll();
			else
				BenchMarkAll((float)atof(argv[2]));
			return 0;
		case 'z':
			GzipFile(argv[3], argv[4], argv[2][0]-'0');
			return 0;
		case 'u':
			GunzipFile(argv[2], argv[3]);
			return 0;
		case 'f':
			if (command == "fips")
				FIPS140_SampleApplication(executableName.c_str(), edcFilename.c_str());
			else if (command == "fips-rand")
				FIPS140_GenerateRandomFiles();
			else if (command == "ft")
				ForwardTcpPort(argv[2], argv[3], argv[4]);
			return 0;
		case 'a':
			if (AdhocTest)
				return (*AdhocTest)(argc, argv);
			else
				return 0;
		default:
			FileSource usage("usage.dat", true, new FileSink(cout));
			return 1;
		}
	}
	catch(CryptoPP::Exception &e)
	{
		cout << "\nCryptoPP::Exception caught: " << e.what() << endl;
		return -1;
	}
	catch(std::exception &e)
	{
		cout << "\nstd::exception caught: " << e.what() << endl;
		return -2;
	}
}
Exemple #13
0
//暗号化
CIPHER_RESULT PmCipher::Encrypt(const char *source_path, const char *cipher_path, bool compress, bool recursive)
{
	//戻り値・・・ステータス
	//第1引数・・・暗号化するファイル/ディレクトリのパス
	//第2引数・・・暗号化ファイルのパス
	//第3引数・・・圧縮フラグ(true:圧縮, false:無圧縮)
	//第4引数・・・再帰処理フラグ(true:再帰処理あり(デフォルト), false:再帰処理なし)

	//ファイルストリーム
	fstream fs_cipher, fs_cipher_idx, fs_cipher_temp;
	//パス
	string str_find_path, str_source_path, str_idx_path, str_idx2_path, str_temp_path, str_cipher_path;
	//ファイルソート用
	unsigned int depth = 0, directory_num = 0;
	//ファイル検索続行フラグ
	BOOL next = TRUE;
	//戻り値
	CIPHER_RESULT cr = CIPHER_OK;
	//再帰処理用スタック
	stack<HANDLE> stack_handle;
	stack<BOOL> stack_next;
	stack<string> stack_directory;
	hash_map<string, unsigned int> map_directory_num;
	pair<string, unsigned int> pair_directory_num;
	//カレントディレクトリ
	string current_directory;
	//ファイル検索用変数
	WIN32_FIND_DATA FindFileData;
	HANDLE hFind;
	//ファイルの位置
	unsigned long offset = 0;

	//圧縮フラグ保存
	m_compress = compress;
	char key_word[] = CIPHER_KEY_WORD;
	char cipher_key_word[CIPHER_KEY_WORD_SIZE];

	m_blow_fish.Encode((unsigned char *)key_word, (unsigned char *)cipher_key_word, 8);

	//ファイルプロパティクラス変数
	PmCipherProperty *cipher_property = NULL;

	//元ファイルパス、中間ファイルパスの生成
	str_source_path = string(source_path);
	if(str_source_path.rfind("\\") == str_source_path.size() - 1)
	{
		str_source_path = str_source_path.substr(0, str_source_path.size() - 1);
	}
	str_cipher_path = string(cipher_path);
	str_idx_path = str_cipher_path + string(".idx");
	str_idx2_path = str_cipher_path + string(".idx2");
	str_temp_path = str_cipher_path + string(".tmp");

	if(!PathFileExists(str_cipher_path.substr(0, str_cipher_path.rfind("\\")).c_str()) || !PathIsDirectory(str_cipher_path.substr(0, str_cipher_path.rfind("\\")).c_str()))
	{
		return CIPHER_ERR_FILE_NOT_FOUND;
	}

	//最初のファイル検索
	hFind = FindFirstFile(str_source_path.c_str(), &FindFileData);
	current_directory = str_source_path;

	//暗号化ファイル(中間ファイル)のオープン
	fs_cipher_temp.open(str_temp_path.c_str(), ios::out|ios::binary);
	//検索が成功した場合
	if(hFind != INVALID_HANDLE_VALUE)
	{
		//引数で指定されたパスがファイルの場合
		if(!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
		{
			//サイズチェック
			if(FindFileData.nFileSizeHigh > 0 || Over2GB(FindFileData.nFileSizeLow))
			{
				cr = CIPHER_ERR_INVALID_FILE_SIZE;
			}
			else
			{
				//ファイルを暗号化
				if((cr = PmCipher::EncryptFile(str_source_path.c_str(), FindFileData.nFileSizeLow, compress, &fs_cipher_temp, &cipher_property)) == CIPHER_OK)
				{
					cipher_property->SetOffset(offset);
					m_property_list->AddProperty(cipher_property);
					offset += cipher_property->GetCipherSize();
					cipher_property = NULL;
					FindClose(hFind);
				}
			}
			next = FALSE;
		}
		//引数で指定されたパスがディレクトリの場合
		else
		{
			//ワイルドカードを付加して再検索
			str_find_path = str_source_path + string("\\*");
			hFind = FindFirstFile(str_find_path.c_str(), &FindFileData);
			pair_directory_num.first = current_directory;
			pair_directory_num.second = directory_num;
			map_directory_num.insert(pair_directory_num);
		}
	}
	//検索が失敗した場合エラー終了
	else
	{
		cr = CIPHER_ERR_FILE_NOT_FOUND;
		next = FALSE;
	}
	//再帰処理が終了しかつ、ファイル検索が終了するまでループ
	while(!stack_handle.empty() || next)
	{
		//ディレクトリのすべてのファイルを検索し終わったら検索処理終了
		if(!next)
		{
			FindClose(hFind);
			//再帰処理の途中の場合、上位フォルダを復帰
			if(!stack_handle.empty())
			{
				hFind = stack_handle.top();
				stack_handle.pop();
				next = stack_next.top();
				stack_next.pop();
				current_directory = stack_directory.top();
				stack_directory.pop();
				depth--;
				if(next)
				{
					next = FindNextFile(hFind, &FindFileData);
				}
			}
		}

		//検索したファイル属性がディレクトリの場合でかつ、再帰処理を行う場合
		if((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && recursive && next)
		{
			//下位ディレクトリの場合は再帰処理
			if(strcmp(FindFileData.cFileName, ".") && strcmp(FindFileData.cFileName, ".."))
			{
				stack_handle.push(hFind);
				stack_next.push(next);
				stack_directory.push(current_directory);
				current_directory = current_directory + string("\\") + string(FindFileData.cFileName);
				depth++;
				directory_num++;
				pair_directory_num.first = current_directory;
				pair_directory_num.second = directory_num;
				map_directory_num.insert(pair_directory_num);
				str_find_path = current_directory + string("\\*");
				hFind = FindFirstFile(str_find_path.c_str(), &FindFileData);
				if(hFind != INVALID_HANDLE_VALUE)
				{
					next = TRUE;
					continue;
				}
				else
				{
					next = FALSE;
					cr = CIPHER_ERR_INVALID_FILE;
				}
			}
		}
		//検索したファイル属性がファイルの場合は暗号化
		if(!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && next)
		{
			//サイズチェック
			if(FindFileData.nFileSizeHigh > 0 || Over2GB(FindFileData.nFileSizeLow + offset))
			{
				next = FALSE;
				cr = CIPHER_ERR_INVALID_FILE_SIZE;
			}
			else
			{
				str_find_path = current_directory + string("\\") + string(FindFileData.cFileName);
				if((cr = PmCipher::EncryptFile(str_find_path.c_str(), FindFileData.nFileSizeLow, compress, &fs_cipher_temp, &cipher_property)) == CIPHER_OK)
				{
					cipher_property->SetOffset(offset);
					offset += cipher_property->GetCipherSize();
					cipher_property->SetDepth(depth);
					hash_map<string, unsigned int>::iterator it;
					if((it = map_directory_num.find(current_directory)) != map_directory_num.end())
					{
						cipher_property->SetDirectoryNum(it->second);
					}
					else
					{
						cr = CIPHER_ERR_FATAL;
						next = FALSE;
					}
					m_property_list->AddProperty(cipher_property);
					cipher_property = NULL;
				}
			}
		}
		//エラーが起きたら直ちに終了
		if(cr != CIPHER_OK)
		{
			while(!stack_handle.empty())
			{
				hFind = stack_handle.top();
				FindClose(hFind);
				stack_handle.pop();
			}
			next = FALSE;
		}
		//次のファイルを検索
		if(next)
		{
			next = FindNextFile(hFind, &FindFileData);
		}
	}
	//暗号化ファイル(中間ファイル)のクローズ
	fs_cipher_temp.close();

	//暗号化が正常に終了した場合
	if(cr == CIPHER_OK)
	{
		//ファイル、バッファ等のサイズ
		unsigned long index_size = 0, cipher_index_size, compress_index_size, buf_size, total_buf_size;
		//バッファメモリの確保
		unsigned char *input_buf = new unsigned char[PmCipher::CIPHER_BUF_SIZE];
		unsigned char *output_buf = new unsigned char[PmCipher::CIPHER_BUF_SIZE];
		//文字列
		char str[CIPHER_MAX_INDEX_SIZE];

		//インデックスのソート
		m_property_list->SortProperty();
		//インデックス書き込み(平文中間ファイル)
		fs_cipher_idx.open(str_idx_path.c_str(), ios::out|ios::binary);
		//ルートディレクトリ書き込み
		sprintf_s(str, MAX_PATH + 1, "%s\n", str_source_path.c_str());
		index_size += str_source_path.length() + 1;
		fs_cipher_idx.write(str, str_source_path.length() + 1);
		for(unsigned int i = 0; i < m_property_list->GetPropertySize(); i++)
		{
			unsigned int str_size = 40 + m_property_list->GetProperty(i)->GetPath().length() + 1;
			sprintf_s(str, CIPHER_MAX_INDEX_SIZE, "%010lu%010lu%010lu%010lu%s\n", m_property_list->GetProperty(i)->GetOffset(), m_property_list->GetProperty(i)->GetSourceSize(), m_property_list->GetProperty(i)->GetCompressSize(), m_property_list->GetProperty(i)->GetCipherSize(), m_property_list->GetProperty(i)->GetPath().c_str());
			fs_cipher_idx.write(str, str_size);
			index_size += (unsigned long)str_size;
		}
		fs_cipher_idx.close();
		//インデックス書き込み(暗号化中間ファイル)
		fs_cipher_idx.open(str_idx2_path.c_str(), ios::out|ios::binary);
		if((cr = EncryptFile(str_idx_path.c_str(), index_size, compress, &fs_cipher_idx, &cipher_property)) == CIPHER_OK)
		{
			if(!Over2GB(cipher_property->GetCipherSize() + offset + CIPHER_HEADER_SIZE + CIPHER_KEY_WORD_SIZE))
			{
				compress_index_size = cipher_property->GetCompressSize();
				cipher_index_size = cipher_property->GetCipherSize();
				SAFE_DELETE(cipher_property);
				fs_cipher_idx.close();
				fs_cipher.open(str_cipher_path.c_str(), ios::out|ios::binary);
				//キーワード書き込み
				fs_cipher.write(cipher_key_word, CIPHER_KEY_WORD_SIZE);
				//ヘッダの書き込み
				sprintf_s(str, CIPHER_MAX_INDEX_SIZE, "%d%010lu%010lu%010lu%010lu", compress?1:0, index_size, compress_index_size, cipher_index_size, offset);
				fs_cipher.write(str, CIPHER_HEADER_SIZE);
				fs_cipher_idx.open(str_idx2_path.c_str(), ios::in|ios::binary);
				
				//ヘッダと暗号化したインデックス、データファイルの結合
				total_buf_size = 0;
				while(!fs_cipher_idx.eof())
				{
					buf_size = (total_buf_size + CIPHER_BUF_SIZE > cipher_index_size)?(cipher_index_size - total_buf_size):CIPHER_BUF_SIZE;
					fs_cipher_idx.read((char *)input_buf, buf_size);
					fs_cipher.write((char *)input_buf, buf_size);
					total_buf_size += buf_size;
					if(cipher_index_size <= total_buf_size)
					{
						break;
					}
				}
				fs_cipher_idx.close();
				fs_cipher_temp.open(str_temp_path.c_str(), ios::in|ios::binary);
				total_buf_size = 0;
				while(!fs_cipher_temp.eof())
				{
					buf_size = (total_buf_size + CIPHER_BUF_SIZE > offset)?(offset - total_buf_size):CIPHER_BUF_SIZE;
					fs_cipher_temp.read((char *)input_buf, buf_size);
					fs_cipher.write((char *)input_buf, buf_size);
					total_buf_size += buf_size;
					if(offset <= total_buf_size)
					{
						break;
					}
				}
				fs_cipher << std::flush;
			}
			else
			{
				cr = CIPHER_ERR_INVALID_FILE_SIZE;
			}
		}
		//ファイルのクローズ
		fs_cipher_temp.close();
		fs_cipher.close();
		m_cipher_index_size = cipher_index_size;
		//バッファメモリの解放
		SAFE_DELETE_ARRAY(input_buf);
		SAFE_DELETE_ARRAY(output_buf);
	}
	return cr;
}