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

📄 104-125.html

📁 这个是密码学的经典著作
💻 HTML
📖 第 1 页 / 共 3 页
字号:
<html><head><TITLE>Learn Encryption Techniques with BASIC and C++:Keyword-Based Monoalphabetic Substitution</TITLE>
<!-- BEGIN HEADER --><META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW"><SCRIPT><!--function displayWindow(url, width, height) {        var Win = window.open(url,"displayWindow",'width=' + width +',height=' + height + ',resizable=1,scrollbars=yes');}//--></SCRIPT></HEAD><body bgcolor="ffffff" link="#006666" alink="#006666" vlink="#006666"><P>
<CENTER><B>Learn Encryption Techniques with BASIC and C++</B>
<FONT SIZE="-2">
<BR>
<I>(Publisher: Wordware Publishing, Inc.)</I>
<BR>
Author(s): Gil Held
<BR>
ISBN: 1556225989
<BR>
Publication Date: 10/01/98
</FONT></CENTER>
<P>


<!-- Empty Reference Subhead -->

<!--ISBN=1556225989//-->
<!--TITLE=Learn Encryption Techniques with BASIC and C++//-->
<!--AUTHOR=Gilbert Held//-->
<!--PUBLISHER=Wordware Publishing, Inc.//-->
<!--CHAPTER=3//-->
<!--PAGES=104-125//-->
<!--UNASSIGNED1//-->
<!--UNASSIGNED2//-->

<CENTER>
<TABLE BORDER>
<TR>
<TD><A HREF="100-104.html">Previous</A></TD>
<TD><A HREF="../ewtoc.html">Table of Contents</A></TD>
<TD><A HREF="125-128.html">Next</A></TD>
</TR>
</TABLE>
</CENTER>
<P><BR></P>
<H4 ALIGN="CENTER"><A NAME="Heading7"></A><FONT COLOR="#000077">The CIPHER5.BAS Program</FONT></H4>
<P>Listing 3.3 illustrates the statements contained in the main portion of CIPHER5.BAS as well as the subroutine INITIALIZE, which required a slight modification from its prior form. You should note that lines terminating with five asterisks (*) as a comment indicate lines that were added to the main program to facilitate an explanation of its operation. Those lines can be removed if you do not wish to burden a user who has no desire to understand the enciphering process with this extraneous information.
</P>
<P><B>Listing 3.3</B> The main portion of the program CIPHER5.BAS and the modified subroutine INITIALIZE.</P>
<!-- CODE //-->
<PRE>
REM PROGRAM CIPHER5.BAS
DIM PLAINTEXT$(26), CIPHERTEXT$(26), KEY$(26)
CLS
GOSUB INITIALIZE
   PRINT "CIPHER5.BAS PROGRAM enciphers text based upon the use of
               a keyword or keyword"
   PRINT "phrase and an alphabetic shift key using a monoalphabetic
               substitution process."
   PRINT
   INPUT "Enter keyword or keyword phrase in UPPERCASE: ", TEXT$
   PRINT "Plaintext based alphabet is : ";    '*****
   FOR I = 0 TO 25: PRINT PLAINTEXT$(I);: NEXT I  '*****
   GOSUB KEYWORD             'form keyword-based mixed alphabet
   PRINT "Keyword-based alphabet is     : "; X$  '*****
1  INPUT "Enter UPPERCASE Alphabetic Shift Key: ", K$
   FOR I = 0 TO 25
   IF K$ = PLAINTEXT$(I) GOTO 2
   NEXT I
   PRINT "You must enter a letter from A to Z"
   GOTO 1
2  REM Position I represents shift key letter

GOSUB FORMCIPHER       'create cipher alphabet
   PRINT "Shifted keyword mixed alphabet is  : ";   '*****
   FOR I = 0 TO 25: PRINT CIPHERTEXT$(I);: NEXT I: PRINT    '*****
GOSUB INITIALIZE       'reinitialize plaintext array
GOSUB MSGFILE          'assign I/O files, place message on a file
GOSUB CONVERTSTORE     'convert and store ciphertext on a file
GOSUB PRTOUT           'print results
STOP
INITIALIZE:
     RESTORE
     REM Initialize plaintext values
     FOR I = 0 TO 25
     READ PLAINTEXT$(I)
     NEXT I
     DATA "A","B","C","D","E","F","G","H","I","J","K","L","M","N"
     DATA "O","P","Q","R","S","T","U","V","W","X","Y","Z"
 RETURN
