You are given a plaintext and a ciphertext, and you know that aes-128-cbc is used to generate the ciphertext from the plaintext, and you also know that the numbers in the IV are all zeros (not the...

1 answer below »
You are given a plaintext and a ciphertext, and you know that aes-128-cbc is used to generate the ciphertext from the plaintext, and you also know that the numbers in the IV are all zeros (not the ASCII character ‘0’). Another clue that you have learned is that the key used to encrypt this plaintext is an English word shorter than 16 characters; the word that can be found from a typical English dictionary. Since the word has less than 16 characters (i.e. 128 bits), space characters (hexadecimal value 0x20) are appended to the end of the word to form a key of 128 bits. Your goal is to write a program to find out this key. English word list is also provided along with the program structure in the Project-1.zip file. The plaintext and ciphertext is the following


41900 – Fundamentals of Security Project Part-2 (Week 9 – Week 12) Finding secret key used in encryption, where plaintext, ciphertext and IV are given OpenSSL provides an API called EVP, which is a high-level interface to cryptographic functions. Although OpenSSL also has direct interfaces for each individual encryption algorithm, the EVP library provides a common interface for various encryption algorithms. To ask EVP to use a specific algorithm, we simply need to pass our choice to the EVP interface. A sample code is given in http://www.openssl.org/docs/crypto/EVP_EncryptInit.html. Please get yourself familiar with this program, and then complete this project. You are given a plaintext and a ciphertext, and you know that aes-128-cbc is used to generate the ciphertext from the plaintext, and you also know that the numbers in the IV are all zeros (not the ASCII character ‘0’). Another clue that you have learned is that the key used to encrypt this plaintext is an English word shorter than 16 characters; the word that can be found from a typical English dictionary. Since the word has less than 16 characters (i.e. 128 bits), space characters (hexadecimal value 0x20) are appended to the end of the word to form a key of 128 bits. Your goal is to write a program to find out this key. English word list is also provided along with the program structure in the Project-1.zip file. The plaintext and ciphertext is the following: Plaintext (total 21 characters): “This is a top secret” Ciphertext (in hex format): “2075386b75eed8b4f2b4a9c9b76967d057b4a441d349c15dd4b8bf4b87445a9e” Expected Result: If the C program has been completed correctly, you should be able to locate the word used as the key to encrypt the plain text. The program must: 1. Scan through the entire words.txt file until a match is found. 2. Use each word to encrypt the plaintext. 3. Compare the encrypted text with the ciphertext bit by bit. 4. Find a match, based on which find the word used. 5. Display the found word, its ciphertext next to the ciphertext being searched for. 6. The length of the ciphertext. Submission Deadline: 14th October - 10am (Any Submissions received after the deadline will be subjected to penalties) http://www.openssl.org/docs/crypto/EVP_EncryptInit.html http://www.openssl.org/docs/crypto/EVP_EncryptInit.html 41900 – Fundamentals of Security Project Part-2 (Week 9 – Week 12) Important Notes: Note 1: Download the Project-Part-2.zip file directly to the SecFun VM image to avoid any potential format changes in the document. Note 2: If you choose to store the contents of words.txt in a separate file and feed the file to your program, you need to check whether any additional formatting is required. Some editors may add a special character to the end of the file. If that happens, you can use a hex editor tool to remove them. Note 3: In this project, you are required to complete the given program and invoke the crypto library. No credit will be given if you simply use the OpenSSL commands to do this project. Note 4: To compile your code, follow the comments provided in the Skeleton code. You are required to edit/complete the areas with comments marked within ‘ /* ’ and ‘ */ ’. Note 5: Information regarding the program file will be discussed during the tutorial session by your respective Tutors. Any questions regarding the assignment can be discussed during the tutorial session or emailed to the tutor (with the Subject Coordinator CC’d). Instructions for compiling and running the program: To Compile use: ➢ gcc -o enc encrypt.c -std=c99 -lcrypto -ldl To run the compile code use: ➢ ./enc Marking Criteria (Total Weightage 20%): Criteria Incomplete Work Partial Work Full Work Program Completeness 0 Points 3 Points 5 Points Program Submitted without any changes Program Modified, but missing certain components Program contains all essential components. Program Functioning 0 Points 3 Points 5 Points Program does not compile / run Program calculates ciphertext but can’t find a match Program calculates ciphertext and finds a match Demo and Questionnaire 0 Points 5 Points 10 Points Unable to answer questions. Able to partially answer the questions. Able to answer all questions. 10th 1st 2nd 3rd 4th 5th 6th 7th 8th 9th a AAA AAAS Aarhus Aaron AAU ABA Ababa aback abacus abalone abandon abase abash abate abater abbas abbe abbey abbot Abbott abbreviate abc abdicate abdomen abdominal abduct Abe abed Abel Abelian Abelson Aberdeen Abernathy aberrant aberrate abet abetted abetting abeyance abeyant abhorred abhorrent abide Abidjan Abigail abject ablate ablaze able ablution Abner abnormal Abo aboard abode abolish abolition abominable abominate aboriginal aborigine aborning abort abound about above aboveboard aboveground abovementioned abrade Abraham Abram Abramson abrasion abrasive abreact abreast abridge abridgment abroad abrogate abrupt abscess abscissa abscissae absence absent absentee absenteeism absentia absentminded absinthe absolute absolution absolve absorb absorbent absorption absorptive abstain abstention abstinent abstract abstracter abstractor abstruse absurd abuilding abundant abusable abuse abusive abut abutted abutting abysmal abyss Abyssinia AC academe academia academic academician academy Acadia acanthus Acapulco accede accelerate accelerometer accent accentual accentuate accept acceptant acceptor access accessible accession accessory accident accidental accipiter acclaim acclamation acclimate accolade accommodate accompaniment accompanist accompany accomplice accomplish accord accordant accordion accost account accountant Accra accredit accreditate accreditation accretion accrual accrue acculturate accumulate accuracy accurate accusation accusative accusatory accuse accustom ace acerbic acerbity acetate acetic acetone acetylene ache achieve Achilles aching achromatic acid acidic acidulous Ackerman Ackley acknowledge acknowledgeable ACM acme acolyte acorn acoustic acquaint acquaintance acquiesce acquiescent acquire acquisition acquisitive acquit acquittal acquitting acre acreage acrid acrimonious acrimony acrobacy acrobat acrobatic acronym acropolis across acrylate acrylic ACS act Actaeon actinic actinide actinium actinolite actinometer activate activation activism Acton actor actress Acts actual actuarial actuate acuity acumen acute acyclic ad Ada adage adagio Adair Adam adamant Adams Adamson adapt adaptation adaptive add added addend addenda addendum addict Addis Addison addition additional additive addle address addressee Addressograph adduce Adelaide Adele Adelia Aden adenine adenoma adenosine adept adequacy adequate adhere adherent adhesion adhesive adiabatic adieu adipic Adirondack adjacent adject adjectival adjective adjoin adjoint adjourn adjudge adjudicate adjunct adjust adjutant Adkins Adler administer administrable administrate administratrix admiral admiralty admiration admire admissible admission admit admittance admitted admitting admix admixture admonish admonition ado adobe adolescent Adolph Adolphus Adonis adopt adoption adoptive adore adorn adposition adrenal adrenaline Adrian Adriatic Adrienne adrift adroit adsorb adsorbate adsorption adsorptive adulate adult adulterate adulterous adultery adulthood advance advantage advantageous advent adventitious adventure adventurous adverb adverbial adversary adverse advert advertise advice advisable advise advisee advisor advisory advocacy advocate Aegean aegis Aeneas Aeneid aeolian Aeolus aerate aerial Aerobacter aerobic aerodynamic aerogene aeronautic aerosol aerospace Aeschylus aesthete aesthetic afar affable affair affect affectate affectation affectionate afferent affiance affidavit affiliate affine affinity affirm affirmation affirmative affix afflict affluence affluent afford afforest afforestation affricate affront Afghan Afghanistan aficionado afield afire aflame afloat afoot aforementioned aforesaid aforethought afoul afraid afresh Africa afro aft aftereffect afterglow afterimage afterlife aftermath afternoon afterthought afterward afterword again against Agamemnon agate Agatha agave age Agee agenda agent agglomerate agglutinate agglutinin aggravate aggregate aggression aggressive aggressor aggrieve aghast agile aging agitate agleam Agnes Agnew agnomen agnostic ago agone agony agouti agrarian agree agreeable agreed agreeing agribusiness Agricola agricultural agriculture agrimony ague Agway ah ahead ahem Ahmadabad Ahmedabad ahoy aid Aida aide Aides Aiken ail ailanthus aile Aileen aileron aim ain't Ainu air airborne aircraft airdrop airedale Aires airfare airfield airflow airfoil airframe airlift airline airlock airmail airman airmass airmen airpark airplane airport airspace airspeed airstrip airtight airway airy aisle Aitken ajar Ajax AK Akers akin Akron AL ala Alabama Alabamian alabaster alacrity alai Alameda Alamo Alan alan alarm Alaska alb alba albacore Albania Albanian Albany albatross albeit Alberich Albert Alberta Alberto Albrecht Albright album albumin Albuquerque Alcestis alchemy Alcmena Alcoa alcohol alcoholic alcoholism Alcott alcove Aldebaran aldehyde Alden alder alderman aldermen Aldrich aldrin ale Alec Aleck aleph alert alewife Alex Alexander Alexandra Alexandre Alexandria Alexei Alexis alfalfa Alfonso alfonso Alfred Alfredo alfresco alga algae algaecide algal algebra algebraic Algenib Alger Algeria Algerian Algiers alginate Algol Algonquin algorithm algorithmic Alhambra Ali alia alias alibi Alice Alicia alien alienate alight align alike alimony aliphatic aliquot Alison Alistair alive alizarin alkali alkaline alkaloid alkane alkene all Allah Allan allay allegate allegation allege Allegheny allegiant allegoric allegory Allegra allegro allele allemand Allen Allentown allergic allergy alleviate alley alleyway alliance allied alligator Allis Allison alliterate allocable allocate allot allotropic allotted allotting allow allowance alloy allspice Allstate allude allure allusion allusive alluvial alluvium ally allyl Allyn alma Almaden almagest almanac almighty almond almost aloe aloft aloha alone along alongside aloof aloud alp alpenstock Alpert alpha alphabet alphabetic alphameric alphanumeric Alpheratz Alphonse alpine Alps already Alsatian also Alsop Altair altar alter alterate alteration altercate alterman altern alternate althea although altimeter altitude alto altogether Alton altruism altruist alum alumina aluminate alumna alumnae alumni alumnus alundum Alva Alvarez alveolar alveoli alveolus Alvin alway always alyssum A&M am AMA Amadeus amalgam amalgamate amanita amanuensis amaranth Amarillo amass amateur amateurish amatory amaze Amazon ambassador amber ambiance ambidextrous ambient ambiguity ambiguous ambition ambitious ambivalent amble ambling ambrose ambrosia ambrosial ambulant ambulate ambulatory ambuscade ambush Amelia ameliorate amen amend amende Amerada America American Americana Americanism americium Ames Ameslan amethyst amethystine Amherst ami amicable amid amide amidst amigo amino aminobenzoic amiss amity Amman Ammerman ammeter ammo ammonia ammoniac ammonium ammunition amnesia Amoco amoeba amoebae amok among amongst amoral amorous amorphous amort Amos amount amp amperage ampere ampersand Ampex amphetamine amphibian amphibious amphibole amphibology amphioxis ample amplifier amplify amplitude amply amputate amputee amra Amsterdam Amtrak amulet amuse Amy amy amygdaloid an ana Anabaptist Anabel anachronism anachronistic anaconda anaerobic anaglyph anagram Anaheim analeptic analgesic analogous analogue analogy analyses analysis analyst analytic anamorphic anaplasmosis anarch anarchic anarchy Anastasia anastigmat anastigmatic anastomosis anastomotic anathema Anatole anatomic anatomy ancestor ancestral ancestry anchor anchorage anchorite anchoritism anchovy ancient ancillary and Andean Andersen Anderson Andes andesine andesite andiron Andorra Andover Andre Andrea Andrei Andrew Andrews Andromache Andromeda Andy anecdotal anecdote anemone anent anew angel Angela Angeles angelfish angelic Angelica Angelina Angeline Angelo anger Angie angiosperm angle Angles Anglican Anglicanism angling Anglo Anglophobia Angola Angora angry angst angstrom anguish angular Angus anharmonic Anheuser anhydride anhydrite anhydrous ani aniline animadversion animadvert animal animate animism animosity anion anionic anise aniseikonic anisotropic anisotropy Anita Ankara ankle Ann Anna annal Annale Annalen annals Annapolis Anne anneal Annette annex Annie annihilate anniversary annotate announce annoy annoyance annual annuity annul annular annuli annulled annulling annulus annum annunciate anode anodic anomalous anomaly anomie anonymity anonymous anorexia anorthic anorthite anorthosite another Anselm Anselmo ANSI answer ant antacid Antaeus antagonism antagonist antagonistic antarctic Antarctica Antares ante anteater antebellum antecedent antedate antelope antenna antennae anterior anteroom anthem anther anthology Anthony anthracite anthracnose anthropogenic anthropology anthropomorphic anthropomorphism anti antic anticipate anticipatory Antietam antigen Antigone antigorite antimony Antioch antipasto antipathy antiperspirant antiphonal antipode antipodean antipodes antiquarian antiquary antiquated antique antiquity antisemite antisemitic antisemitism antithetic antler Antoine Antoinette Anton Antonio Antony antonym Antwerp anus anvil anxiety anxious any anybody anybody'd anyhow anyone anyplace anything anyway anywhere aorta A&P apace apache apart apartheid apathetic apathy apatite ape aperiodic aperture apex aphasia aphasic aphelion aphid aphorism Aphrodite apices apiece aplomb apocalypse apocalyptic Apocrypha apocryphal apogee Apollo Apollonian apologetic apologia apology apostate apostle apostolic apostrophe apothecary apothegm apotheosis Appalachia appall appanage apparatus
Answered Same DayOct 08, 2021

Answer To: You are given a plaintext and a ciphertext, and you know that aes-128-cbc is used to generate the...

Shanaya answered on Oct 10 2021
142 Votes
New folder/encrypt.c
#include
#include
#include
#include "openssl/evp.h"
#define MAX_LENGTH 16 // A global variable t define max-length
int main(int argc, char* argv[])
{
    if (argc != 3 || strlen(argv[1]) != (MAX_LENGTH*4))
    {
        printf("\nUsage : %s HexaCipherSTring(Must be of %d length) WordFile\n", argv[0], (MAX_LENGTH*4));
        printf("\nUsage : %s 3EE6E497181171BD6980B51DB1043B71D93B2094518854BB70ADE3AC90DA68EC words-tnx5glxp.txt\n", argv[0]);
        return 0;
    }
    char *cipherTxt = argv[1];
    unsigned char cipherHexaTxt[
MAX_LENGTH * 4];
    /* This variable is used to store the ciphertext provided to you. Make sure to use the proper format, eg. the hex 'd23a' would be written as {0xd2,0x3a} in C */
    unsigned char ciphertxt[] = { 0x7a, 0x6f, 0x6d, 0x62, 0x69, 0x65 }; // zombie
    // This is the plaintext that we are encrypting. Do not change it as it may result in a different ciphertext
    unsigned char plaintext[] = "This is a top secret";
    // Pointer fp used to point to the English words file provided along.
    FILE *fp;
    // The initialization Vector is set to 0
    unsigned char iv[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    // Output buffer set to 1024 size
    unsigned char outbuf[1024];
    // Some other variables that are used in the program
    int outlen = 0, tmplen = 0;
    /* You may want to declare some additional variables to be used as flags*/
    EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
    bool isMatched;
    int lenOfCipherText;
    if (/* Use this statement to check is the words.txt file can be opened in 'r' permission */ !(fp = fopen(argv[2], "r")))
    {
        printf("\n Error : Unable to open sample word file\n");
        /* Print a statement if the above condition is not met */
        return 0;
    }
    char key[MAX_LENGTH]; //array to store the key getting from the dictionary
    while (fgets(key, MAX_LENGTH, fp) != NULL)
    {
        for (int i = 0; i < MAX_LENGTH; i++)
        {
            if (key[i] == '\n' || key[i] == 0) //when key is less than 16 characters, the extra left part is filled with " "
            {
                for (int j = i; j < strlen(key); j++)
                {
                    key[j] = ' ';
                }
                break;
            }
        }
        // Use the EVP library to initialize cipher
        EVP_CIPHER_CTX_init(ctx);
        // Use the EVP library to encrypt the cipher
        EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, (unsigned char*)key, iv);
        // Checking to see if EVP_EncryptUpdate is valid or not
        if (!EVP_EncryptUpdate(ctx, outbuf, &outlen, plaintext, strlen((char*)plaintext)))
        {
            printf("\nError : invalid encryption\n");
            /*Print Out a relevant Error Messege*/
            return 0;
        }
        // Buffer passed to EVP_EncryptFinal() must be after data just encrypted to avoid overwriting it
        // Checking to see if !EVP_EncryptFinal_ex is valid or not
        if (!EVP_EncryptFinal_ex(ctx, outbuf + outlen, &tmplen))
        {
            printf("\nError : Not a valid encryption\n");
            /*Print Out a relevant Error Messege*/
            return 0;
        }
        outlen += tmplen;
        EVP_CIPHER_CTX_cleanup(ctx);
        //print curret key and its corresponding ciphertext
        printf("The key is : %s The Corresponding Cipher Text Is: ", key);
        char *hex_str = (char*) malloc((outlen * 2) + 1);
        int i = 0;
        /* Use a loop to print out the buffer */
        for (int j = 0; j < outlen; j++)
        {
            // String char to hexa char
            sprintf(&hex_str[j * 2], "%02x", outbuf[j]);
        }
        for (int q = 0; q < (outlen * 2) + 1; q++)
        {
            printf("%c", hex_str[q]);
        }
        printf("\n");
        isMatched = true;
        for (int q = 0; q < (outlen * 2) + 1 ; q++)
        {
            if (cipherTxt[q] != hex_str[q])
            {
                isMatched = false;
                break;
            }
            /* Judge whether the cipher text generated by this key is match for the provoded one */
            /* As the whole ciphertext cannot be matched at once, use this loop to match it bit by bit */
        }
        if (isMatched /* If the generated ciphertext matched with the one provided*/)
        {
            printf("\n*****************************************************\n");
            /* Print the key used */
            printf("\nKey Used %s \n", key);
            /* Print the text in the output buffer */
            printf("\nOutput buffer ");
            for (int q = 0; q < (outlen * 2) + 1; q++)
            {
                printf("%c", hex_str[q]);
            }
            printf("\nProvided Cipher text %s", cipherTxt);
            /* Print the length of the ciphertext */
            printf("\nLength of cipher text %d \n", MAX_LENGTH*4);
            printf("\n*****************************************************\n");
            return 0;
        }
    }
    fclose(fp);
    return 0;
}
New folder/HowTo.txt
Usage : MyRepo.exe HexaCipherSTring(Must be of 64 length) WordFile
Usage : MyRepo.exe 3EE6E497181171BD6980B51DB1043B71D93B2094518854BB70ADE3AC90DA68EC words-tnx5glxp.txt
===================================================================================================
gcc solution :
Install gcc(https://preshing.com/20141108/how-to-install-the-latest-gcc-on-windows/)
Install OpenSSL(https://tecadmin.net/install-openssl-on-windows/)
run command :
gcc -o enc encrypt.c -std=c99 -lcrypto -ldl
Note : You may faced compilation and Linker errors, if Open ssl is not install correctly
Note : for gcc on windows you need to run
gcc -o enc encrypt.c -std=c99 -lcrypto -ldl -luitest.lib -lpadlock.lib -lossltest.lib -lopenssl.lib -llibtestutil.lib -llibssl_static.lib -llibssl.lib -llibcrypto_static.lib -llibcrypto.lib -llibapps.lib -ldasync.lib -lcapi.lib -lWs2_32.lib -lruntimeobject.lib -I
====================================================================================================
For VC++ :
Unzip MyRepo.zip
Open the solution in VS 2017 and rebuild
New...
SOLUTION.PDF

Answer To This Question Is Available To Download

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here