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

📄 pgptestencode.c

📁 PGP8.0源码 请认真阅读您的文件包然后写出其具体功能
💻 C
📖 第 1 页 / 共 2 页
字号:
/*____________________________________________________________________________
	Copyright (C) 2002 PGP Corporation
	All rights reserved.
	
	A test program is also available in libs/pgpcdk/win32/test.  If you build 
	and run this, it puts up a command prompt.
	
	Mac project to run this is at: pgpcdk/mac/lib/test/Test.prj
	
	Suitable command lines include:

	-l
		Print out all the keys in the key ring (by userid).

	-e <userid> <infile> <outfile>

		Encrypt using the key for <userid> from <infile> to <outfile>.
		Can have multiple "-e <userid>" switches to encrypt to multiple
		recipients.

	-s <userid> -z <pphrase> <infile> <outfile>

		Sign using thekey for <userid> and the specified <pphrase> (which
		must not have any spaces).  If you leave off the -z <pphrase> it
		will prompt you for the passphrase when the callback event occurs.

	-e <userid> -s <userid> <infile> <outfile>

		Encrypt and sign.

	-d <infile> <outfile>

		Decrypt or verify the <infile>, output to <outfile>.  Can include
		"-z <pphrase>" to specify decryption passphrase (no spaces allowed)
		or else it will prompt you for one.

	-v <sigfile> <datafile>

		Verify detached signature from the <sigfile> against data in the
		<datafile>.

	-c <pphrase> <infile> <outfile>

		Conventionally encrypt <infile> to <outfile> using the specified
		<pphrase>, which must not have any spaces.


	Some optional switches, which should go before <infile>:

	-a
		Ascii armor output

	-t
		Treat input file as text

	-m
		Use memory-buffer versions of functions rather than file versions

	-b
		Output detached signature (signing only)

	-u
		Warn on untrusted keys
	
	-i	<force | auto [nonvolatileonly]>		Encode
	-i	[nonvolatileonly | nocrcok]				Decode
		extended file info; e.g. MacBinary for Mac. Suitable
		for reconstructing a file exactly the same as the original.


	$Id: pgpTestEncode.c,v 1.3 2002/08/06 20:11:17 dallen Exp $
____________________________________________________________________________*/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <ctype.h>


#if PGP_MACINTOSH
#include <stat.h>
#else
#include <sys/stat.h>
#endif

#if PGP_INTERNAL_TESTING
#include "pgpLeaks.h"
#endif

#include "pgpErrors.h"
#include "pgpEncode.h"
#include "pgpKeys.h"
#include "pgpUtilities.h"

#include "pgpTest.h"


#ifndef min
#define min(x,y) (((x)<(y))?(x):(y))
#endif
#ifndef max
#define max(x,y) (((x)>(y))?(x):(y))
#endif


#ifndef IsNull
#define IsntNull( p )	( (p) != NULL )
#define IsNull( p )		( (p) == NULL )
#endif



#include <string.h>

static const char *pgpoptarg;
static int pgpoptind;

static int
pgpgetopt (int argc, char const *argv[], char const *opts)
{
	int c;
	const char *s;

	(void)argc;
	
	if (!pgpoptind)
		pgpoptind = 1;

	if (!argv[pgpoptind] || argv[pgpoptind][0] != '-') {
		return -1;
	}
	c = argv[pgpoptind][1];
	if (!(s = strchr (opts, c))) {
		pgpoptind += 1;
		return '?';
	}
	if (s[1] == ':') {
		pgpoptarg = argv[++pgpoptind];
	} else
		pgpoptarg = 0;
	pgpoptind += 1;
	return c;
}

static PGPByte *
fileread (char const *filename, size_t *bufsize)
{
	PGPByte *buf;
	struct stat statbuf;
	FILE *f;

	if (stat (filename, &statbuf) < 0) {
		perror ("stat");
		exit (2);
	}
	*bufsize = statbuf.st_size;
	buf = (PGPByte *)malloc (statbuf.st_size);
	if (!(f = fopen (filename, "rb"))) {
		perror ("fopen");
		exit (2);
	}
	if (fread (buf, 1, statbuf.st_size, f) != (size_t)statbuf.st_size) {
		perror ("fread");
		exit (2);
	}
	fclose (f);
	return buf;
}

