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

📄 makekeys.cpp

📁 伯克利做的SFTP安全文件传输协议
💻 CPP
字号:
//  $Archive:: /STP/MakeKeys/makekeys.cpp                             $//     $Date: 1999/11/13 08:31:20 $// $Revision: 1.17 $// Description: Makekeys main// copyright SafeTP Development Group, Inc., 2000  Terms of use are as specified in license.txt#ifdef SAFETPC#include "platform.h" // Platform#include "warnhand.h" // client warning handler#endif#include <stdio.h>       // printf#include <stdlib.h>      // abort#include <string.h>      // strrchr#include "selgamal.h"    // ElGamal*#include "sdsa.h"        // DSA*#include "cryputil.h"    // various utilities#include "syserr.h"      // xSysError::xsyserror#include "globrand.h"    // global random pool#include "addent.h"      // getEntropyFromConsole#include "keyutils.h"    // saveKey#include "nonport.h"     // getMilliseconds#include "weakkey.h"     // SetKeyStrength#include "sftpver.h"     // SFTP_version#include "usercfg.h"     // userConfigDir// key save/load that checks result and stops program on error//-----------------------------------------static void saveKey(char const *path, DataBlock &block, bool forceProtArea=false){  string temp(path);  if (!SaveKey(temp, block, forceProtArea)) {    printf("failed to write key to %s\n", path);    exit(2);  }}//-----------------------------------------static void loadKey(char const *path, DataBlock &block, bool forceProtArea=false){  string temp(path);  if (!LoadKey(temp, block, forceProtArea)) {    printf("failed to read key from %s\n", path);    exit(2);  }}//-----------------------------------------//-----------------------------------------bool GenerateElgamalKey(char const * const * elgamalParams, int elgamalLen, bool forceProtected=false) {  unsigned long A = getMilliseconds();  // create  printf("creating ElGamal keys with %d bits...\n", elgamalLen);  ElGamalParameters params(elgamalParams);  GlobalRandomPool grp;  ElGamalPrivateKey elg(params, grp.pool());  // save  {    DataBlock prvkey;    elg.encode(prvkey);    saveKey("ElGamal/private.key", prvkey, forceProtected);    DataBlock pubkey;    elg.ElGamalPublicKey::encode(pubkey);    saveKey("ElGamal/public.key", pubkey, forceProtected);    SetKeyStrength(KS_STRONG, "ElGamal/", forceProtected);    SetKeyTimeStamp("ElGamal/", forceProtected);    }  printf("Time used to create ElGamal key: %10.4f sec\n",         ((float)(getMilliseconds()-A))/1000.0);  // load  printf("Verifying ElGamal keys\n");  DataBlock pubKey;  loadKey("ElGamal/public.key", pubKey, forceProtected);  DataBlock privKey;  loadKey("ElGamal/private.key", privKey, forceProtected);  // test that encrypting and decrypting yields original data  DataBlock plaintext("This is some plaintext");  // encrypt  DataBlock ciphertext =    elGamalEncrypt(pubKey, plaintext);  // decrypt  DataBlock decrypted =    elGamalDecrypt(privKey, ciphertext);  // compare  if (plaintext != decrypted) {    printf("Private key failed to decrypt message encrypted \n"           "with public key.. that's bad.\n\n");    return false;    }  else {    printf("Verified.\n\n");    #ifdef __UNIX__    // our client key management on unix still leaves a lot to    // be desired, but by at least saying where the heck they    // are going it might save some grief    printf("Your keys have been saved to %s\n\n", userConfigDir().pcharc());    #endif    return true;    }  }//-----------------------------------------#ifdef MAKEKEYS_MAIN       // SM: so I can link a version of this with sftpcint main(int argc, char *argv[]){  #ifdef SAFETPC    setupWarningHandler(); // make sure we don't scribble warnings to random places on disk  #endif  // setup nonport error handling  nonportFail = xSysError::xsyserror;  if (argc < 3 || argc > 4) {    char const *argvzero = argv[0];    // remove all before last backslash    char const *p = strrchr(argvzero, '\\');    if (p && p > argvzero) {      argvzero = p+1;      }    // remove all before last slash    p = strrchr(argvzero, '/');    if (p && p > argvzero) {      argvzero = p+1;      }    printf("makekeys version %s\n"           "usage:\n"           "  %s ElGamal-key-length DSA-key-length [no-entropy]\n"	   "  ElGamal lengths:\n"           "          (performance numbers for x86 233 MHz)\n"           "       0  don't generate (use this for server)\n"           "     512  .3 sec to encrypt, breakable\n"	   "    1024  1.7 sec to encrypt, reasonably secure (recommended)\n"           "    1536  7.2 secs to encrypt, very secure\n"	   "    2048  10.5 secs to encrypt, unbreakable\n"	   "  DSA lengths:\n"           "       0  don't generate (use this for client)\n"	   "    %4d  minimum length, breakable\n"	   "    %4d  maximum length, very secure (recommended)\n"           "  (security estimates assume brute force is fastest attack)\n"           "\n"	   "  no-entropy: Any 3rd param disables entropy-gathering.\n",	   SFTP_version, argvzero,	   MIN_DSA_PRIME_LENGTH, MAX_DSA_PRIME_LENGTH);    return 0;    }  int gatherEntropy = argc < 4;  int elgamalLen = atoi(argv[1]);  int dsaLen = atoi(argv[2]);  char const * const *elgamalParams;  char const * const *dsaParams;  switch (elgamalLen) {    case  512: elgamalParams = ElGamal_512bit_parameters; break;    case 1024: elgamalParams = ElGamal_1024bit_parameters; break;    case 1536: elgamalParams = ElGamal_1536bit_parameters; break;    case 2048: elgamalParams = ElGamal_2048bit_parameters; break;    case    0: elgamalParams = NULL; break;   // no keygen    default:      printf("ElGamal key size must be 512, 1024, 1536, or 2048.\n");      return 1;    }  switch (dsaLen) {    case  512: dsaParams = DSA_512bit_parameters; break;    case 1024: dsaParams = DSA_1024bit_parameters; break;    case    0: dsaParams = NULL; break;   // no keygen    default:      printf("DSA key size must be 512 or 1024.\n");      return 1;    }  // get name for key branding  string serverName;  if (dsaLen > 0) {    DataBlock test;                string temp("DSA/public.key");    if (LoadKey(temp, test, true)) { // warn about re-creating DSA keys      printf("This machine appears to already have a DSA key pair.\n"             "This key is used solely for server operations, and it's HIGHLY recommended that\n"             "it ONLY be updated if you believe the DSA private key has been compromised.\n"             "After updating this key, any users who've previously logged into this machine\n"             "using SafeTP will now get a security warning the next time they log in, \n"             "informing them the DSA key has changed. There is no way to undo this operation. \n"             "\nAre you ABSOLUTELY SURE you want to continue and replace the DSA keys? (yes/no)\n"             );      char temp[50];      fgets(temp, 50, stdin);                // caved and fixed      if (0!=strncmp(temp, "yes", 3)) {      // strncmp since fgets leaves the '\n' at the end        printf("Canceling operation. Bailing out...\n");        exit(1);        }      }    printf("Part of SafeTP's countermeasures against interception attacks\n"           "is the use of \"branded\" DSA keys-- that is, keys that include\n"           "a string that identifies the server who owns that key.  This\n"           "string is attached to the public key, and the pair is signed with\n"           "the private key.  Users will see this string when they first\n"           "connect to your server.\n"           "\n"           "The string should include a domain name that users are likely\n"           "to use when connecting to your server.  It can contain additional\n"           "information as well.  (A creation date will be automatically\n"           "appended.)\n"           "\n"           "For example: \"UCB CS FTP server, ftp.cs.berkeley.edu\"\n"           "\n"           "Enter an identifying string (80 chars maximum):\n");    char buf[81];  // this maximum (80 chars) is local to this section of code    fgets(buf, 80, stdin);     	       // caved and fixed    buf[strlen(buf)-1] = 0;            // kill final newline    // retrieve date    int m, d, y;    getCurrentDate(m, d, y);    // construct server string    serverName = stringb(buf << " [" << m << "/" << d << "/" << y << "]");    }  bool makeweakkey = false;  if (argc == 4 && !strcmp(argv[3],"/checkseed")) {    // we're being run on windows startup to check for seed    DataBlock junk;    	  string temp;	  temp = "randomSeed";    // some g++ screwing	  int haveRandSeed = LoadKey(temp, junk);	  temp = "ElGamal/private.key";	  int haveElgPrv = LoadKey(temp, junk);	  temp = "ElGamal/public.key";	  int haveElgPub = LoadKey(temp, junk);    if (haveRandSeed && haveElgPrv && haveElgPub && GetKeyStrength() == KS_STRONG)           exit(0);  // user has all necessary stuff - no need to generate keys        gatherEntropy = true;    makeweakkey = true;     printf("This machine is equipped with SafeTP FTP Security Software.\n");    printf("All users must generate their SafeTP security key pair.\n");    }    readRandomSeed(false /*complain*/);  if (makeweakkey) { // we make a weak key to start with, in case they cancel entropy gathering    int retval = GenerateWeakKey(elgamalParams,"ElGamal/");    if (!retval) printf("Failed to generate preliminary key\n");    }  if (gatherEntropy) {    printf("\nSafeTP will now generate your new security keys. In order to make your keys\n"           "truly secure, you must provide us with some random input on the keyboard. \n"           "SafeTP will measure the time intervals between your keypresses and use this \n"           "to add entropy to the key generation procedure.\n");    getEntropyFromConsole(elgamalLen+dsaLen);    }  if (elgamalLen > 0) GenerateElgamalKey(elgamalParams, elgamalLen);  if (dsaLen > 0) {    unsigned long B = getMilliseconds();    // create DSA keys    printf("creating DSA keys with %d bits...\n", dsaLen);    DSAParameters params(dsaParams);       GlobalRandomPool grp;    DSAPrivateKey dsa(dsaParams, grp.pool());    // write private key (to protected region)    {      DataBlock prvkey;                  dsa.encode(prvkey);      saveKey("DSA/private.key", prvkey, true);             }    // write branded public key (to protected region)    {      DSASigner signer(dsa, grp.pool());      DSABrandedPublicKey branded(signer, serverName);      DataBlock pubkey = branded.encode();   // interface bug.. whatever      saveKey("DSA/public.key", pubkey, true);      }    printf("Time used to create DSA key: %10.4f sec\n",           ((float)(getMilliseconds()-B))/1000.0);    // load    printf("Verifying DSA keys\n");    DataBlock brandedPubKey;    loadKey("DSA/public.key", brandedPubKey, true);    DataBlock privKey;    loadKey("DSA/private.key", privKey, true);    // de-brand    DataBlock pubKey;    {      DSABrandedPublicKey branded(brandedPubKey);      printf("server name: %s\n", (char const*)serverName);      branded.DSAPublicKey::encode(pubKey);      }    DataBlock plaintext("This is some plaintext");   // sign    DataBlock block(plaintext);    dsaSign(privKey, block);    // verify    try {      dsaVerify(pubKey, block, "dummy message");      printf("Verified.\n\n");      }    catch (...) {      printf("Signature check failed.. that's bad.\n\n");      exit(1);      }    #ifdef SAFETPC  // only makes sense on windows      if (Platform::isNT()) {         Registry::ProtectKey(HKEY_LOCAL_MACHINE, "Protected/", PROT_NO_ACCESS); // hide this dir from everyone        }      /*      if (Platform::isNT()) {	      printf("Generating a strong Elgamal key for the SYSTEM user while we're at it...\n");	      GenerateElgamalKey(ElGamal_1024bit_parameters, 1024, true);        }        */    #endif    }  // save random number  saveRandomSeed();  return 0;  }#endif // MAKEKEYS_MAIN

⌨️ 快捷键说明

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