Data Integrity

Hey Guys,

I am new to c++ and am looking to get some help on an assignment. I've been looking at this code for hours and just haven't moved forward at all. Any help pointing me in the right direction is greatly appreciated. Here is my assignment:

A common way to ensure that binary data has not been tampered with or has not been corrupted by some event (transport, sending, etc.) is to test its “integrity”. This is done by running some hash or checksum algorithm on the binary data before the event and again after the event. If the results are not the same it can be concluded that the integrity of the data has been compromised (changed).

There are many checksum and hash algorithms that have been used over the years. They all generate some numeric value of fixed size based on examination of the binary data. For simplicity, we will not use a real checksum algorithm but instead just use a regular 32 bit sum. That is, we will add the ASCII values of each character of the input file.

You may wonder how characters such as ‘a’, ‘b’, ‘c’, etc. can be added. The key is remembering that computers cannot store letters but only numbers, and that the ASCII table maps every character into a number. The ASCII representations of all the characters are added together.

When that file is read, the same checksum is run over the same file data. If the resulting checksum is not the same as the previously computed checksum, the data has been compromised (changed).


Your assignment is to write a C++ program which will automatically compute the checksum on a specified data file, and then store that checksum in an unsigned integer array. The program must also store the file name in another, parallel array. You can use these declarations in your program:

const int SUM_ARR_SZ = 100;
unsigned int checkSums[SUM_ARR_SZ];
string fileNames[SUM_ARR_SZ];

This gives your program the flexibility to run checksums on several files (up to 100) and remember which sums go with which files.

Your program should then be able to verify that a specified file has not been compromised by running the checksum over it and verifying that the checksum is what it was previously.

Your program *must* read the file into a char array. Make the array size 100000 chars so that it is large enough for our file. After the file is stored in the array, your program must loop through the array to compute the checksum using the algorithm described above (simple sum).

Since this is essentially an operation on a binary file (even though text may be stored in the file), open the file in binary mode to prevent the system from performing any interpretation on the data like this:

inFile.open(filePath.c_str(), ios::binary);


To get the file size, use the seekg and tellg operators like this:

inFile.seekg(0, ios_base::end);
int fileLen = inFile.tellg();
inFile.seekg(0, ios_base::beg);


The first line moves the file cursor to the end of the file. The second line reads the byte position at that current location. The third statement moves the file cursor back to the beginning of the file so the data can be read from the beginning.

After that, you can read the entire file contents into your char array in one statement like this:

inFile.read(charArr, fileLen);

Then the file must be closed:

inFile.close();

The following line seems to be required to put the file back to a state where it can be opened again it (otherwise, some compilers, like mine, will not allow the file to be reopened):

inFile.clear(std::ios_base::goodbit);

For comparing file names, use the strcmp() built in function.

High level pseudocode for determining the checksum may look something like this:

1. Open the specified file in binary mode
2. Save the file name in the fileNames array.
3. Determine the file size using seekg and tellg
4. Read the file contents into the character array in one statement
5. Close the file
6. Loop through the array, one character at a time and accumulate the sum of each byte
7. Store the sum into the checkSums array.

Sample Dialog:
Note: In the example below, the user’s input is in RED BOLD. The program output is not. Also, your code should allow menu entry input in a case insensitive manner.

Please select:
A) Compute checksum of specified file
B) Verify integrity of specified file
Q) Quit
a
Specify the file path: c:\temp\tmp1
File checksum = 1530
Please select:
A) Compute checksum of specified file
B) Verify integrity of specified file
Q) Quit
a
Specify the file path: c:\temp\tmp2
File checksum = 29430
Please select:
A) Compute checksum of specified file
B) Verify integrity of specified file
Q) Quit
b
Specify the file path: c:\temp\tmp1
File checksum = 1530
The file integrity check has passed successfully (checksum = 1530).

Please select:
A) Compute checksum of specified file
B) Verify integrity of specified file
Q) Quit
b
Specify the file path: c:\temp\tmp1
File checksum = 1597
The file integrity check has failed (previous checksum = 1530, new checksum = 1597)

Please select:
A) Compute checksum of specified file
B) Verify integrity of specified file
Q) Quit
b
Specify the file path: c:\temp\tmp3
File checksum = 5596
The checksum has not been computed on the file: c:\temp\tmp3
Please select:
A) Compute checksum of specified file
B) Verify integrity of specified file
Q) Quit

I have uploaded a file for you to test with. I suggest you start with a very short file (3-4 characters) and step through your code to make sure it works correctly. Have fun!

Deliverables:

Please upload your program source code (.cpp file) as usual.

Notes:

Design your solution to use as many aspects of this class as possible. For example, your code *must* be modularized using multiple (more than 2) C++ functions. Your program should prompt the user to enter the file name of the input file, and should provide appropriate error handling as necessary.

And here is what I have so far. The I'm getting values like "Filechecksum = 0034F980". I have no idea what to do at this point.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>

using namespace std;

// Declare Variables
char reply;

string filePath;

void openFile();


int main()
{
	do
	{
		cout << "Please select: " << endl;
		cout << "A) Compute checksum of specified file " << endl;
		cout << "B) Verify integrity of specified file " << endl;
		cout << "Q) Quit " << endl;
		cin >> reply;

		switch (reply)
		{
		case'A':
		case'a':
			cout << "Specify the file path: " << endl;
			cin >> filePath;
			openFile();
			break;
		case'B':
		case'b':
			cout << "Specify the file path: " << endl;
			cin >> filePath;
			openFile();
			break;
		case'Q':
		case'q':
			break;
		default:
			cout << "Invalid Input." << endl;
			break;

		}
	} while (reply != 'Q' || reply != 'q');

	system("pause");
	return 0;

}

void openFile()
{

	const int SUM_ARR_SZ = 100;
	unsigned int checkSums[SUM_ARR_SZ];
	string fileNames[SUM_ARR_SZ];

	char charArr[100000];

	ifstream inFile;

	inFile.open(filePath.c_str(), ios::binary);
	inFile.seekg(0, ios_base::end);
	int fileLen = inFile.tellg();
	inFile.seekg(0, ios_base::beg);

	inFile.read(charArr, fileLen);

	cout << "File checksum = " << checkSums << endl;

	inFile.close();

	inFile.clear(std::ios_base::goodbit);

}
Here is the .txt file we are imputing. (Half because of the character limit.)
Name: DeclarationOfIndenendence.txt
of Independence of the Thirteen Colonies
In CONGRESS, July 4, 1776

The unanimous Declaration of the thirteen united States of America,

When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.

We hold these truths to be self-evident, that all men are created equal, that they are endowed by their Creator with certain unalienable Rights, that among these are Life, Liberty and the pursuit of Happiness. --That to secure these rights, Governments are instituted among Men, deriving their just powers from the consent of the governed, --That whenever any Form of Government becomes destructive of these ends, it is the Right of the People to alter or to abolish it, and to institute new Government, laying its foundation on such principles and organizing its powers in such form, as to them shall seem most likely to effect their Safety and Happiness. Prudence, indeed, will dictate that Governments long established should not be changed for light and transient causes; and accordingly all experience hath shewn, that mankind are more disposed to suffer, while evils are sufferable, than to right themselves by abolishing the forms to which they are accustomed. But when a long train of abuses and usurpations, pursuing invariably the same Object evinces a design to reduce them under absolute Despotism, it is their right, it is their duty, to throw off such Government, and to provide new Guards for their future security. Such has been the patient sufferance of these Colonies; and such is now the necessity which constrains them to alter their former Systems of Government. The history of the present King of Great Britain OGeorge IIIQ is a history of repeated injuries and usurpations, all having in direct object the establishment of an absolute Tyranny over these States. To prove this, let Facts be submitted to a candid world.

He has refused his Assent to Laws, the most wholesome and necessary for the public good.

He has forbidden his Governors to pass Laws of immediate and pressing importance, unless suspended in their operation till his Assent should be obtained; and when so suspended, he has utterly neglected to attend to them.

He has refused to pass other Laws for the accommodation of large districts of people, unless those people would relinquish the right of Representation in the Legislature, a right inestimable to them and formidable to tyrants only.

He has called together legislative bodies at places unusual, uncomfortable, and distant from the depository of their public Records, for the sole purpose of fatiguing them into compliance with his measures.

He has dissolved Representative Houses repeatedly, for opposing with manly firmness his invasions on the rights of the people.

He has refused for a long time, after such dissolutions, to cause others to be elected; whereby the Legislative powers, incapable of Annihilation, have returned to the People at large for their exercise; the State remaining in the mean time exposed to all the dangers of invasion from without, and convulsions within.

He has endeavoured to prevent the population of these States; for that purpose obstructing the Laws for Naturalization of Foreigners; refusing to pass others to encourage their migrations hither, and raising the conditions of new Appropriations of Lands.

He has obstructed the Administration of Justice, by refusing his Assent to Laws for establishing Judiciary powers.

He has made Judges dependent on his Will alone, for the tenure of their offices, and the amount and payment of their salaries.

He has erected a multitude of New Offices, and sent hither swarms of Officers to harass our people, and eat out their substance.

He has kept among us, in times of peace, Standing Armies without the consent of our legislatures.

He has affected to render the Military independent of and superior to the Civil power.