static void
filewrite (char const *filename, PGPByte *buf, size_t bufsize)
{
	FILE *f;

	if (!(f = fopen (filename, "wb"))) {
		perror ("fopen");
		exit (3);
	}
	if (fwrite (buf, 1, bufsize, f) != bufsize) {
		perror ("fwrite");
		exit (3);
	}
	fclose (f);
}


static void
usage (const char *pname)
{
	fprintf (stderr,
"Usage: %s [options] infile outfile\n"
" * Options:\n"
" * -d				Decrypt\n"
" * -s <username>	Sign it specified user name\n"
" * -b				Break off as separate signature\n"
" * -a				Ascii armor the output\n"
" * -t				Treat as text mode\n"
" * -c <passphrase>	Use pass phrase for encrypting/decrypting\n"
" * -u				Warn on untrusted keys\n"
" * -z <passphrase>	Key passphrase for signing/decrypting\n"
" * -e <username>	Encrypt to username (may have multiple -e switches)\n"
" * -m				Use memory buffer functions rather than file functions\n"
" * -v				Do verify, infile is sig, outfile is text (no output)\n"
" * -l				List keyring contents.  Filenames not used.\n"
" *\n"
" * Following are not implemented\n"
" * -y				AnalYze to see what the file is.  Output file not used.\n"
" * -k               Add keys from infile into outfile\n"
" * -x               Extract key (\"infile\" param) to outfile\n"
" \n", pname);
}

static void
userr (const char *pname)
{
	usage (pname);
	exit (1);
}



/********************* Callback Function Support ************************/

struct codename {
	PGPUInt32	code;
	const char	*name;
};

#define EV(x)	{ (PGPUInt32)kPGPEvent_##x##Event, #x " event" }

struct codename eventnames[] =
{
	EV(Null),
	EV(Initial),
	EV(Final),
	EV(Error),
	EV(Warning),
	EV(Entropy),
	EV(Passphrase),
	EV(InsertKey),
	EV(Analyze),
	EV(Recipients),
	EV(KeyFound),
	EV(Output),
	EV(Signature),
	EV(BeginLex),
	EV(EndLex),
	EV(Recursion),
	EV(DetachedSignature),
	EV(Encryption),
	EV(Decryption)
};

#undef EV

static char const *
eventName( PGPEventType evt )
{
	unsigned i;
	for (i=0; i<sizeof(eventnames)/sizeof(eventnames[0]); ++i) {
		if (eventnames[i].code == (PGPUInt32)evt) {
			return eventnames[i].name;
		}
	}
	return "Unknown event";
}

#define EV(x)	{ (PGPUInt32)kPGPAnalyze_##x, #x }

struct codename analyzenames[] =
{
	EV(Encrypted),
	EV(Signed),
	EV(DetachedSignature),
	EV(Key),
	EV(Unknown)
};

static char const *
analyzeName( PGPAnalyzeType anl )
{
	unsigned i;
	for (i=0; i<sizeof(analyzenames)/sizeof(analyzenames[0]); ++i) {
		if (analyzenames[i].code == (PGPUInt32)anl) {
			return analyzenames[i].name;
		}
	}
	return "Unknown analyze code";
}


static void
printKeys( PGPKeySetRef keyset, const char *prefix, FILE *fout )
{
	PGPKeyListRef	klist;
	PGPKeyIterRef	kiter;
	PGPKeyDBObjRef	key;

	PGPOrderKeySet( keyset, kPGPKeyOrdering_Any, FALSE, &klist );
	PGPNewKeyIter( klist, &kiter );
	while( IsntPGPError( PGPKeyIterNextKeyDBObj( kiter,
							kPGPKeyDBObjType_Key, &key ) ) ) {
		char name[256];
		PGPSize namelen = sizeof(name);
		PGPGetPrimaryUserIDName( key, name, sizeof( name ), &namelen );
		fprintf(fout, "%s%s\n", prefix, name);
	}
	PGPFreeKeyIter( kiter );
	PGPFreeKeyList( klist );
}

typedef struct MyState {
	PGPFileSpecRef	 fileRef;
	char const		*fileName;
	PGPByte			*dataBuf;
	PGPLocalEncodingFlags fLocalEncode;
	PGPSize			 dataBufSize;
	PGPUInt32		 sectionCount;
} MyState;


/* Generic event handler */
	static PGPError
