⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pgputil.cpp

📁 加密解密
💻 CPP
📖 第 1 页 / 共 3 页
字号:
#include "stdafx.h"
#include "pgputil.h"

#ifndef PGP_WIN32
#define PGP_WIN32 1 
#endif

#include <direct.h>
#include "pgpKeys.h"
#include "pgpErrors.h"
#include "pgpEncode.h"
#include "pgpFeatures.h"
#include "pgpOptionList.h"
#include "pgpSymmetricCipher.h"
#include "pgpCBC.h"
#include "pgpCFB.h"
#include "pgpUtilities.h"
#include "pgpKeyServer.h"
#include "pgpRandomPool.h"
#include "pgpDump.h"

/////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
typedef enum   
{
	kDecode_NoOption	= 0,
	kDecode_DumpTar,
	kDecode_UnpackTar,
	kDecode_MakeTarCache,
	kDecode_AllocOutput,
	kDecode_FileOutput,
	kDecode_Ignore_Output,
	PGP_ENUM_FORCE( EventHandlerOptions )
 } EventHandlerOptions;
 
 
typedef struct 
{
	EventHandlerOptions option;
	PGPByte				*sessionKey;
	PGPSize				sessionKeySize;
	PGPFileSpecRef		outFile;
	PGPByte				*outBuf;
	PGPSize				outBufSize;
	PGPByte				*outDir;	
	int					keyCount;
	PGPKeyIterRef		keyIter;
	struct {
		PGPKeyID		keyID;
		const   char    *passPhrase;
	} key[8];	
 } DecodeInfo;

/////////////////////////////////////////////////////////////////////
static 	char  *cipherModeTxt[] = {"ECB","CBC","CFB"};
typedef enum  {kCipherModeECB, kCipherModeCBC, kCipherModeCFB} CipherMode;

//////////////////////////////////////////////////////////////////////////
//
static  PGPContextRef    m_gContext = kInvalidPGPContextRef ;  // g
static	DecodeInfo		 m_gDecodeInfo  ;   //
static 	PGPKeyDBRef		 m_gKeyDB	 	= kInvalidPGPKeyDBRef; //
static  std::string      m_gPwd   ;
//static  PGPFilterRef     m_gFilter = kInvalidPGPFilterRef ; 
static  PGPUInt32		 m_gnumKeys = 0 ;
static  PGPKeySetRef     m_guserKeySet = kInvalidPGPKeySetRef ;
static  PGPKeyDBObjRef   m_gSignKey 	= kInvalidPGPKeyDBObjRef;
//////////////////////////////////////////////////////////////////////////



static PGPChar*  cipher_mode_text(CipherMode  mode)
{
	return cipherModeTxt[mode] ;
}

// 获取Hash算法名称
static PGPChar*  hash_algor_table(int algor)
{
 	switch (algor )
	{
		case kPGPHashAlgorithm_MD5: 		return (PGPTXT_USER("MD5"));
		case kPGPHashAlgorithm_SHA: 		return (PGPTXT_USER("SHA-1"));
		case kPGPHashAlgorithm_RIPEMD160: 	return (PGPTXT_USER("RIPE-MD-160"));
		case kPGPHashAlgorithm_SHA256:		return (PGPTXT_USER("SHA-128"));
		case kPGPHashAlgorithm_SHA384:		return (PGPTXT_USER("SHA-384"));
		case kPGPHashAlgorithm_SHA512:		return (PGPTXT_USER("SHA-512"));						
		default:							return (PGPTXT_USER("Invalid"));
	}
}

//获取cipher算法名称
static PGPChar*  cipher_algor_table(int algor)
{
 	switch (algor )
	{
		case kPGPCipherAlgorithm_IDEA: 		return (PGPTXT_USER("IDEA"));
		case kPGPCipherAlgorithm_3DES: 		return (PGPTXT_USER("3-DES"));
		case kPGPCipherAlgorithm_CAST5: 	return (PGPTXT_USER("CAST-5"));
		case kPGPCipherAlgorithm_AES128: 	return (PGPTXT_USER("AES-128"));
		case kPGPCipherAlgorithm_AES192: 	return (PGPTXT_USER("AES-192"));
		case kPGPCipherAlgorithm_AES256: 	return (PGPTXT_USER("AES-256"));	
		case kPGPCipherAlgorithm_Blowfish:  return (PGPTXT_USER("BlowFish"));
		case kPGPCipherAlgorithm_Twofish256: return (PGPTXT_USER("TwoFish"));
		default:	 return (PGPTXT_USER("Invalid"));
	}
}