He has combined with others to subject us to a jurisdiction foreign to our constitution and unacknowledged by our laws; giving his Assent to their Acts of pretended Legislation:

For Quartering large bodies of armed troops among us:

For protecting them, by a mock Trial, from punishment for any Murders which they should commit on the Inhabitants of these States:

For cutting off our Trade with all parts of the world:

For imposing Taxes on us without our Consent:

For depriving us, in many cases, of the benefits of Trial by Jury:

For transporting us beyond Seas to be tried for pretended offences:

For abolishing the free System of English Laws in a neighbouring Province, establishing therein an Arbitrary government, and enlarging its Boundaries so as to render it at once an example and fit instrument for introducing the same absolute rule into these Colonies:

For taking away our Charters, abolishing our most valuable Laws, and altering fundamentally the Forms of our Governments:

For suspending our own Legislatures, and declaring themselves invested with power to legislate for us in all cases whatsoever.

He has abdicated Government here, by declaring us out of his Protection and waging War against us.

He has plundered our seas, ravaged our Coasts, burnt our towns, and destroyed the lives of our people.

He is at this time transporting large Armies of foreign Mercenaries to compleat the works of death, desolation and tyranny, already begun with circumstances of Cruelty and perfidy scarcely paralleled in the most barbarous ages, and totally unworthy the Head of a civilized nation.

He has constrained our fellow Citizens taken Captive on the high Seas to bear Arms against their Country, to become the executioners of their friends and Brethren, or to fall themselves by their Hands.

He has excited domestic insurrections amongst us, and has endeavoured to bring on the inhabitants of our frontiers, the merciless Indian Savages, whose known rule of warfare, is an undistinguished destruction of all ages, sexes and conditions.

In every stage of these Oppressions We have Petitioned for Redress in the most humble terms: Our repeated Petitions have been answered only by repeated injury. A Prince whose character is thus marked by every act which may define a Tyrant, is unfit to be the ruler of a free people.

Nor have We been wanting in attentions to our British brethren. We have warned them from time to time of attempts by their legislature to extend an unwarrantable jurisdiction over us. We have reminded them of the circumstances of our emigration and settlement here. We have appealed to their native justice and magnanimity, and we have conjured them by the ties of our common kindred to disavow these usurpations, which, would inevitably interrupt our connections and correspondence. They too have been deaf to the voice of justice and of consanguinity. We must, therefore, acquiesce in the necessity, which denounces our Separation, and hold them, as we hold the rest of mankind, Enemies in War, in Peace Friends.

Last edited on
We, therefore, the Representatives of the united States of America, in General Congress, Assembled, appealing to the Supreme Judge of the world for the rectitude of our intentions, do, in the Name, and by the Authority of the good People of these Colonies, solemnly publish and declare, That these United Colonies are, and of Right ought to be Free and Independent States; that they are Absolved from all Allegiance to the British Crown, and that all political connection between them and the State of Great Britain, is and ought to be totally dissolved; and that as Free and Independent States, they have full Power to levy War, conclude Peace, contract Alliances, establish Commerce, and to do all other Acts and Things which Independent States may of right do. And for the support of this Declaration, with a firm reliance on the protection of divine Providence, we mutually pledge to each other our Lives, our Fortunes and our sacred Honor.

The signers of the Declaration represented the new states as follows:

New Hampshire
Josiah Bartlett, William Whipple, Matthew Thornton

Massachusetts
John Hancock, Samual Adams, John Adams, Robert Treat Paine, Elbridge Gerry

Rhode Island
Stephen Hopkins, William Ellery

Connecticut
Roger Sherman, Samuel Huntington, William Williams, Oliver Wolcott

New York
William Floyd, Philip Livingston, Francis Lewis, Lewis Morris

New Jersey
Richard Stockton, John Witherspoon, Francis Hopkinson, John Hart, Abraham Clark

Pennsylvania
Robert Morris, Benjamin Rush, Benjamin Franklin, John Morton, George Clymer, James Smith, George Taylor, James Wilson, George Ross

Delaware
Caesar Rodney, George Read, Thomas McKean

Maryland
Samuel Chase, William Paca, Thomas Stone, Charles Carroll of Carrollton

Virginia
George Wythe, Richard Henry Lee, Thomas Jefferson, Benjamin Harrison, Thomas Nelson, Jr., Francis Lightfoot Lee, Carter Braxton

North Carolina
William Hooper, Joseph Hewes, John Penn

South Carolina
Edward Rutledge, Thomas Heyward, Jr., Thomas Lynch, Jr., Arthur Middleton

Georgia
Button Gwinnett, Lyman Hall, George Walton
Topic archived. No new replies allowed.