myEvents(
	PGPContextRef context,
	PGPEvent *event,
	PGPUserValue userValue
	)
{
	static PGPByte buf[256];
	size_t len;
	MyState	*s;

	(void) context;

	s = (MyState *)userValue;
	printf ("%s: (callback code %d)\n", eventName(event->type), event->type);
	switch( event->type ) {
	case kPGPEvent_NullEvent:
		{	PGPEventNullData *d = &event->data.nullData;
			printf (" written %ld / %ld bytes\n", (long)d->bytesWritten,
					(long)d->bytesTotal);
		}
		break;
	case kPGPEvent_ErrorEvent:
		{
			PGPEventErrorData const *	d = &event->data.errorData;
			pgpTestAssertNoErr( d->error );
		}
		break;
	case kPGPEvent_WarningEvent:
		{	PGPEventWarningData *d = &event->data.warningData;
			printf (" warning code %d\n", d->warning);
		}
		break;
	case kPGPEvent_PassphraseEvent:
		{
			PGPEventPassphraseData *d = &event->data.passphraseData;
			if( d->fConventional ) {
				printf ("Enter conventional-decryption pass phrase: ");
			} else {
				PGPUInt32	numKeys;
				
				PGPCountKeys(d->keyset, &numKeys );
				if (numKeys == 0) {
					/* Can happen if don't have RSA support */
					printf (" NO KEYS CAN DECRYPT MESSAGE, SKIPPING\n");
					return kPGPError_NoErr;
				}
				printf (" decryption key%s:\n",
						numKeys >1?"s":"");
				printKeys( d->keyset, "  ", stdout );
				printf (" enter passphrase: ");
			}
			fgets( (char *)buf, sizeof(buf), stdin);
			len = strlen( (char *)buf) - 1;
			/* Test abort using zero length passphrase */
			if( len == 0 )
				return kPGPError_NoErr;
			PGPAddJobOptions( event->job, 
							PGPOPassphraseBuffer( context, buf, len),
							PGPOLastOption( context ) );
		}
		break;
	case kPGPEvent_SignatureEvent:
		{
			PGPEventSignatureData *d = &event->data.signatureData;
			time_t		stdTime;
			
			printf (" signature data:");
			if( IsNull( d->signingKey ) ) {
				printf (" (unknown signer)");
			} else {
				char	name[256];
				PGPSize	namelen = sizeof(name);
				PGPGetPrimaryUserIDName( d->signingKey,
					name, sizeof( name ), &namelen );
				printf (" by %s", name);
				if ( ! d->verified )
					printf( "\n!!!!!  WARNING: did not verify  !!!!!!!" );
				printf ("\n %schecked, %sverified, %skeyDisabled, "
						"%skeyRevoked, %skeyExpired, "
						"%skeyMeetsValidityThreshold, validity=%d",
						(d->checked?"":"!"),(d->verified?"":"!"),
						(d->keyDisabled?"":"!"), (d->keyRevoked?"":"!"),
						(d->keyExpired?"":"!"),
						(d->keyMeetsValidityThreshold?"":"!"),
						d->keyValidity);
			}
			
			stdTime	= PGPGetStdTimeFromPGPTime( d->creationTime );
			printf (", signed: %s", ctime( &stdTime ));
		}
		break;
	case kPGPEvent_RecipientsEvent:
		{
			PGPEventRecipientsData *d = &event->data.recipientsData;
			PGPUInt32	numKeys;
			
			if( d->keyCount > 0 ) {
				PGPUInt32 i;
				printf (" encrypted to %d key%s total:\n", d->keyCount,
											(d->keyCount>1?"s":" "));
				for (i=0; i<d->keyCount; ++i) {
					PGPKeyID	keyid = d->keyIDArray[i];
					char		keyidstr[ kPGPMaxKeyIDStringSize ];

					PGPGetKeyIDString( &keyid, kPGPKeyIDString_Abbreviated,
									   keyidstr );
					printf ("  %s\n", keyidstr );
				}
			}

			PGPCountKeys(d->recipientSet, &numKeys );
			if( numKeys > 0 ) {
				printf (" encrypted to keys which we have:\n");
				printKeys( d->recipientSet, "  ", stdout );
			}
			if( d->conventionalPassphraseCount > 0 ) {
				printf (" encrypted with %d conventional passphrase%s\n",
					 d->conventionalPassphraseCount,
					 (d->conventionalPassphraseCount > 1 ? "s" : ""));
			}
		}
		break;
	case kPGPEvent_AnalyzeEvent:
		{	PGPEventAnalyzeData *d = &event->data.analyzeData;
			static int skipper = 0;
			printf (" %s (analyze code %d)\n",
					analyzeName(d->sectionType), d->sectionType);
			if( skipper ) {
				printf (" (Returning SkipSection error)\n");
				return kPGPError_SkipSection;
			}
		}
		break;
	case kPGPEvent_DetachedSignatureEvent:
		if( IsntNull( s->dataBuf ) ) {
			printf(" (using memory buffer)\n");
			PGPAddJobOptions( event->job,
				  PGPODetachedSig( context,
				  		PGPOInputBuffer( context, s->dataBuf, s->dataBufSize ),
						PGPOLocalEncoding( context, s->fLocalEncode ),
						PGPOLastOption ( context ) ),
				  PGPOLastOption ( context ) );
		} else {
			printf( " (using file %s)\n", s->fileName );
			PGPAddJobOptions( event->job,
				  PGPODetachedSig( context,
					  PGPOInputFile( context, s->fileRef ),
					  PGPOLocalEncoding( context, s->fLocalEncode ),
					  PGPOLastOption ( context ) ),
				  PGPOLastOption ( context ) );
		}
		break;
	case kPGPEvent_OutputEvent:
		{	PGPEventOutputData *d = &event->data.outputData;
			printf (" type = %d, suggested name = %s, %sfyeo\n",
					d->messageType, d->suggestedName,
					d->forYourEyesOnly?"":"!");
#if 0
			if( IsntNull( s ) ) {
				char *outname;
				PGPFileSpecRef outref;

				outname = pgpMemAlloc( strlen(s->outFile)+5 );
				strcpy(outname, s->outFile);
				sprintf(outname+strlen(outname), "%d", s->count++);
				pgpNewFileRefFromFullPath( outname, &outref);
				PGPAddJobOptions( event->job,
								  PGPOOutputFile(outref),
								  PGPOLastOption( context ));
				printf(" setting output file as %s\n", outname);
				pgpFree( outname );
			}
#endif
		}
		break;
	case kPGPEvent_EncryptionEvent:
		{	PGPEventEncryptionData *d = &event->data.encryptionData;
			PGPUInt32 i;
			printf (" Cipher algorithm number: %d\n", d->cipherAlgorithm);
			printf (" Session key: 0x");
			for (i=0; i<d->sessionKeyLength; i++)
				printf ("%02x", d->sessionKey[i]);
			printf ("\n");
		}
		break;
	case kPGPEvent_DecryptionEvent:
		{	PGPEventDecryptionData *d = &event->data.decryptionData;
			PGPUInt32 i;
			printf (" Cipher algorithm number: %d\n", d->cipherAlgorithm);
			printf (" Session key: 0x");
			for (i=0; i<d->sessionKeyLength; i++)
				printf ("%02x", d->sessionKey[i]);
			printf ("\n");
		}
		break;
	case kPGPEvent_BeginLexEvent:
		{	PGPEventBeginLexData *d = &event->data.beginLexData;
			printf (" section number = %d\n", d->sectionNumber);
			s->sectionCount = d->sectionNumber;
		}
		break;
	case kPGPEvent_EndLexEvent:
		{	PGPEventEndLexData *d = &event->data.endLexData;
			printf (" section number = %d\n", d->sectionNumber);
		}
		break;
		
	default:
		break;
	}
				
	return kPGPError_NoErr;
}



#if PGP_MACINTOSH /* [ */

	static void
CToPString(
	const char	*cString,
	StringPtr	pString)
	{
	UInt32		length;
	UInt8		*curOut;
	
	pgpTestAssert( IsntNull( cString ) );
	pgpTestAssert( IsntNull( pString ) );
	
	length		= 0;
	curOut		= &pString[1];
	#define kMaxPascalStringLength	255
	while ( length < kMaxPascalStringLength )
		{
		if ( (curOut[length] = cString[length]) == 0)
			break;
		++length;
		}
	
	pString[0]	= length;
	}
	
	static OSStatus
GetSpecFromRefNum(
	short		refNum,
	FSSpec *	spec)
	{
	OSStatus	err	= noErr;
	FCBPBRec	pb;
	

⌨️ 快捷键说明

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