//获取钥匙类型名称
static PGPChar*  key_algor_table(int keytype)
{
	switch(keytype)
	{
		case kPGPPublicKeyAlgorithm_RSA:			return (PGPTXT_USER("RSA"));
		case kPGPPublicKeyAlgorithm_RSAEncryptOnly:	return (PGPTXT_USER("RSA Encrypt Only"));
		case kPGPPublicKeyAlgorithm_RSASignOnly:	return (PGPTXT_USER("RSA Sign Only"));
		case kPGPPublicKeyAlgorithm_ElGamal:		return (PGPTXT_USER("Elgamal"));
		case kPGPPublicKeyAlgorithm_DSA:			return (PGPTXT_USER("DSA"));
 		case kPGPPublicKeyAlgorithm_ECEncrypt:		return (PGPTXT_USER("EC-Enc"));
		case kPGPPublicKeyAlgorithm_ECSign:			return (PGPTXT_USER("EC-Sign"));
		default:									return (PGPTXT_USER("Invalid"));
	}
}


//获取Compression算法名称
static PGPChar*  compression_algor_table(int algor)
{
	switch(algor)
	{
		case kPGPCompressionAlgorithm_None:			return (PGPTXT_USER("None"));
		case kPGPCompressionAlgorithm_ZLIB:			return (PGPTXT_USER("ZLIB"));
		case kPGPCompressionAlgorithm_ZIP:			return (PGPTXT_USER("Zip"));
		case kPGPCompressionAlgorithm_BZIP2:		return (PGPTXT_USER("BZip2"));
 		default:									return (PGPTXT_USER("Invalid"));
	}
}

//
static PGPChar*  email_encoding_table(int encoding)
{
	switch(encoding)
	{
 		case kPGPPreferredEmailEncoding_PGPMIME:			return (PGPTXT_USER("PGPMIME"));
		case kPGPPreferredEmailEncoding_Partitioned:		return (PGPTXT_USER("Legacy"));
  		default:											return (PGPTXT_USER("Invalid"));
	}
}

static char*  extname (const char *name)
{
	const char *ext;
	if(!name) return 0;
	
	for (ext = name + strlen(name) ; ext != name && ( *ext != '.' &&  *ext != '/') ; ext--)
		;
	if(ext == name ) return 0;
	else return (char*)(ext+1);
}

//初始化信息
void InitDecodeInfo( DecodeInfo* info)
{
	info->outBuf = NULL;
	info->outBufSize = 0;
	info->sessionKey = NULL;
	info->sessionKeySize = 0;
	info->outFile = NULL;
	info->keyCount = 0;
	info->keyIter = kInvalidPGPKeyIterRef;
}

//清除信息
void CleanUpDecodeInfo( DecodeInfo* info)
{
	if(info->outBuf) 
	{
		PGPFreeData(info->outBuf);
		info->outBuf = NULL;
		info->outBufSize = 0;
	}
	
	if(info->sessionKey) 
	{
		PGPFreeData(info->sessionKey);
		info->sessionKey = NULL;
		info->sessionKeySize = 0;
	}

	if( PGPFileSpecRefIsValid(info->outFile))
	{
		PGPFreeFileSpec(info->outFile);
		info->outFile = NULL;
	}
}


