static void updateConfigCert( void ) { CRYPT_CERTIFICATE trustedCert; int status; /* Import the first certificate, make it trusted, and commit the changes */ importCertFromTemplate( &trustedCert, CERT_FILE_TEMPLATE, 1 ); cryptSetAttribute( trustedCert, CRYPT_CERTINFO_TRUSTED_IMPLICIT, TRUE ); cryptSetAttribute( CRYPT_UNUSED, CRYPT_OPTION_CONFIGCHANGED, FALSE ); cryptDestroyCert( trustedCert ); cryptEnd(); /* Do the same with a second certificate. At the conclusion of this, we should have two trusted certificates on disk */ status = cryptInit(); if( cryptStatusError( status ) ) { puts( "Couldn't reload cryptlib configuration." ); return; } importCertFromTemplate( &trustedCert, CERT_FILE_TEMPLATE, 2 ); cryptSetAttribute( trustedCert, CRYPT_CERTINFO_TRUSTED_IMPLICIT, TRUE ); cryptSetAttribute( CRYPT_UNUSED, CRYPT_OPTION_CONFIGCHANGED, FALSE ); cryptDestroyCert( trustedCert ); cryptEnd(); }
static void testKludge( const char *argPtr ) { #if 0 testReadCorruptedKey(); #endif /* 0 */ /* To test dodgy certificate collections */ #if 0 int result; if( argPtr == NULL ) { printf( "Error: Missing argument.\n" ); exit( EXIT_FAILURE ); } if( *argPtr == '@' ) { cryptSetAttribute( CRYPT_UNUSED, CRYPT_OPTION_CERT_COMPLIANCELEVEL, CRYPT_COMPLIANCELEVEL_OBLIVIOUS ); argPtr++; } if( *argPtr == '#' ) { cryptSetAttribute( CRYPT_UNUSED, CRYPT_OPTION_CERT_COMPLIANCELEVEL, CRYPT_COMPLIANCELEVEL_PKIX_FULL ); argPtr++; } result = xxxCertImport( argPtr ); cryptEnd(); exit( result ? EXIT_SUCCESS : EXIT_FAILURE ); #endif /* 1 */ /* Performance-testing test harness */ #if 0 void performanceTests( const CRYPT_DEVICE cryptDevice ); performanceTests( CRYPT_UNUSED ); #endif /* 0 */ /* Memory diagnostic test harness */ #if 0 testReadFileCertPrivkey(); testEnvelopePKCCrypt(); /* Use "Datasize, certificate" */ testEnvelopeSign(); /* Use "Datasize, certificate" */ #endif /* 0 */ /* Simple (brute-force) server code. NB: Remember to change setLocalConnect() to not bind the server to localhost if expecting external connections */ #if 0 while( TRUE ) testSessionTSPServer(); #endif /* 0 */ /* Exit point for the test harnesses above, used when we don't want to fall through to the main test code */ #if 0 cleanupAndExit( EXIT_SUCCESS ); #endif /* 0 */ }
static int gen_sha2( uchar * inbufp, int bsize, uchar * outbufp) { CRYPT_CONTEXT hashContext; uchar hash[40]; int ansr; memset(hash, 0, 40); if (cryptInit() != CRYPT_OK) { FATAL(MSG_ERROR, "initializing cryptlib"); } if (cryptCreateContext(&hashContext, CRYPT_UNUSED, CRYPT_ALGO_SHA2) != CRYPT_OK) { FATAL(MSG_ERROR, "creating cryptlib hash context"); } cryptEncrypt(hashContext, inbufp, bsize); cryptEncrypt(hashContext, inbufp, 0); cryptGetAttributeString(hashContext, CRYPT_CTXINFO_HASHVALUE, hash, &ansr); cryptDestroyContext(hashContext); cryptEnd(); memcpy(outbufp, hash, ansr); return ansr; }
static void testContinuousThreads( void ) { unsigned threadID1, threadID2; #ifdef UNIX_THREADS pthread_t thread1, thread2; #else HANDLE hThread1, hThread2; #endif /* Different threading models */ cryptAddRandom( "xyzzy", 5 ); #ifdef UNIX_THREADS pthread_create( &thread1, NULL, envelopeDataThread, ( void * ) 1 ); pthread_create( &thread2, NULL, envelopeDataThread, ( void * ) 2 ); #else hThread1 = ( HANDLE ) _beginthreadex( NULL, 0, envelopeDataThread, ( void * ) 1, 0, &threadID1 ); hThread2 = ( HANDLE ) _beginthreadex( NULL, 0, envelopeDataThread, ( void * ) 2, 0, &threadID2 ); #endif /* Different threading models */ delayThread( 30 ); printf( "Hit a key..." ); fflush( stdout ); getchar(); cryptEnd(); exit( EXIT_SUCCESS ); }
void testKludge( const char *argPtr ) { #if 0 // testGetBorkenKey(); // testKeyset(); /* For client-server tests */ // testWriteCert(); /* For client-server tests */ testSessionSuiteBClientServer(); #endif #if 0 // testSessionTLS12(); // testKeyset(); /* For client-server tests */ // testWriteCert(); /* For client-server tests */ // testSessionSSLClientCertClientServer(); // testSessionTLS12ClientServerEccKey(); // testSessionTLS12ClientServerEcc384Key(); // testKeyset(); /* For client-server tests */ // testWriteCert(); /* For client-server tests */ // testSessionTLS12ClientCertClientServer(); #endif #if 0 testReadCorruptedKey(); #endif /* 0 */ /* Performance-testing test harness */ #if 0 void performanceTests( const CRYPT_DEVICE cryptDevice ); performanceTests( CRYPT_UNUSED ); #endif /* 0 */ /* Memory diagnostic test harness */ #if 0 testReadFileCertPrivkey(); testEnvelopePKCCrypt(); /* Use "Datasize, certificate" */ testEnvelopeSign(); /* Use "Datasize, certificate" */ #endif /* 0 */ /* Simple (brute-force) server code. NB: Remember to change setLocalConnect() to not bind the server to localhost if expecting external connections */ #if 0 while( TRUE ) testSessionTSPServer(); #endif /* 0 */ /* Shared exit point for the test harnesses above, used when we don't want to fall through to the main test code */ #if 0 cryptEnd(); puts( "\nPress a key to exit." ); getchar(); exit( EXIT_SUCCESS ); #endif /* 0 */ }
int main( int argc, char **argv) { CRYPT_CONTEXT privKeyContext; CRYPT_KEYSET cryptKeyset; int ksize; if (argc < 3) { fprintf(stderr, "Usage: %s filename keysize\n", argv[0]); return 1; } if (sscanf(argv[2], "%d", &ksize) != 1) { fprintf(stderr, "Invalid key size\n"); return 1; } if (ksize != STANDARD_KEY_SIZE) { fprintf(stderr, "Warning: key size %d is not the standard size (%d)\n", ksize, STANDARD_KEY_SIZE); } printf("Making %s with key size %d bits \n", argv[1], ksize); if (cryptInit() != CRYPT_OK) { fprintf(stderr, "Can't open Cryptlib\n"); return 1; } if (cryptCreateContext(&privKeyContext, CRYPT_UNUSED, CRYPT_ALGO_RSA) != CRYPT_OK) { fprintf(stderr, "Can't create cryptlib private key context\n"); return 1; } cryptSetAttributeString(privKeyContext, CRYPT_CTXINFO_LABEL, "label", 5); cryptSetAttribute(privKeyContext, CRYPT_CTXINFO_KEYSIZE, ksize / 8); if (cryptGenerateKey(privKeyContext) != CRYPT_OK) { fprintf(stderr, "Can't generate key\n"); return 1; } if (cryptKeysetOpen(&cryptKeyset, CRYPT_UNUSED, CRYPT_KEYSET_FILE, argv[1], CRYPT_KEYOPT_CREATE) != CRYPT_OK) { fprintf(stderr, "Can't open keyset\n"); return 1; } if (cryptAddPrivateKey(cryptKeyset, privKeyContext, "password") != CRYPT_OK) { fprintf(stderr, "Can't add key to keyset\n"); return 1; } cryptKeysetClose(cryptKeyset); cryptDestroyContext(privKeyContext); cryptEnd(); return 0; }
static void cleanupAndExit( const int exitStatus ) { int status; status = cryptEnd(); if( status == CRYPT_ERROR_INCOMPLETE ) puts( "cryptEnd() failed with CRYPT_ERROR_INCOMPLETE." ); cleanExit( exitStatus ); }
int scEnd() { #if defined(HAVE_LIBCRYPT) #if 0 if( cryptEnd() ) return( SC_EXIT_LIB_ERROR); #endif #endif /* HAVE_LIBCRYPT */ return( SC_EXIT_OK ); }
int main(int argc, char **argv) { const char *cmd; struct cmd_func_pair { const char *cmd; cmd_exec_func_t func; } *pair_ptr, exec_funcs[] = { { "help", exec_help }, { "create", exec_create }, { "enroll", exec_enroll }, { "request", exec_request }, { "sign", exec_sign }, { "revoke", exec_revoke }, { "gencrl", exec_gencrl }, { "cmpsvr", exec_cmpsvr }, { "cmpcli", exec_cmpcli }, { "info", exec_info }, { "addpubkey", exec_addpubkey }, { NULL, NULL } }; int retval, status; int argv_cmd_index; if (argc < 2) { fprintf(stderr, "usage: %s [opts] command [params]\n", argv[0]); fprintf(stderr, "%s help gives more help\n", argv[0]); exit(1); } status = cryptInit(); if (!cryptStatusOK(status)) { fprintf(stderr, "cryptlib error %d while initializing cryptlib\n", status); } argv_cmd_index = 1; while (argv[argv_cmd_index][0] == '-') { process_opt(argv[argv_cmd_index]); argv_cmd_index++; } cmd = argv[argv_cmd_index]; for (pair_ptr = exec_funcs; pair_ptr->cmd; pair_ptr++) { if (strcmp(cmd, pair_ptr->cmd) == 0) { retval = pair_ptr->func(argc - argv_cmd_index - 1, argv + argv_cmd_index + 1); break; } } if (pair_ptr->cmd == 0) { fprintf(stderr, "unknown command %s\n", cmd); fprintf(stderr, "%s help gives more help\n", argv[0]); retval = 1; } status = cryptEnd(); if (!cryptStatusOK(status)) { fprintf(stderr, "cryptlib error %d while deinitializing cryptlib\n", status); } return retval; }
/* * int fatal(char *msg) { if (msg && *msg) fprintf(stderr, "%s\n", msg); * exit(0); } */ int main( int argc, char **argv) { CRYPT_CONTEXT privKeyContext; CRYPT_KEYSET cryptKeyset; if (argc < 2) { fprintf(stderr, "Usage: Filename\n"); return 1; } printf("Making %s\n", argv[1]); #define CRYPT_CALL(f) \ do \ { \ if ((f) != CRYPT_OK) \ { \ fprintf(stderr, "Error calling %s\n", #f); \ exit(EXIT_FAILURE); \ } \ } while (false) CRYPT_CALL(cryptInit()); CRYPT_CALL(cryptCreateContext(&privKeyContext, CRYPT_UNUSED, CRYPT_ALGO_RSA)); CRYPT_CALL(cryptSetAttributeString(privKeyContext, CRYPT_CTXINFO_LABEL, "label", 5)); CRYPT_CALL(cryptSetAttribute(privKeyContext, CRYPT_CTXINFO_KEYSIZE, 1024 / 8)); CRYPT_CALL(cryptGenerateKey(privKeyContext)); CRYPT_CALL(cryptKeysetOpen(&cryptKeyset, CRYPT_UNUSED, CRYPT_KEYSET_FILE, argv[1], CRYPT_KEYOPT_CREATE)); CRYPT_CALL(cryptAddPrivateKey(cryptKeyset, privKeyContext, "password")); CRYPT_CALL(cryptKeysetClose(cryptKeyset)); CRYPT_CALL(cryptDestroyContext(privKeyContext)); CRYPT_CALL(cryptEnd()); #undef CRYPT_CALL return 0; }
int main( int argc, char **argv ) { const char *zargPtr = NULL; BOOLEAN sessionTestError = FALSE, loopbackTestError = FALSE; int flags, status; void testSystemSpecific1( void ); void testSystemSpecific2( void ); /* If we're running in test mode, run the test code and exit */ #ifdef CONFIG_SUITEB_TESTS return( suiteBMain( argc, argv ) ); #endif /* CONFIG_SUITEB_TESTS */ /* Print a general banner to let the user know what's going on */ printf( "testlib - cryptlib %d-bit self-test framework.\n", ( int ) sizeof( long ) * 8 ); /* Cast for gcc */ puts( "Copyright Peter Gutmann 1995 - 2012." ); puts( "" ); /* Skip the program name and process any command-line arguments */ argv++; argc--; status = processArgs( argc, argv, &flags, &zargPtr ); if( !status ) exit( EXIT_FAILURE ); #ifdef USE_TCHECK THREAD_DEBUG_SUSPEND(); #endif /* USE_TCHECK */ /* Make sure that various system-specific features are set right */ testSystemSpecific1(); /* VisualAge C++ doesn't set the TZ correctly. The check for this isn't as simple as it would seem since most IBM compilers define the same preprocessor values even though it's not documented anywhere, so we have to enable the tzset() call for (effectively) all IBM compilers and then disable it for ones other than VisualAge C++ */ #if ( defined( __IBMC__ ) || defined( __IBMCPP__ ) ) && !defined( __VMCMS__ ) tzset(); #endif /* VisualAge C++ */ /* Initialise cryptlib */ printf( "Initialising cryptlib..." ); status = cryptInit(); if( cryptStatusError( status ) ) { printf( "\ncryptInit() failed with error code %d, line %d.\n", status, __LINE__ ); exit( EXIT_FAILURE ); } puts( "done." ); #ifndef TEST_RANDOM /* In order to avoid having to do a randomness poll for every test run, we bypass the randomness-handling by adding some junk. This is only enabled when cryptlib is built in debug mode so it won't work with any production systems */ #if defined( __MVS__ ) || defined( __VMCMS__ ) #pragma convlit( resume ) cryptAddRandom( "xyzzy", 5 ); #pragma convlit( suspend ) #else cryptAddRandom( "xyzzy", 5 ); #endif /* Special-case EBCDIC handling */ #endif /* TEST_RANDOM */ /* Perform a general sanity check to make sure that the self-test is being run the right way */ if( !checkFileAccess() ) { cryptEnd(); exit( EXIT_FAILURE ); } /* Make sure that further system-specific features that require cryptlib to be initialised to check are set right */ #ifndef _WIN32_WCE testSystemSpecific2(); #endif /* WinCE */ #ifdef USE_TCHECK THREAD_DEBUG_RESUME(); #endif /* USE_TCHECK */ /* For general testing purposes we can insert test code at this point to test special cases that aren't covered in the general tests below */ testKludge( zargPtr ); #ifdef SMOKE_TEST /* Perform a general smoke test of the kernel */ smokeTest(); #endif /* SMOKE_TEST */ /* Test each block of cryptlib functionality */ if( ( flags & DO_SELFTEST ) && !testSelfTest() ) goto errorExit; if( ( flags & DO_LOWLEVEL ) && !testLowLevel() ) goto errorExit; if( ( flags & DO_RANDOM ) && !testRandom() ) goto errorExit; if( ( flags & DO_CONFIG ) && !testConfig() ) goto errorExit; if( ( flags & DO_DEVICE ) && !testDevice() ) goto errorExit; if( ( flags & DO_MIDLEVEL ) && !testMidLevel() ) goto errorExit; if( ( flags & DO_CERT ) && !testCert() ) goto errorExit; if( ( flags & DO_KEYSETFILE ) && !testKeysetFile() ) goto errorExit; if( ( flags & DO_KEYSETDBX ) && !testKeysetDatabase() ) goto errorExit; if( ( flags & DO_CERTPROCESS ) && !testCertMgmt() ) goto errorExit; if( ( flags & DO_HIGHLEVEL ) && !testHighLevel() ) goto errorExit; if( ( flags & DO_ENVELOPE ) && !testEnveloping() ) goto errorExit; if( ( flags & DO_SESSION ) && !testSessions() ) { sessionTestError = TRUE; goto errorExit; } if( ( flags & DO_SESSIONLOOPBACK ) && !testSessionsLoopback() ) { loopbackTestError = TRUE; goto errorExit; } if( ( flags & DO_USER ) && !testUsers() ) goto errorExit; /* Shut down cryptlib */ status = cryptEnd(); if( cryptStatusError( status ) ) { if( status == CRYPT_ERROR_INCOMPLETE ) { puts( "cryptEnd() failed with error code CRYPT_ERROR_INCOMPLETE, " "a code path in the\nself-test code resulted in an error " "return without a full cleanup of objects.\nIf you were " "running the multithreaded loopback tests this may be " "because one\nor more threads lost sync with other threads " "and exited without cleaning up\nits objects. This " "happens occasionally due to network timing issues or\n" "thread scheduling differences." ); } else { printf( "cryptEnd() failed with error code %d, line %d.\n", status, __LINE__ ); } goto errorExit1; } puts( "All tests concluded successfully." ); return( EXIT_SUCCESS ); /* All errors end up here */ errorExit: cryptEnd(); errorExit1: puts( "\nThe test was aborted due to an error being detected. If you " "want to report\nthis problem, please provide as much information " "as possible to allow it to\nbe diagnosed, for example the call " "stack, the location inside cryptlib where\nthe problem occurred, " "and the values of any variables that might be\nrelevant." ); if( sessionTestError ) { puts( "\nThe error occurred during one of the network session tests, " "if the error\nmessage indicates a network-level problem such " "as ECONNREFUSED, ECONNRESET,\nor a timeout or read error then " "this is either due to a transient\nnetworking problem or a " "firewall interfering with network connections. This\nisn't a " "cryptlib error, and doesn't need to be reported." ); } if( loopbackTestError ) { puts( "\nThe error occurred during one of the multi-threaded network " "loopback\ntests, this was probably due to the different threads " "losing synchronisation.\nFor the secure sessions this usually " "results in read/write, timeout, or\nconnection-closed errors " "when one thread is pre-empted for too long. For the\n" "certificate-management sessions it usually results in an error " "related to the\nserver being pre-empted for too long by database " "updates. Since the self-\ntest exists only to exercise " "cryptlib's capabilities, it doesn't bother with\ncomplex thread " "synchronisation during the multi-threaded loopback tests.\nThis " "type of error is non-fatal, and should disappear if the test is " "re-run." ); } cleanExit( EXIT_FAILURE ); return( EXIT_FAILURE ); /* Get rid of compiler warnings */ }
static void cleanupAndExit( const int exitStatus ) { cryptEnd(); cleanExit( exitStatus ); }
int main(int argc, char **argv) { int status; CRYPT_CONTEXT cryptContext; CRYPT_KEYSET cryptKeyset; printf("Initializing cryptlib\n"); status = cryptInit(); if (status != CRYPT_OK) { fprintf(stderr, "Error initializing cryptlib\n"); return 1; } /* Create an RSA public/private key context, set a label for it, and generate a key into it */ status = cryptCreateContext( &cryptContext, CRYPT_UNUSED, CRYPT_ALGO_RSA ); if (status != CRYPT_OK) { fprintf(stderr, "Error creating crypt_context\n"); return 1; } status = cryptSetAttributeString( cryptContext, CRYPT_CTXINFO_LABEL, "Private key", 11 ); if (status != CRYPT_OK) { fprintf(stderr, "Error setting key label\n"); return 1; } fprintf(stderr, "Generating RSA key\n"); status = cryptGenerateKey( cryptContext ); if (status != CRYPT_OK) { fprintf(stderr, "Error generating key\n"); return 1; } fprintf(stderr, "done!\n"); /* Save the generated public/private key pair to a keyset */ status = cryptKeysetOpen( &cryptKeyset, CRYPT_UNUSED, CRYPT_KEYSET_FILE, KEY_FILENAME, CRYPT_KEYOPT_CREATE ); if (status != CRYPT_OK) { fprintf(stderr, "Error opening keyset\n"); return 1; } status = cryptAddPrivateKey( cryptKeyset, cryptContext, PASSWORD ); if (status != CRYPT_OK) { fprintf(stderr, "Error adding key to keyset\n"); return 1; } status = cryptKeysetClose( cryptKeyset ); if (status != CRYPT_OK) { fprintf(stderr, "Error closing keyset\n"); return 1; } /* Create CSR */ createCSR(cryptContext); /* Create CA cert */ createCACert(cryptContext); /* Clean up */ status = cryptDestroyContext( cryptContext ); if (status != CRYPT_OK) { fprintf(stderr, "Error destroying context\n"); return 1; } printf("Deinitializing cryptlib\n"); status = cryptEnd(); if (status != CRYPT_OK) { fprintf(stderr, "Error deinitializing cryptlib\n"); return 1; } return 0; }
int main( int argc, char **argv ) { const char *zargPtr = NULL; BOOLEAN doSelftest = FALSE, doLowlevel = FALSE, doRandom = FALSE; BOOLEAN doConfig = FALSE, doMidlevel = FALSE, doCert = FALSE; BOOLEAN doKeyset = FALSE, doCertprocess = FALSE, doHighlevel = FALSE; BOOLEAN doEnvelope = FALSE, doSession = FALSE, doSessionLoopback = FALSE; BOOLEAN doAll = FALSE, moreArgs = TRUE; BOOLEAN sessionTestError = FALSE, loopbackTestError = FALSE; int status; void testSystemSpecific1( void ); void testSystemSpecific2( void ); /* Print a general banner to let the user know what's going on */ printf( "testlib - cryptlib %d-bit self-test framework.\n", sizeof( long ) * 8 ); puts( "Copyright Peter Gutmann 1995 - 2010." ); puts( "" ); /* Skip the program name */ argv++; argc--; /* No args means test everything */ if( argc <= 0 ) doAll = TRUE; /* Check for arguments */ while( argc > 0 && *argv[ 0 ] == '-' && moreArgs ) { const char *argPtr = argv[ 0 ] + 1; while( *argPtr ) { switch( toupper( *argPtr ) ) { case '-': moreArgs = FALSE; /* GNU-style end-of-args flag */ break; case 'B': doSelftest = TRUE; break; case 'C': doCert = TRUE; break; case 'E': doEnvelope = TRUE; break; case 'F': doSessionLoopback = TRUE; break; case 'H': usageExit(); break; case 'I': doHighlevel = TRUE; break; case 'K': doKeyset = TRUE; break; case 'L': doLowlevel = TRUE; break; case 'M': doMidlevel = TRUE; break; case 'O': doConfig = TRUE; break; case 'P': doCertprocess = TRUE; break; case 'R': doRandom = TRUE; break; case 'S': doSession = TRUE; break; case 'Z': zargPtr = argPtr + 1; if( *zargPtr == '\0' ) { puts( "Error: Missing argument for -z option." ); exit( EXIT_FAILURE ); } while( argPtr[ 1 ] ) argPtr++; /* Skip rest of arg */ break; default: printf( "Error: Unknown argument '%c'.\n", *argPtr ); return( EXIT_FAILURE ); } argPtr++; } argv++; argc--; } #ifdef USE_TCHECK THREAD_DEBUG_SUSPEND(); #endif /* USE_TCHECK */ /* Make sure that various system-specific features are set right */ testSystemSpecific1(); /* VisualAge C++ doesn't set the TZ correctly. The check for this isn't as simple as it would seem since most IBM compilers define the same preprocessor values even though it's not documented anywhere, so we have to enable the tzset() call for (effectively) all IBM compilers and then disable it for ones other than VisualAge C++ */ #if ( defined( __IBMC__ ) || defined( __IBMCPP__ ) ) && !defined( __VMCMS__ ) tzset(); #endif /* VisualAge C++ */ /* Initialise cryptlib */ printf( "Initialising cryptlib..." ); status = cryptInit(); if( cryptStatusError( status ) ) { printf( "\ncryptInit() failed with error code %d, line %d.\n", status, __LINE__ ); exit( EXIT_FAILURE ); } puts( "done." ); #ifndef TEST_RANDOM /* In order to avoid having to do a randomness poll for every test run, we bypass the randomness-handling by adding some junk. This is only enabled when cryptlib is built in debug mode so it won't work with any production systems */ #if defined( __MVS__ ) || defined( __VMCMS__ ) #pragma convlit( resume ) cryptAddRandom( "xyzzy", 5 ); #pragma convlit( suspend ) #else cryptAddRandom( "xyzzy", 5 ); #endif /* Special-case EBCDIC handling */ #endif /* TEST_RANDOM */ /* Perform a general sanity check to make sure that the self-test is being run the right way */ if( !checkFileAccess() ) goto errorExit; /* Make sure that further system-specific features that require cryptlib to be initialised to check are set right */ #ifndef _WIN32_WCE testSystemSpecific2(); #endif /* WinCE */ #ifdef USE_TCHECK THREAD_DEBUG_RESUME(); #endif /* USE_TCHECK */ /* For general testing purposes we can insert test code at this point to test special cases that aren't covered in the general tests below */ testKludge( zargPtr ); #ifdef SMOKE_TEST /* Perform a general smoke test of the kernel */ smokeTest(); #endif /* SMOKE_TEST */ /* Test each block of cryptlib functionality */ if( ( doSelftest || doAll ) && !testSelfTest() ) goto errorExit; if( ( doLowlevel || doAll ) && !testLowLevel() ) goto errorExit; if( ( doRandom || doAll ) && !testRandom() ) goto errorExit; if( ( doConfig || doAll ) && !testConfig() ) goto errorExit; if( ( doSelftest || doAll ) && !testDevice() ) goto errorExit; if( ( doMidlevel || doAll ) && !testMidLevel() ) goto errorExit; if( ( doCert || doAll ) && !testCert() ) goto errorExit; if( ( doKeyset || doAll ) && !testKeyset() ) goto errorExit; if( ( doCertprocess || doAll ) && !testCertMgmt() ) goto errorExit; if( ( doHighlevel || doAll ) && !testHighLevel() ) goto errorExit; if( ( doEnvelope || doAll ) && !testEnveloping() ) goto errorExit; if( ( doSession || doAll ) && !testSessions() ) { sessionTestError = TRUE; goto errorExit; } if( ( doSessionLoopback || doAll ) && !testSessionsLoopback() ) { loopbackTestError = TRUE; goto errorExit; } if( ( doAll ) && !testUsers() ) goto errorExit; /* Shut down cryptlib */ status = cryptEnd(); if( cryptStatusError( status ) ) { if( status == CRYPT_ERROR_INCOMPLETE ) { puts( "cryptEnd() failed with error code CRYPT_ERROR_INCOMPLETE, " "a code path in the\nself-test code resulted in an error " "return without a full cleanup of objects.\nIf you were " "running the multithreaded loopback tests this may be " "because one\nor more threads lost sync with other threads " "and exited without cleaning up\nits objects. This " "happens occasionally due to network timing issues or\n" "thread scheduling differences." ); } else { printf( "cryptEnd() failed with error code %d, line %d.\n", status, __LINE__ ); } goto errorExit1; } puts( "All tests concluded successfully." ); return( EXIT_SUCCESS ); /* All errors end up here */ errorExit: cryptEnd(); errorExit1: puts( "\nThe test was aborted due to an error being detected. If you " "want to report\nthis problem, please provide as much information " "as possible to allow it to\nbe diagnosed, for example the call " "stack, the location inside cryptlib where\nthe problem occurred, " "and the values of any variables that might be\nrelevant." ); if( sessionTestError ) { puts( "\nThe error occurred during one of the network session tests, " "if the error\nmessage indicates a network-level problem such " "as ECONNREFUSED, ECONNRESET,\nor a timeout or read error then " "this is either due to a transient\nnetworking problem or a " "firewall interfering with network connections. This\nisn't a " "cryptlib error, and doesn't need to be reported." ); } #ifdef WINDOWS_THREADS if( loopbackTestError ) { puts( "\nThe error occurred during one of the multi-threaded network " "loopback\ntests, this was probably due to the different threads " "losing synchronisation.\nFor the secure sessions this usually " "results in read/write, timeout, or\nconnection-closed errors " "when one thread is pre-empted for too long. For the\n" "certificate-management sessions it usually results in an error " "related to the\nserver being pre-empted for too long by database " "updates. Since the self-\ntest exists only to exercise " "cryptlib's capabilities, it doesn't bother with\ncomplex thread " "synchronisation during the multi-threaded loopback tests.\nThis " "type of error is non-fatal, and should disappear if the test is " "re-run." ); } #endif /* WINDOWS_THREADS */ #if defined( __WINDOWS__ ) && !defined( NDEBUG ) /* The pseudo-CLI VC++ output windows are closed when the program exits so we have to explicitly wait to allow the user to read them */ puts( "\nHit a key..." ); getchar(); #endif /* __WINDOWS__ && !NDEBUG */ return( EXIT_FAILURE ); }
main(int argc, char **argv){ int i; /* Loop iterator */ int ret; /* Return value */ int total; /* Total key bytes */ int bytesCopied; /* Bytes output by cryptlib enc/dec ops */ int urandFd; /* Pointer to /dev/urandom */ char *keyPtr; /* Pointer to key */ CRYPT_ENVELOPE dataEnv; /* Envelope for encrypt/decrypt */ CRYPT_CONTEXT symContext; /* Key context */ char *clrDataPtr; /* Pointer to clear text */ int clrDataSize; /* Bytes of clear text */ int clrDataFd; /* Pointer to clear text file */ struct stat clrDataFileInfo; /* fstat return for clear text file */ int encDataFd; /* Pointer to encrypted text file */ char *encDataPtr; /* Pointer to encrypted data */ int encDataSize; /* Buffer bytes availble for decrypt */ struct stat encDataFileInfo; /* fstat return for encrypted data file */ if (argc!=3) {printf("Wrong number of arguments\n");exit(__LINE__);} /*============================================== Cryptlib initialization ============================================== */ cryptInit(); ret=cryptAddRandom( NULL , CRYPT_RANDOM_SLOWPOLL); checkCryptNormal(ret,"cryptAddRandom",__LINE__); /*============================================= Open DATAFILE and get data ============================================= */ clrDataFd=open(argv[1],O_RDONLY); if (clrDataFd<=0){perror("open clrData");exit(clrDataFd);} ret=fstat(clrDataFd,&clrDataFileInfo); if (ret!=0){perror("fstat clrDataFd");exit(ret);} clrDataSize=clrDataFileInfo.st_size; clrDataPtr=malloc(clrDataFileInfo.st_size); if (clrDataPtr==NULL){perror("malloc clrData");exit(__LINE__);} ret=read(clrDataFd,clrDataPtr,clrDataSize); if (ret!=clrDataSize){perror("read clrData");exit(ret);} close(clrDataFd); /*============================================== (1) Generate the key ============================================== */ keyPtr=malloc(KEYSIZE); if (keyPtr==NULL){perror("malloc keyPtr");exit(__LINE__);} urandFd=open("/dev/urandom",O_RDONLY); if (urandFd<=0){perror("open urandFd");exit(urandFd);} total=0;ret=0; while (total<KEYSIZE){ ret=read(urandFd,&keyPtr[total],KEYSIZE-total);total+=ret; if (ret < 0){perror("read urand");exit(ret);} } close(urandFd); /*============================================== (2) Encrypt data from file with the key and write it to output file. ============================================== */ ret=cryptCreateEnvelope(&dataEnv, CRYPT_UNUSED, CRYPT_FORMAT_CRYPTLIB); checkCryptNormal(ret,"cryptCreateEnvelope",__LINE__); ret=cryptCreateContext(&symContext, CRYPT_UNUSED, SYMMETRIC_ALG); checkCryptNormal(ret,"cryptCreateContext",__LINE__); ret=cryptSetAttributeString(symContext, CRYPT_CTXINFO_KEY,keyPtr,KEYSIZE); checkCryptNormal(ret,"cryptSetAttributeString",__LINE__); ret=cryptSetAttribute(dataEnv, CRYPT_ENVINFO_SESSIONKEY, symContext); checkCryptNormal(ret,"cryptSetAttribute",__LINE__); ret=cryptDestroyContext(symContext); checkCryptNormal(ret,"cryptDestroyContext",__LINE__); ret=cryptSetAttribute(dataEnv, CRYPT_ENVINFO_DATASIZE, clrDataSize); checkCryptNormal(ret,"cryptSetAttribute",__LINE__); ret=cryptPushData(dataEnv,clrDataPtr,clrDataSize,&bytesCopied); checkCryptNormal(ret,"cryptAddRandom",__LINE__); cryptFlushData(dataEnv); encDataSize=clrDataFileInfo.st_size+2048; encDataPtr=malloc(encDataSize); if (encDataPtr==NULL){perror("malloc encData");exit(__LINE__);} ret=cryptPopData(dataEnv,encDataPtr,encDataSize,&bytesCopied); checkCryptNormal(ret,"cryptPopData",__LINE__); printf("<%d> bytes of encrypted data\n",bytesCopied); ret=cryptDestroyEnvelope(dataEnv); checkCryptNormal(ret,"cryptDestroyEnvelope",__LINE__); encDataFd=open(argv[2],O_RDWR|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR); if (encDataFd<=0){perror("open encDataFd");exit(encDataFd);} ret=write(encDataFd,encDataPtr,bytesCopied); if (ret!=bytesCopied){perror("write encData");exit(ret);} close(encDataFd); free(encDataPtr); /*====================================================== Get decrypted data from file and write to stdout ====================================================== */ encDataFd=open(argv[2],O_RDONLY); if (encDataFd<=0){perror("(2) open encDataFd");exit(encDataFd);} ret=fstat(encDataFd,&encDataFileInfo); if (ret!=0){perror("fstat encDataFd");exit(ret);} encDataSize=encDataFileInfo.st_size; encDataPtr=malloc(encDataSize); if (encDataPtr==NULL){perror("malloc encData");exit(__LINE__);} ret=read(encDataFd,encDataPtr,encDataSize); if (ret!=encDataSize){perror("read encData");exit(ret);} close(encDataFd); cryptCreateEnvelope(&dataEnv, CRYPT_UNUSED, CRYPT_FORMAT_AUTO); checkCryptNormal(ret,"cryptCreateEnvelope",__LINE__); cryptPushData(dataEnv,encDataPtr,encDataSize,&bytesCopied); checkCryptNormal(ret,"cryptPushData",__LINE__); cryptCreateContext(&symContext,CRYPT_UNUSED,SYMMETRIC_ALG); checkCryptNormal(ret,"cryptCreateContext",__LINE__); cryptSetAttributeString(symContext, CRYPT_CTXINFO_KEY,keyPtr,KEYSIZE); checkCryptNormal(ret,"cryptSetAttributeString",__LINE__); cryptSetAttribute(dataEnv,CRYPT_ENVINFO_SESSIONKEY,symContext); checkCryptNormal(ret,"cryptSetAttribute",__LINE__); ret=cryptDestroyContext(symContext); checkCryptNormal(ret,"cryptDestroyContext",__LINE__); cryptFlushData(dataEnv); ret=cryptPopData(dataEnv,clrDataPtr,clrDataSize,&bytesCopied); checkCryptNormal(ret,"cryptPopData",__LINE__); ret=cryptDestroyEnvelope(dataEnv); checkCryptNormal(ret,"cryptDestroyEnvelope",__LINE__); printf("<%d> bytes of decrypted data\n",bytesCopied); for (i=0;i<bytesCopied;i++){printf("%c",clrDataPtr[i]);} printf("\n"); fflush(stdout); ret=cryptEnd(); checkCryptNormal(ret,"cryptEnd",__LINE__); }
int main(int argc, char const *argv[]) { struct passwd *pws; /* info for input user */ char *pwname; /* username */ char *pwdir; /* home directory */ char *encFile; char *encKey; int encKeyFd; //file state char *encKeyPtr; /* Pointer to encrypted data */ int encKeySize; /* Buffer bytes availble for decrypt */ struct stat fileStat; /* Struce for checking file attributes */ char *keyFile; /* GPG key ring file name */ char *gpgPrivateKeyPtr; int ret; /* Return code */ int i; /* Loop iterator */ int bytesCopied; /* Bytes output by cryptlib enc/dec ops */ int reqAttrib; /* Crypt required attributed */ CRYPT_ENVELOPE dataEnv; /* Envelope for enc/dec */ CRYPT_KEYSET keyset; /* GPG keyset */ CRYPT_CONTEXT symContext; /* Key context */ char label[100]; /* Private key label */ int labelLength; /* Length of label */ char passbuf[1024]; /* Buffer for GPG key passphrase */ struct termios ts, ots; /* Strutures for saving/modifying term attribs */ char *encDataPtr; /* Pointer to encrypted data */ int encDataSize; /* Size of encrypted data */ struct passwd *userInfo; /* Password info for input user */ int encFileFd; /* Destination (Encrypted) File Descriptor */ int encFileSize; /* Bytes of encrypted data */ char * encFilePtr; /* Pointer to enc text */ char *clrFilePtr; /* Pointer to clear text */ int clrFileSize; /* Bytes of clear text */ char *clrKeyPtr; int clrKeySize; struct stat encFileInfo; uid = getuid(); pws = getpwuid(uid); pwname = pws->pw_name;//get the user login name; pwdir = pws->pw_dir;//get the user dir path //Check arguments number if (argc!=2) { printf("slient exit\n"); exit (1); } //Get encrepted file encFile = malloc(strlen(argv[1]) + 4); strcpy(encFile, argv[1]); strcat(encFile, ".enc"); //Get gpg encrepted key name encKey = malloc(strlen(encFile) + strlen(pwname) +5 ); strcpy(encKey,encFile); strcat(encKey, "."); strcat(encKey, pwname); strcat(encKey, ".key"); //Open gpg encrepted key encKeyFd=open(encKey, O_RDONLY); if (encKeyFd<=0){perror("(2) open encKeyFd2");exit(encKeyFd);} ret=fstat(encKeyFd,&fileStat); if (ret!=0){perror("fstat encKeyFd");exit(ret);} encKeySize=fileStat.st_size; encKeyPtr=malloc(encKeySize); if (encKeyPtr==NULL){perror("malloc encData");exit(__LINE__);} ret=read(encKeyFd,encKeyPtr,encKeySize); if (ret!=encKeySize){perror("read encData");exit(ret);} close(encKeyFd); //Get the private key name gpgPrivateKeyPtr=malloc(strlen(pwdir) + strlen("/.gnupg/secring.gpg") + 1); getPrivateKeyName(gpgPrivateKeyPtr,uid); //Decrypt key cryptInit(); ret=cryptAddRandom( NULL , CRYPT_RANDOM_SLOWPOLL); checkCryptNormal(ret,"cryptAddRandom",__LINE__); ret=cryptKeysetOpen(&keyset, CRYPT_UNUSED, CRYPT_KEYSET_FILE, gpgPrivateKeyPtr, CRYPT_KEYOPT_READONLY); free(gpgPrivateKeyPtr); checkCryptNormal(ret,"cryptKeysetOpen",__LINE__); ret=cryptCreateEnvelope(&dataEnv, CRYPT_UNUSED, CRYPT_FORMAT_AUTO); checkCryptNormal(ret,"cryptCreateEnvelope",__LINE__); ret=cryptSetAttribute(dataEnv, CRYPT_ENVINFO_KEYSET_DECRYPT, keyset); checkCryptNormal(ret,"cryptSetAttribute",__LINE__); ret=cryptPushData(dataEnv,encKeyPtr,encKeySize,&bytesCopied); /* Expect non-zero return -- indicates need private key */ ret=cryptGetAttribute(dataEnv, CRYPT_ATTRIBUTE_CURRENT, &reqAttrib); if (reqAttrib != CRYPT_ENVINFO_PRIVATEKEY) {printf("Decrypt error\n");exit(ret);} ret=cryptGetAttributeString(dataEnv, CRYPT_ENVINFO_PRIVATEKEY_LABEL, label, &labelLength); label[labelLength]='\0'; checkCryptNormal(ret,"cryptGetAttributeString",__LINE__); /*=============================================== Get the passphrase =============================================== */ tcgetattr(STDIN_FILENO, &ts); ots = ts; ts.c_lflag &= ~ECHO; ts.c_lflag |= ECHONL; tcsetattr(STDIN_FILENO, TCSAFLUSH, &ts); tcgetattr(STDIN_FILENO, &ts); if (ts.c_lflag & ECHO) { fprintf(stderr, "Failed to turn off echo\n"); tcsetattr(STDIN_FILENO, TCSANOW, &ots); exit(1); } printf("Enter password for <%s>: ",label); fflush(stdout); fgets(passbuf, 1024, stdin); tcsetattr(STDIN_FILENO, TCSANOW, &ots); ret=cryptSetAttributeString(dataEnv, CRYPT_ENVINFO_PASSWORD, passbuf, strlen(passbuf)-1); if (ret != CRYPT_OK) { if (ret=CRYPT_ERROR_WRONGKEY) { printf("Wrong Key\n"); exit(ret); }else{ printf("cryptSetAttributeString line %d returned <%d>\n",__LINE__,ret); exit(ret); } } ret=cryptFlushData(dataEnv); checkCryptNormal(ret,"cryptFlushData",__LINE__); clrKeySize=KEYSIZE; clrKeyPtr=malloc(clrKeySize); if (clrKeyPtr==NULL){perror("malloc");exit(__LINE__);} bzero(clrKeyPtr,clrKeySize); ret=cryptPopData(dataEnv,clrKeyPtr,clrKeySize,&bytesCopied); checkCryptNormal(ret,"cryptPopData",__LINE__); ret=cryptDestroyEnvelope(dataEnv); checkCryptNormal(ret,"cryptDestroyEnvelope",__LINE__); cryptKeysetClose(keyset); checkCryptNormal(ret,"cryptKeysetClose",__LINE__); printf("Bytes decrypted <%d>\n",bytesCopied); // for (i=0;i<bytesCopied;i++){printf("%c",clrKeyPtr[i]);} ret=cryptEnd(); checkCryptNormal(ret,"cryptEnd",__LINE__); //read enc file encFileFd=open(encFile, O_RDONLY); if (encFileFd<=0){perror("(2) open encFileFd1");exit(encFileFd);} ret=fstat(encFileFd,&encFileInfo); if (ret!=0){perror("fstat encFileFd");exit(ret);} encFileSize=encFileInfo.st_size; encFilePtr=malloc(encFileSize); if (encFilePtr==NULL){perror("malloc encData");exit(__LINE__);} ret=read(encFileFd,encFilePtr,encFileSize); if (ret!=encFileSize){perror("read encData");exit(ret);} close(encFileFd); //Decrypt and get the content of decrepted file cryptInit(); ret=cryptAddRandom( NULL , CRYPT_RANDOM_SLOWPOLL); checkCryptNormal(ret,"cryptAddRandom",__LINE__); cryptCreateEnvelope(&dataEnv, CRYPT_UNUSED, CRYPT_FORMAT_AUTO); checkCryptNormal(ret,"cryptCreateEnvelope",__LINE__); cryptPushData(dataEnv,encFilePtr,encFileSize,&bytesCopied); checkCryptNormal(ret,"cryptPushData",__LINE__); cryptCreateContext(&symContext,CRYPT_UNUSED,SYMMETRIC_ALG); checkCryptNormal(ret,"cryptCreateContext",__LINE__); cryptSetAttributeString(symContext, CRYPT_CTXINFO_KEY,clrKeyPtr,clrKeySize); checkCryptNormal(ret,"cryptSetAttributeString",__LINE__); cryptSetAttribute(dataEnv,CRYPT_ENVINFO_SESSIONKEY,symContext); checkCryptNormal(ret,"cryptSetAttribute",__LINE__); ret=cryptDestroyContext(symContext); checkCryptNormal(ret,"cryptDestroyContext",__LINE__); cryptFlushData(dataEnv); clrFileSize=KEYSIZE+1028; clrFilePtr=malloc(encDataSize); ret=cryptPopData(dataEnv,clrFilePtr,clrFileSize,&bytesCopied); checkCryptNormal(ret,"cryptPopData",__LINE__); ret=cryptDestroyEnvelope(dataEnv); checkCryptNormal(ret,"cryptDestroyEnvelope",__LINE__); printf("<%d> bytes of decrypted data\n",bytesCopied); for (i=0;i<bytesCopied;i++){printf("%c",clrFilePtr[i]);} printf("\n"); fflush(stdout); ret=cryptEnd(); checkCryptNormal(ret,"cryptEnd",__LINE__); return 0; }
static void updateConfig( void ) { #if 0 const char *driverPath = "c:/winnt/system32/acospkcs11.dll";/* ACOS */ const char *driverPath = "c:/winnt/system32/aetpkss1.dll"; /* AET */ const char *driverPath = "c:/winnt/system32/aloaha_pkcs11.dll"; /* Aloaha */ const char *driverPath = "c:/winnt/system32/etpkcs11.dll"; /* Aladdin eToken */ const char *driverPath = "c:/winnt/system32/psepkcs11.dll"; /* A-Sign */ const char *driverPath = "c:/winnt/system32/asepkcs.dll"; /* Athena */ const char *driverPath = "c:/winnt/system32/cryst32.dll"; /* Chrysalis */ const char *driverPath = "c:/program files/luna/cryst201.dll"; /* Chrysalis */ const char *driverPath = "c:/winnt/system32/pkcs201n.dll"; /* Datakey */ const char *driverPath = "c:/winnt/system32/dkck201.dll"; /* Datakey (for Entrust) */ const char *driverPath = "c:/winnt/system32/dkck232.dll"; /* Datakey/iKey (NB: buggy, use 201) */ const char *driverPath = "c:/program files/eracom/cprov sw/cryptoki.dll"; /* Eracom (old, OK) */ const char *driverPath = "c:/program files/eracom/cprov runtime/cryptoki.dll"; /* Eracom (new, doesn't work) */ const char *driverPath = "c:/winnt/system32/sadaptor.dll"; /* Eutron */ const char *driverPath = "c:/winnt/system32/ngp11v211.dll"; /* Feitain Technology */ const char *driverPath = "c:/winnt/system32/pk2priv.dll"; /* Gemplus */ const char *driverPath = "c:/program files/gemplus/gclib.dll"; /* Gemplus */ const char *driverPath = "c:/winnt/system32/cryptoki.dll"; /* IBM */ const char *driverPath = "c:/winnt/system32/csspkcs11.dll"; /* IBM */ const char *driverPath = "c:/winnt/system32/ibmpkcss.dll"; /* IBM */ const char *driverPath = "c:/winnt/system32/id2cbox.dll"; /* ID2 */ const char *driverPath = "c:/winnt/system32/cknfast.dll"; /* nCipher */ const char *driverPath = "/opt/nfast/toolkits/pkcs11/libcknfast.so";/* nCipher under Unix */ const char *driverPath = "/usr/lib/libcknfast.so"; /* nCipher under Unix */ const char *driverPath = "softokn3.dll"; /* Netscape */ const char *driverPath = "c:/winnt/system32/nxpkcs11.dll"; /* Nexus */ const char *driverPath = "c:/winnt/system32/AuCryptoki2-0.dll"; /* Oberthur */ const char *driverPath = "c:/winnt/system32/opensc-pkcs11.dll"; /* OpenSC */ const char *driverPath = "c:/winnt/system32/micardoPKCS11.dll"; /* Orga Micardo */ const char *driverPath = "c:/winnt/system32/cryptoki22.dll";/* Rainbow HSM (for USB use Datakey dvr) */ const char *driverPath = "c:/winnt/system32/p11card.dll"; /* Safelayer HSM (for USB use Datakey dvr) */ const char *driverPath = "c:/winnt/system32/slbck.dll"; /* Schlumberger */ const char *driverPath = "c:/winnt/system32/SetTokI.dll"; /* SeTec */ const char *driverPath = "c:/winnt/system32/siecap11.dll"; /* Siemens */ const char *driverPath = "c:/winnt/system32/smartp11.dll"; /* SmartTrust */ const char *driverPath = "c:/winnt/system32/SpyPK11.dll"; /* Spyrus */ #endif /* 0 */ const char *driverPath = "c:/program files/eracom/cprov sw/cryptoki.dll"; /* Eracom (old, OK) */ int status; printf( "Updating cryptlib configuration to load PKCS #11 driver\n " "'%s'\n as default driver...", driverPath ); /* Set the path for a PKCS #11 device driver. We only enable one of these at a time to speed the startup time */ status = cryptSetAttributeString( CRYPT_UNUSED, CRYPT_OPTION_DEVICE_PKCS11_DVR01, driverPath, strlen( driverPath ) ); if( cryptStatusError( status ) ) { printf( "\n\nError updating PKCS #11 device driver profile, " "status %d.\n", status ); return; } /* Flush the updated options to disk */ status = cryptSetAttribute( CRYPT_UNUSED, CRYPT_OPTION_CONFIGCHANGED, FALSE ); if( cryptStatusError( status ) ) { printf( "\n\nError comitting device driver profile update to disk, " "status %d.\n", status ); return; } puts( " done.\n\nYou'll need to restart cryptlib for the changes to " "take effect." ); cryptEnd(); puts( "\nPress a key to exit." ); getchar(); exit( EXIT_SUCCESS ); }
main(int argc, char **argv){ int ret; /* Return code */ int i; /* Loop iterator */ int bytesCopied; /* Bytes output by cryptlib enc/dec ops */ int reqAttrib; /* Crypt required attributed */ CRYPT_ENVELOPE dataEnv; /* Envelope for enc/dec */ CRYPT_KEYSET keyset; /* GPG keyset */ CRYPT_CONTEXT symContext; /* Key context */ char *keyPtr; /* Pointer to key */ char label[100]; /* Private key label */ int labelLength; /* Length of label */ char passbuf[1024]; /* Buffer for GPG key passphrase */ struct termios ts, ots; /* Strutures for saving/modifying term attribs */ char *clrDataPtr; /* Pointer to clear text */ int clrDataSize; /* Size of clear text */ int clrDataFd; /* Pointer to clear text file */ char *encDataPtr; /* Pointer to encrypted data */ int encDataSize; /* Size of encrypted data */ int encDataFd; /* Pointer to encrypted text file */ struct stat encDataFileInfo; /* fstat return for encrypted data file */ struct passwd *userInfo; /* Password info for input user */ char *keyFile; /* GPG key ring file name */ uid_t ownerID = getuid(); struct passwd *owner_pws = getpwuid(ownerID); char* owner_pwname = owner_pws->pw_name;//get the user login name; char* owner_pwdir = owner_pws->pw_dir; char *fileKeyName; *fileKeyName = malloc(strlen(owner_pwname)+strlen(argv[2]+10)); strcpy(fileKeyName,argv[2]); strcat(fileKeyName,".enc."); strcat(fileKeyName,owner_pwname); strcat(fileKeyName,".key"); printf("%s\n",fileKeyName); char *outputFileKeyName = malloc(strlen(argv[1])+strlen(argv[2])+20); strcpy(outputFileKeyName,argv[2]); strcat(outputFileKeyName,".enc."); strcat(outputFileKeyName,argv[1]); strcat(outputFileKeyName,".key"); printf("%s\n",outputFileKeyName); /*============================================== Check Check Check Check Check Check ============================================== */ if (argc!=3) {printf("Wrong number of arguments\n");exit(1);} char *fileName = malloc(strlen(argv[2])+5); strcpy(fileName,argv[2]); strcat(fileName,".enc"); fileChecker(fileName); /*============================================= Open DATAFILE and get data ============================================= */ encDataFd=open(fileKeyName,O_RDONLY); if (encDataFd<=0){perror("open encData1");exit(encDataFd);} ret=fstat(encDataFd,&encDataFileInfo); if (ret!=0){perror("fstat encDataFd");exit(ret);} encDataSize=encDataFileInfo.st_size; encDataPtr=malloc(encDataFileInfo.st_size); if (encDataPtr==NULL){perror("malloc encData");exit(__LINE__);} ret=read(encDataFd,encDataPtr,encDataSize); if (ret!=encDataSize){perror("read encData");exit(ret);} close(encDataFd); /*============================================== Cryptlib initialization ============================================== */ //cryptInit(); //ret=cryptAddRandom( NULL , CRYPT_RANDOM_SLOWPOLL); //checkCryptNormal(ret,"cryptAddRandom",__LINE__); /*================================================= Decrypt the key ================================================= */ keyFile=malloc( strlen(owner_pwdir ) + strlen("/.gnupg/secring.gpg") + 1); if (keyFile==NULL){perror("malloc");exit(__LINE__);} strcpy(keyFile,owner_pwdir); strcat(keyFile,"/.gnupg/secring.gpg"); printf("Getting secret key from <%s>\n",keyFile); //Decrypt key cryptInit(); ret=cryptAddRandom( NULL , CRYPT_RANDOM_SLOWPOLL); checkCryptNormal(ret,"cryptAddRandom",__LINE__); ret=cryptKeysetOpen(&keyset, CRYPT_UNUSED, CRYPT_KEYSET_FILE, keyFile, CRYPT_KEYOPT_READONLY); free(keyFile); checkCryptNormal(ret,"cryptKeysetOpen",__LINE__); ret=cryptCreateEnvelope(&dataEnv, CRYPT_UNUSED, CRYPT_FORMAT_AUTO); checkCryptNormal(ret,"cryptCreateEnvelope",__LINE__); ret=cryptSetAttribute(dataEnv, CRYPT_ENVINFO_KEYSET_DECRYPT, keyset); checkCryptNormal(ret,"cryptSetAttribute",__LINE__); ret=cryptPushData(dataEnv,encDataPtr,encDataSize,&bytesCopied); /* Expect non-zero return -- indicates need private key */ ret=cryptGetAttribute(dataEnv, CRYPT_ATTRIBUTE_CURRENT, &reqAttrib); if (reqAttrib != CRYPT_ENVINFO_PRIVATEKEY) {printf("Decrypt error\n");exit(ret);} ret=cryptGetAttributeString(dataEnv, CRYPT_ENVINFO_PRIVATEKEY_LABEL, label, &labelLength); label[labelLength]='\0'; checkCryptNormal(ret,"cryptGetAttributeString",__LINE__); /*=============================================== Get the passphrase =============================================== */ tcgetattr(STDIN_FILENO, &ts); ots = ts; ts.c_lflag &= ~ECHO; ts.c_lflag |= ECHONL; tcsetattr(STDIN_FILENO, TCSAFLUSH, &ts); tcgetattr(STDIN_FILENO, &ts); if (ts.c_lflag & ECHO) { fprintf(stderr, "Failed to turn off echo\n"); tcsetattr(STDIN_FILENO, TCSANOW, &ots); exit(1); } printf("Enter password for <%s>: ",label); fflush(stdout); fgets(passbuf, 1024, stdin); tcsetattr(STDIN_FILENO, TCSANOW, &ots); ret=cryptSetAttributeString(dataEnv, CRYPT_ENVINFO_PASSWORD, passbuf, strlen(passbuf)-1); if (ret != CRYPT_OK) { if (ret=CRYPT_ERROR_WRONGKEY) { printf("Wrong Key\n"); exit(ret); }else{ printf("cryptSetAttributeString line %d returned <%d>\n",__LINE__,ret); exit(ret); } } ret=cryptFlushData(dataEnv); checkCryptNormal(ret,"cryptFlushData",__LINE__); clrDataSize=KEYSIZE; clrDataPtr=malloc(clrDataSize); if (clrDataPtr==NULL){perror("malloc");exit(__LINE__);} bzero(clrDataPtr,clrDataSize); ret=cryptPopData(dataEnv,clrDataPtr,clrDataSize,&bytesCopied); checkCryptNormal(ret,"cryptPopData",__LINE__); ret=cryptDestroyEnvelope(dataEnv); checkCryptNormal(ret,"cryptDestroyEnvelope",__LINE__); cryptKeysetClose(keyset); checkCryptNormal(ret,"cryptKeysetClose",__LINE__); printf("Bytes decrypted <%d>\n",bytesCopied); for (i=0;i<bytesCopied;i++){printf("%c",clrDataPtr[i]);} ret=cryptEnd(); checkCryptNormal(ret,"cryptEnd",__LINE__); /*==================================================== Part2 Encrypt the key with user's private key ==================================================== */ /*============================================== Cryptlib initialization ============================================== */ cryptInit(); ret=cryptAddRandom( NULL , CRYPT_RANDOM_SLOWPOLL); checkCryptNormal(ret,"cryptAddRandom",__LINE__); /*==================================================== Get key file name ==================================================== */ keyFile=malloc( strlen(owner_pwdir ) + strlen("/.gnupg/pubring.gpg") + 1); if (keyFile==NULL){perror("malloc");exit(__LINE__);} strcpy(keyFile,owner_pwdir); strcat(keyFile,"/.gnupg/pubring.gpg"); printf("Getting secret key from <%s>\n",keyFile); /*==================================================== Encrypt key with GPG public key Email address is for recipient =================================================== */ ret=cryptKeysetOpen(&keyset, CRYPT_UNUSED, CRYPT_KEYSET_FILE, keyFile, CRYPT_KEYOPT_READONLY); free(keyFile); checkCryptNormal(ret,"cryptKeysetOpen",__LINE__); ret=cryptCreateEnvelope(&dataEnv, CRYPT_UNUSED, CRYPT_FORMAT_PGP); checkCryptNormal(ret,"cryptCreateEnvelope",__LINE__); ret=cryptSetAttribute(dataEnv, CRYPT_ENVINFO_KEYSET_ENCRYPT, keyset); checkCryptNormal(ret,"cryptSetAttribute",__LINE__); ret=cryptSetAttributeString(dataEnv, CRYPT_ENVINFO_RECIPIENT, argv[1],strlen(argv[1])); checkCryptNormal(ret,"cryptSetAttributeString",__LINE__); ret=cryptSetAttribute(dataEnv, CRYPT_ENVINFO_DATASIZE, KEYSIZE); ret=cryptPushData(dataEnv,clrDataPtr,KEYSIZE,&bytesCopied); checkCryptNormal(ret,"cryptPushData",__LINE__); ret=cryptFlushData(dataEnv); checkCryptNormal(ret,"cryptFlushData",__LINE__); encDataSize=strlen(clrDataPtr)+1+1028; encDataPtr=malloc(encDataSize); if (encDataPtr==NULL){perror("malloc");exit(__LINE__);} ret=cryptPopData(dataEnv,encDataPtr,encDataSize,&bytesCopied); printf("cryptPopData returned <%d> bytes of encrypted data\n",bytesCopied); encDataSize=bytesCopied; ret=cryptDestroyEnvelope(dataEnv); checkCryptNormal(ret,"cryptDestroyEnvelope",__LINE__); cryptKeysetClose(keyset); checkCryptNormal(ret,"cryptKeysetClose",__LINE__); /*============================================== write it to output file. ============================================== */ printf("%s\n",outputFileKeyName); encDataFd=open(outputFileKeyName,O_RDWR|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR); if (encDataFd<=0){perror("open encDataFd");exit(encDataFd);} ret=write(encDataFd,encDataPtr,bytesCopied); if (ret!=bytesCopied){perror("write encData");exit(ret);} close(encDataFd); int chmodStat = chmod (outputFileKeyName, S_IWRITE| S_IREAD| S_IRGRP | S_IWGRP); if(chmodStat<0){ perror("failed to chmod"); exit(-1); } free(encDataPtr); }
int suiteBMain( int argc, char **argv ) { const char *stringArg; BOOLEAN isServer, sendHTTPheader; int testNo, intArg, status; void testSystemSpecific1( void ); void testSystemSpecific2( void ); printf( "testlib - cryptlib %d-bit Suite B test framework.\n", ( int ) sizeof( long ) * 8 ); /* Cast for gcc */ puts( "Copyright Peter Gutmann 1995 - 2011." ); puts( "" ); /* Skip the program name and process any command-line arguments */ argv++; argc--; status = processArgs( argc, argv, &testNo, &stringArg, &intArg, &isServer, &sendHTTPheader ); if( !status ) exit( EXIT_FAILURE ); /* Make sure that various system-specific features are set right */ testSystemSpecific1(); /* Initialise cryptlib */ status = cryptInit(); if( cryptStatusError( status ) ) { printf( "\ncryptInit() failed with error code %d, line %d.\n", status, __LINE__ ); exit( EXIT_FAILURE ); } /* In order to avoid having to do a randomness poll for every test run, we bypass the randomness-handling by adding some junk. This is only enabled when cryptlib is built in debug mode so it won't work with any production systems */ cryptAddRandom( "xyzzy", 5 ); /* Perform a general sanity check to make sure that the self-test is being run the right way */ if( !checkFileAccess() ) exit( EXIT_FAILURE ); /* Make sure that further system-specific features that require cryptlib to be initialised to check are set right */ testSystemSpecific2(); /* If the test number is negative, it's a special-case non-test operation */ if( testNo < 0 ) { switch( testNo ) { case -1: status = generateKey( intArg, stringArg ); if( status == TRUE ) printf( "Wrote %d-bit certificate request to " "file '%s'.\n\n", intArg, stringArg ); break; case -2: status = updateKey( intArg, stringArg ); if( status == TRUE ) printf( "Updated %d-bit key with certificate from " "file '%s'.\n\n", intArg, stringArg ); break; } } else { /* Run the selected test */ status = suitebTest( isServer, testNo, stringArg, intArg, sendHTTPheader ); } /* Clean up and exit */ cryptEnd(); return( ( status == TRUE ) ? EXIT_SUCCESS : EXIT_FAILURE ); }