</PRE>
<!-- END CODE //-->
<P>As indicated in Listing 3.3, first initialize the string array PLAINTEXT$ and then display information about the program. After the keyword or keyword phrase is entered and assigned to the string  variable TEXT$, the plaintext alphabet is displayed. Next, the subroutine KEYWORD is invoked to form a keyword-based mixed alphabet. That subroutine is the same as the subroutine previously developed in the program WORD.BAS.
</P>
<P>After the subroutine KEYWORD is invoked, the keyword-based alphabet is displayed via the use of another optional statement. The user is then prompted to enter an alphabetic shift character, and the subroutine FORMCIPHER is invoked to create a cipher alphabet. That alphabet is displayed through the use of a pair of optional statements.</P>
<P>Because the subroutine FORMCIPHER creates the cipher alphabet by shifting the previously created keyword-based mixed alphabet, you must restore the plaintext alphabet to its original sequence to correctly convert plaintext characters to their equivalent ciphertext characters. This is accomplished by again invoking the subroutine INITIALIZE. However, because that subroutine previously read the normal letter sequence into the array PLAINTEXT, you must place a RESTORE statement at the beginning of the subroutine. Otherwise, you would receive an &#147;out-of-data&#148; error message.</P>
<H4 ALIGN="CENTER"><A NAME="Heading8"></A><FONT COLOR="#000077">The Encipherment Process</FONT></H4>
<P>Figure 3.2 illustrates the execution of CIPHER5.BAS to encipher a short but important message. To understand the encipherment process, examine the composition of the different alphabets displayed by the program.
</P>
<P><A NAME="Fig2"></A><A HREF="javascript:displayWindow('images/03-02.jpg',472,417 )"><IMG SRC="images/03-02t.jpg"></A>
<BR><A HREF="javascript:displayWindow('images/03-02.jpg',472,417)"><FONT COLOR="#000077"><B>Figure 3.2</B></FONT></A>&nbsp;&nbsp; A sample execution of CIPHER5.BAS</P>
<P>The plaintext based alphabet is simply the character sequence A through Z. After a keyword or keyword phrase is entered, the plaintext sequence is modified based upon the keyword or keyword phrase. For example, entering the keyword MICROSOFTWINDOWS results in the keyword-based alphabet MICROSFTWNDABEGHJKLPQUVXYZ because all duplicate characters in the keyword or keyword phrase are eliminated prior to the addition of the characters in the plaintext alphabet that are not in the modified keyword or keyword phrase. The entry of an alphabetic shift key causes the cycling of the keyword-based alphabet so that all characters to and including the alphabetic shift key character are rotated. Thus, the shifted keyword mixed alphabet becomes EGHJKLPQUVXYZMICROSFTWNDAB.
</P>
<P>The encipherment process requires each character in the message to be located in the array PLAINTEXT$, which contains the normal alphabetic sequence. When a match is found, the ciphertext character located in the same position in the shifted keyword mixed alphabet in the CIPHERTEXT$ array is extracted and substituted for the plaintext character. Note the positional relationship of characters between the plaintext based alphabet and the shifted keyword mixed alphabet in Figure 3.2. The first character in the message is B, located in the second position in the plaintext alphabet. The second character in the shifted keyword mixed alphabet is G. Hence, B was replaced by G. The second letter in the message is I, located in the ninth position in the plaintext alphabet. In the ninth position in the shifted keyword mixed alphabet, extract a U. Similarly, D is replaced by the character J and the first word in the plaintext message, BID, is enciphered as GUJ.</P>
<H4 ALIGN="CENTER"><A NAME="Heading9"></A><FONT COLOR="#000077">The CIPHER5.CPP Program</FONT></H4>
<P>The C&#43;&#43; version of the previously described CIPHER5.BAS program is appropriately named CIPHER5.CPP and is contained on the CD-ROM under the C directory. The executable version of this C&#43;&#43; program follows our naming convention and is named CIPHER5.EXE. To distinguish the BASIC executable version of CIPHER5 from the C&#43;&#43; version of that program, it is important to remember that those versions are located in the BASIC and C directories on the CD-ROM.
</P>
<P>Listing 3.4 lists the contents of the program CIPHER5.CPP. As you examine the program listing you will note that the C&#43;&#43; software author, Jonathan Held, replaced the #define statements with the use of integer constants to demonstrate another method you can use to create constants for a C&#43;&#43; program. Similar to other C&#43;&#43; program listings, the listing of CIPHER5.CPP includes a detailed description via embedded comments that indicates how the program operates. The only function that is completely new in Listing 3.4 is the welcome function whose statements are listed at the end of the program. Although the other functions in CIPHER5.CPP were developed for previously covered C&#43;&#43; programs, the entire program is given in Listing 3.4 to provide you with the manner by which functions interact with one another as well as to provide an example of the use of integer constants instead of magic numbers.</P>
<P><B>Listing 3.4</B> The CIPHER5.CPP program listing.</P>
<!-- CODE //-->
<PRE>
/*
cipher5.cpp
C&#43;&#43; Code written by Jonathan Held, February 28, 1998, using
Microsoft Visual C&#43;&#43;, version 5.0.  Please read file for
detailed description of how the program works.
*/

//standard include files
#include &lt;iostream.h&gt;      //standard i/o operations
#include &lt;string.h&gt;        //used to find the length of a string
#include &lt;ctype.h&gt;         //for character handling
#include &lt;fstream.h&gt;       //file stream processing
#include &lt;stdlib.h&gt;        //standard library functions
#include &lt;string.h&gt;        //string handling functions

//Constants - we don't want to use any magic numbers!
//Notice how now we aren't using #defines as we did before -
//Just another way to create constants for our program.
const int TWO=2, THREE = 3, FOUR = 4, FIVE = 5, TWENTYFIVE = 25,
      TWENTYSIX = 26, TWENTYSEVEN = 27, SIXTYFIVE = 65,
      NINETY = 90, NINETYTWO = 92, SIZE = 256, BIGSIZE = 1000;


//function prototypes - see function headers for more information
void welcome(void);              //only function that is
                                 //new to this file

void getFileNames(char* &#38;, char* &#38;);   //all other functions have
int getInputType(void);                //been used in previous programs

//keyword or keyword phrase functions:
void getKeyword(char * &#38;);
bool checkInput(char * &#38;);
void createAlphabet(char *, char []);
bool getMessage(char*, char*, char [], const char[], const char[]);

//monoalphabetic substitution functions:
void getShiftKey(char &#38;);
void shiftKeyword(char [], char); //shiftKeyword modified for this
                                  //program - see function for details

//other functions:
char* formCipheredMessage(const char[], const char [], char []);
void printResults(const char[], const char[], const char[], const char [],
                    const int);
void printCipherToFile(ofstream, char[]);
void formatData(char []);
void groupBUFFER(ofstream, int);
bool encryptText(char *, char *, const char [], const char[], char []);
void display(char *);

char BUFFER[BIGSIZE] = &#123;'\0'&#125;;


//------------------------------------------------
//Function: main()
//Parameters: None
//Return Type: int - 0 execution is normal, 1 abnormal termination
//Purpose: Runs the main part of the program.
//------------------------------------------------
int main()&#123;

  //initialize plaintext
  char plaintext[TWENTYSEVEN] = &#123;'A','B','C','D','E','F','G','H','I',
                      'J','K','L','M','N','O','P','Q','R',
                      'S','T','U', 'V','W','X','Y','Z', '\0'&#125;;

  //other variables we will use
  char ciphertext[TWENTYSEVEN]= &#123;'\0'&#125;;
  char message_to_cipher[SIZE], key;
  char *infile, *outfile, *keyword;
  int input_type;
  bool success = false;

  welcome();
  getKeyword(keyword);
  createAlphabet(keyword, ciphertext);
  cout &lt;&lt; "\nPlaintext-based alphabet is: " &lt;&lt; plaintext &lt;&lt; endl
     &lt;&lt; "Keyword-based alphabet is:   " &lt;&lt; ciphertext &lt;&lt; endl &lt;&lt; endl;
  getShiftKey(key);
  shiftKeyword(ciphertext, key);
  cout &lt;&lt; "Shifted keyword mixed alphabet is: " &lt;&lt; endl &lt;&lt; ciphertext
                  &lt;&lt; endl &lt;&lt; endl;
  getFileNames(infile, outfile);
  input_type = getInputType();
  //check for manual entry of data
  if (!(input_type))&#123;
     success = getMessage(infile, outfile, message_to_cipher, plaintext,
                  ciphertext);
  &#125;
  //user wants to encipher a file
  else &#123;
    success = encryptText(infile, outfile, plaintext, ciphertext,
                  message_to_cipher);
  &#125;

  //display the output file only if we were successful
  if (success)&#123;
     cout &lt;&lt; "Press return to display resulting enciphered message."
                   &lt;&lt; endl;
     //get the newlines off the current input stream
     cin.get();
     cin.get();
     display(outfile);
  &#125;
  else &#123;
    cerr &lt;&lt; "Error executing program!" &lt;&lt; endl;
  &#125;

  //delete all dynamically allocated memory
  delete [] keyword;
  delete [] infile;
  delete [] outfile;

  return (static_cast&lt;int&gt;(!(success)));

&#125;//end main()


//------------------------------------------------
//Function: checkInput()
//Parameters: input - the keyword the user entered
//Return Type: bool - true if the input string contains an error,
//        false otherwise
//Purpose: Checks the user's keyword for invalid characters.
//------------------------------------------------
bool checkInput(char * &#38;input)
&#123;
  bool error = false;
  int count = strlen(input);

  for (int ix=0; ix&lt;count; ix&#43;&#43;)&#123;

    int char_value = static_cast&lt;int&gt;(*(input&#43;ix));

    //determine if the user did not enter an uppercase character
    if ((char_value &lt; SIXTYFIVE) || (char_value &gt; NINETY))&#123;
       error = true;
       cerr &lt;&lt; "You entered an invalid keyword!" &lt;&lt; endl &lt;&lt; endl;
       break;
     &#125;
  &#125;

  return error;
&#125;//end checkInput()


//-------------------------------------------------
//Function: createAlphabet()
//Parameters: input - the keyword the user entered
//      cipher - the keyword alphabet that will be constructed
//Return Type: None
//Purpose: Creates the keyword alphabet.
//-------------------------------------------------
void createAlphabet(char *input, char cipher[])
&#123;
  bool used[TWENTYSIX];
  int index = 0,
      count = strlen(input);

  //no characters are initially used
  for (int ix=0; ix&lt;TWENTYSIX; ix&#43;&#43;)&#123;
    used[ix] = false;
  &#125;

⌨️ 快捷键说明

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