//事件响应函数
static PGPError  OptestEventHandler(PGPContextRef context, PGPEvent *event, PGPUserValue userValue) 
{
	PGPError		err = kPGPError_NoErr;
	DecodeInfo*		info = (DecodeInfo*)userValue;

	static PGPBoolean   bKeyGen = false , bNull = false;
	static int			nlastProgress = 0;
 
  	static PGPEventRecipientsData	*recipdata = NULL;
 	
	if( event->type != kPGPEvent_KeyGenEvent)
		bKeyGen = FALSE;

	if( event->type != kPGPEvent_NullEvent)
		bNull = FALSE;

	switch(event->type)
	{
	case kPGPEvent_NullEvent    ://			=  0,		/* ----- Null Event-----Nothing happened */
		{
			PGPEventNullData  *d = &event->data.nullData;
			int nprogress =  (int)(( (float) d->bytesWritten /  d->bytesTotal) * 100);
			
			if(!bNull)
				bNull = TRUE;
			nlastProgress = nprogress;
		}
		break ;
	case kPGPEvent_InitialEvent	://	=  1,		/* ----- Initial Event----- */
		{
			bKeyGen = FALSE;
			bNull = FALSE;
			nlastProgress = 0;
			info->keyIter = kInvalidPGPKeyIterRef;
		}
		break ;
	case kPGPEvent_FinalEvent	://	=  2,		/* ----- Final Event----- */
//释放内存资源
		{
			nlastProgress = 0;
 			if( recipdata != NULL) 
			{ 
				PGPFreeData(recipdata); 
				recipdata = NULL; 
			}
			
			if( PGPKeyIterRefIsValid( info->keyIter ) ) 
			{	
				PGPFreeKeyIter( info->keyIter );
				info->keyIter = kInvalidPGPKeyIterRef;
			};
 
			if(info->outBuf == NULL) 
				break ;

			if(info->option == kDecode_DumpTar)
			{
 				//dumpTAR(info->outBuf, (int)(info->outBufSize), FALSE);
				PGPFreeData(info->outBuf);
				info->outBuf = NULL;
				info->outBufSize = 0;
			}
 			else  if(info->option == kDecode_Ignore_Output)
			{

			}
			else
			{			
				//if(strlen((char*)info->outBuf) < info->outBufSize)
				//{
				//	if(info->outBufSize < 128)
				//		dumpHex(info->outBuf, (int)(info->outBufSize), 0);
				//	else
				//	{
				//		dumpHex(info->outBuf, 128, 0);
				//		STATUS_LOG("      .....\n");
				//		dumpHex(info->outBuf + (int)(info->outBufSize) - 128, 128, (int)(info->outBufSize) - 128);
				//	}					
				//}
			}
		}
		break ;
	case kPGPEvent_ErrorEvent	://	=  3,		/* ----- Error Event----- An error occurred */
		{
			PGPEventErrorData *d = &event->data.errorData;
		}
		break ;
	case kPGPEvent_WarningEvent	://	=  4,		/*----- Warning Event----- Warning event */
//
		{
 			PGPEventWarningData *d = &event->data.warningData;		
/*			if(d->warning == kPGPError_KeyInvalid && d->warningArg)
			{
				PGPKeySetRef keyset = d->warningArg;
				PGPUInt32 numKeys;	
				err = PGPCountKeys(keyset, &numKeys);
				if(numKeys)
				{
					PGPKeyIterRef   iter	= kInvalidPGPKeyIterRef;
					PGPKeyDBObjRef  aKey	= kInvalidPGPKeyDBObjRef;
					
					err = PGPNewKeyIterFromKeySet(keyset, &iter);
					while( IsntPGPError( PGPKeyIterNextKeyDBObj( iter, kPGPKeyDBObjType_Key, &aKey) ) )
					{
						PGPKeyID  keyID;
						PGPChar8 outString[ kPGPMaxKeyIDStringSize ];
						
						PGPGetKeyID( aKey, &keyID );
						PGPGetKeyIDString( &keyID, kPGPKeyIDString_Full, outString);
					}			
					if( PGPKeyIterRefIsValid( iter ) ) 
						PGPFreeKeyIter( iter );
				}
 			}	*/		
		}
		break ;
	case kPGPEvent_EntropyEvent	://	=  5,		/* More entropy is needed */

		break ;
	case kPGPEvent_PassphraseEvent ://	=  6,		/* ----- Passphrase Event-----A passphrase is needed */
		{
			PGPEventPassphraseData  *d = &event->data.passphraseData;
			if(d->keyset)
			{
				PGPUInt32 numKeys;		
				err = PGPCountKeys(d->keyset, &numKeys);
				if(numKeys)
				{
 					PGPKeyDBObjRef  aKey = kInvalidPGPKeyDBObjRef;
					
					if( !PGPKeyIterRefIsValid( info->keyIter ) ) 
						err = PGPNewKeyIterFromKeySet(d->keyset, &info->keyIter);
					
 					while( IsntPGPError( PGPKeyIterNextKeyDBObj( info->keyIter, kPGPKeyDBObjType_Key, &aKey) ) )
					{
						PGPKeyID  keyID;
 						PGPChar8 outString[ kPGPMaxKeyIDStringSize ];
						int i;
 						
						PGPGetKeyID( aKey, &keyID );
 						PGPGetKeyIDString( &keyID, kPGPKeyIDString_Full, outString);
						
						for(i = 0;i < info->keyCount; i++)
 							if( PGPCompareKeyIDs( &info->key[i].keyID, &keyID) == 0 )
							{
									err = PGPAddJobOptions( event->job,
												PGPOPassphraseBuffer( context, info->key[i].passPhrase, 
																	  strlen( info->key[i].passPhrase ) ),
												PGPOLastOption( context ) );
 								goto got_paassphrase;
							}
   					}
					
		got_paassphrase:	
					break ;
 				}
 			}
		}
		break ;
	case kPGPEvent_InsertKeyEvent ://	=  7,		/* Smart card must be inserted */

		break ;
	case kPGPEvent_AnalyzeEvent	://	=  8,		/* ----- Analyze Event-----Initial analysis event,  before any output */
		{
			PGPEventAnalyzeData *d = &event->data.analyzeData;

	  	}			
		break ;
	case kPGPEvent_RecipientsEvent ://	=  9,		/*-----  Recipients Event----- Recipient list report,  before any output */
		{
			PGPEventRecipientsData  *d = &event->data.recipientsData;
			if(recipdata != NULL)
				PGPFreeData(recipdata);
			recipdata = (PGPEventRecipientsData*) PGPNewData( PGPGetDefaultMemoryMgr(), sizeof(PGPEventRecipientsData) ,  0 );
			if(recipdata != NULL)
			{
				recipdata->recipientSet = d->recipientSet;
				recipdata->keyCount 	= d->keyCount;
				recipdata->keyIDArray 	= d->keyIDArray;				
				PGPIncKeySetRefCount(d->recipientSet);
			}			
		}
		break ;
	case kPGPEvent_KeyFoundEvent ://		= 10,		/* Key packet found */

		break ;
	case kPGPEvent_OutputEvent	://	= 11,		/* ----- Output Event-----Output specification needed */
		{
			PGPEventOutputData *d = &event->data.outputData;
			PGPBoolean  bHandled   = FALSE;
			
			if(d->suggestedName != NULL)
			{
 				char		*ext	= extname(d->suggestedName);
				char		baseName[MAX_PATH];
				char		pathName[MAX_PATH];
				
				PGPBoolean  bTAR		= FALSE;
				
				baseName[0] = 0;
				
 				if ((d->messageType == 'b') && (ext && (strcmp("tar", ext) == 0))) 
					bTAR = TRUE;
				if(ext != NULL )
				{
					strncat(baseName, d->suggestedName, ext - d->suggestedName );
					baseName[ ext - d->suggestedName-1] = 0;
				}
				else 
					strcat(baseName, d->suggestedName);					
		 
				switch( info->option)
				{
					case kDecode_MakeTarCache:
					if(bTAR)
					{
						if( PGPFileSpecRefIsValid(info->outFile))
						{
							PGPFreeFileSpec(info->outFile);
							info->outFile = NULL;
						}
						err = PGPNewFileSpecFromFullPath( context, pathName, &info->outFile );
						err = PGPAddJobOptions( event->job,
												PGPOOutputTARCache(context, info->outFile ),
												PGPOLastOption(context));
						bHandled = TRUE;
					}
					break;
	 
					case kDecode_UnpackTar:
					if(bTAR)  /* make a directory to drop the TAR */
 					{
						if( (_mkdir(pathName) != 0) && (errno != EEXIST))
								err = kPGPError_FileOpFailed;  
						else
						{						
							if( PGPFileSpecRefIsValid(info->outFile))
							{
								PGPFreeFileSpec(info->outFile);
								info->outFile = NULL;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -