EG Information
Training Missions
Knowledge Bank
Pimp Us Out!
Has Enigma Group Helped You? Then Help Us By Advertising For Us. Place One Of The Following Images On Your Site And Create A Link Back To Enigma Group.
|
| |
Affiliates
|
|
Enigma Group's Code Bank
Example of using OpenSSL CryptoFunctionsBy: BinaryShinigami - Date Submitted: 2009-05-31 18:38:56 //MUST LINK WITH LibCrypto (-lcrypto) Tested under Linux with G++ make sure you have openssl installed /* This program is an example of using openssl's encryption functions to encrypt a file using blowfish and decrypt it This was created by BinaryShinigami as an example. Hope you enjoy it :) P.S. I know I'm not an expert at ssl and encryption so some things may not be perfect but FUCK YOU! This is simply to help those who have never used openssl's crypto functions b/c The documentation is poor at explaining shit and I couldn't find all the much, I did find one tutorial and I followed it through so the code may look similar but I have changed some stuff as the code that was posted was giving me problems. */ #include <iostream> #include <fstream> #include <openssl/ssl.h> //This is the include under linux for openssl, haven't tested it on windows so you may have to look this up for your system :p #include <string> #include <cstring> using namespace std; //These functions will be used to encrypt some data or decrypt some data using openssl's blowfish algorithm. int myBlowfishEncrypt(char *inBuff, char *outBuff,char *pass,char *iv,int *outLen, int inLen); int myBlowfishDecrypt(char *inBuff, char *outBuff, char *pass, char *iv, int *outLen, int inLen, int maxSize); int main(int argc, char *argv[]) { if (argc < 6) { cout <<"Usage: " <<argv[0] <<" -e|-d (encrypt or decrypt respectively) <inputFile> <outputFile> <iv_file> <passwordFile>" <<endl; cout <<"\t -e : Encrypt a file in inputFile and put encrypted contents in outputFile" <<endl; cout <<"\t -d : Decrypt a file in inputFile and put decrypted contents in outputFile" <<endl; cout <<"\t <inputFile> : The filename of the file to be encrypted/decrypted" <<endl; cout <<"\t <outputFile> : The filename to store the encrypted/decrypted contents" <<endl; cout <<"\t <ivFile> : The filename of the file that contains the data for the initialization vector, should be 56 bytes" <<endl; cout <<"\t <passwordFile> : The filename of the file that contains the encryption key must be no bigger than 512 bytes, if not a multiple of 8 then it will be padded to be one" <<endl; return 0; } char blowfish_iv[57]; //This will be the IV or initialization vector, its 56 + 1 since We will use a iv of size 56 just cuz i can :p char plaintext[40]; //This is the plaintext or data that has been read, the program will be reading in chunks of 40 until it hits the end char password[512]; //This will be the password we will use, I have decided to make it a max of 512 chars for mere simplicity but so far I found that as long ass the pass is a power of 8 it works char cipherText[48]; //This will hold the outputed data, it is 48 bytes b/c blowfish outputted 48 chars for every chunk of 40 i tried :) it's supposed to be inputlength+1 block size so I guess it makes the block size 8 bytes int outputLength = 0; //This will be used to hold the output length for the ciphertext or plaintext from our encryption/decryption functions so we know how many bytes to write to the new file int BytesRead = 0; //This will tell us how many bytes was read from the last read operation int bytesToRead = 40; //We use this to keep track of how many bytes we need to read, e.g. for encryption we read 40 byte chunks, for decryption we read 48 byte chunks ofstream outFile; //Self explanatory :p ifstream inFile; //Same as above //Here we open the ivFile and load the contents and only read 56 bytes if not 56 bytes then we error out b/c I say so //NOTE I believe we only need a IV of 40 but I choose a IV of 56 just to be safe :p and The IV does matter in encryption/decryption, if they are not the same then decryption will not work I've tried it inFile.open(argv[4]); if (!inFile) { cerr <<"Unable to open IV File! Try again" <<endl; return 0; } inFile.read(blowfish_iv,56); if (inFile.gcount() < 56) { cerr <<"IV < 56 bytes ! Problem Encountered!" <<endl; return 0; } inFile.close(); //strcpy(blowfish_iv,"12345678901234567890123456789012345678901234567890123456"); //Fill the //Now its time to load the password key If the key is not a multiple of 8 it will pad it with 0's which is bad so you should make sure it is inFile.open(argv[5]); if (!inFile) { cerr <<"Can't Open Password File!" <<endl; return 0; } inFile.read(password,512); BytesRead = inFile.gcount(); if ((BytesRead%8) > 0) { int BytesToPad = 8-(BytesRead%8); for (int i = 0; i< BytesToPad; i++) sprintf(password,"%s%c",password,'0'); } inFile.close(); //strcpy(password,"12345678901234567890123456789012345678901234567890123456"); //END OF loading iv and password //Here we check if the file mode is encryption and if so we encrypt the file if (strcmp(argv[1],"-e") == 0) { //BEGIN FILE ENCRYPTION CODE inFile.open(argv[2]); outFile.open(argv[3]); while(! inFile.eof()) { inFile.read(plaintext,bytesToRead); BytesRead = inFile.gcount(); myBlowfishEncrypt(plaintext,cipherText,password,blowfish_iv,&outputLength,BytesRead); outFile.write(cipherText,outputLength); outFile.flush(); } inFile.close(); outFile.close(); cout <<"File Encrypted!" <<endl; //END ENCRYPTION CODE } //Now we check if mode is decryption instead else if (strcmp(argv[1],"-d") == 0) { //BEGIN FILE DECRYPTION CODE inFile.open(argv[2]); outFile.open(argv[3]); while (!inFile.eof()) { bytesToRead = 48; //We do this b/c for some reason 48 kept getting changed to 0 :( inFile.read(cipherText,bytesToRead); BytesRead = inFile.gcount(); cout <<"Read " <<BytesRead <<" bytes" <<endl; myBlowfishDecrypt(cipherText,plaintext,password,blowfish_iv,&outputLength,BytesRead,bytesToRead); outFile.write(plaintext,outputLength); outFile.flush(); cout <<"Wrote " <<outputLength <<" bytes" <<endl; } cout <<"File Decrypted!" <<endl; inFile.close(); outFile.close(); cout <<"Files Closed" <<endl; //END DECRYPTION CODE } return 0; } //For a full explanation of what each parameter to the EVP functions is for check out the decrypt function as it has the same variables and same meanings to both functions. int myBlowfishEncrypt(char *inBuff,char *outBuff,char *pass,char *iv, int *outLen, int inLen) { int finalOut = 0; EVP_CIPHER_CTX cipherHandle; //The handle to the current setup kinda like a cURL handle EVP_CIPHER_CTX_init(&cipherHandle); //Like cURL_Init in cURL, it has to be the first function called EVP_EncryptInit(&cipherHandle,EVP_bf_cbc(),(const unsigned char*)pass, (const unsigned char*) iv); //Setup our handle to use blowfish memset(outBuff,0,inLen); //Wipe any garbage memory in the output buffer //Actually encrypt the data if ( EVP_EncryptUpdate(&cipherHandle, (unsigned char*)outBuff, outLen, (const unsigned char*)inBuff, inLen) != 1) { cout <<"error Encrypting data" <<endl; cout <<"Update" <<endl; return -1; } //If needed pad the data and encrypt the left over data if ( EVP_EncryptFinal(&cipherHandle,(unsigned char*) (outBuff + *outLen), &finalOut) != 1) { cout <<"Error Encrypting Data" <<endl; return -1; } *outLen += finalOut; EVP_CIPHER_CTX_cleanup(&cipherHandle); return 0; } //Maxsize is the size of the chunk of data read(48) if it wasn't padded with data ;) int myBlowfishDecrypt(char *inBuff, char *outBuff, char *pass, char *iv, int *outLen, int inLen, int maxSize) { int finalOut = 0; EVP_CIPHER_CTX cipherHandle; int charLen = strlen(inBuff); EVP_CIPHER_CTX_init(&cipherHandle); EVP_DecryptInit(&cipherHandle,EVP_bf_cbc(),(const unsigned char*)pass, (const unsigned char*) iv); memset(outBuff,0,charLen); //ALL THE ABOVE IS THE SAME AS BEFORE IN ENCRYPT //Here we decrypt the data blocks //The first arg is the ctx handle, the 2nd is the output buffer, the 3rd is the address of a int to store the size of the outputed data, the 3rd is the input buffer, the 4th is teh size of the input buffer, success == 1 if ( EVP_DecryptUpdate(&cipherHandle, (unsigned char*)outBuff, outLen, (const unsigned char*)inBuff, inLen) != 1) { cout <<"error decrypting data" <<endl; cout <<"Udate" <<endl; return -1; } //This code here handles files that were padded //it would be padded if the file length was not a multiple of 8 so the block count would be different, //we read in 48 as max so if it is less then 48 we have some short blocks may not always work //but worst case scenario we could run this function everytime and not check for errors if (inLen < maxSize) { //This function acutally deals with the padding //1st arg is handle, 2nd is location to store the data (we used the regular outputBuffer just used some pointer arithmetic to move to the end of the last decrypt so we don't need to concatenate the values //3rd is the address of the place to store the new outputlenght if ( EVP_DecryptFinal(&cipherHandle,(unsigned char*)(outBuff + *outLen),&finalOut) != 1) { cout <<"Unable to decryptFinal data" <<endl; return -1; } //Add the new outputlength from Final to that from Update since they both form the same varible we need the actual size of the variable *outLen += finalOut; } //Cleanup EVP_CIPHER_CTX_cleanup(&cipherHandle); return 0; }
|
| Return to
cpp category list |
|
|
Who Visited EnigmaGroup Today?
1505 Guests, 295 Users (193 Spiders)
g3nu1n3, Distorted, ant0601, BlAd373, nmobin27, myfabregas, spartanvedicrishi, DrOptix, saraf, VireekadiaFap, obencefoozy, memoryshot, mongrel88, drag0n, Kearstin29, litbk, alexelixir, r0z4, Abhinav2107, theanonymous21, greatg, CreedoFiegree, bivaEmilltite, posthuman01, Taireegaddita, Taicadine, c_a13, hizImmoli, scifics, slchill, KELATALFTUS, kynapse, Tonyui, Hackpad, Epilioptiop, Mamorite, IodindDog, brunoriversyhn, Effomeidonize, ReottphoffBom, arktek, burgeoningneophyte, TradaGreant, SlayingDragons, Waldlyeps, Arsenal, CJ_Omaha, Ryuske, thethird3y3, todayadvila, pwnpwnlolz, NeetaexomYgom, ookami-namikaze, dot_Cipher, Unotohumsmush, SaubymorRoyab, loltyg, Ausome1, Rik, hrangel, cyber-guard, Meonkzt, mori, 31415926, optioniLele, intorerse, FlifobbyFloks, Ios, Røgue, cossyDrybrich, IvanDimitriev, havisham, KIKNWING, fitz, fleeloCycle, hackboy302, strudels, CootoDorbeeft, gymnediny, hustleman9tv, comando300, Ysri13, thatoneguy, Paran0id, whoami, Pitanteerve, Reapon, cls777, Afrika, suetekh, somebody777, floontiny, Frudopvia, jasonbourne, zombiehack640, CloverCipher, spoosh, Fraubbova, rulebreaker, dncjor, Fintyoptots, viRuleNt, NipPaineHainy, TheHarrisonW, Jamesgo, TheGanjator, psychomarine, 1421carter, tingle65, claudius, Feld Grau, Partisan, Gunslinger, gydeqqzpn, yshiau, Zaccarato, chromoSone, priovasashCor, ellisp, GothicLogic, keetone, M0rdak, UsedDeteKef, nhorton, archestraty, HatriteBeft, JC06dc5, alpha1, spg, dark_void, wakazi, mtroscheck, TheCheeseDemon, ach.n30, sahariar, hervelegeraf, Psiber_Syn, hackaday, Mod777, neompenly, pollolololo, SnoopSky, Cigmimifs, ProloG-Shaman, unicornrainbow, cheapnikeshoxog, bobsters, foofthoorgo, polemarchos, avacraft, spencerwilliams23, lotato, ryanjcrook, dollerolf, robintenboden, rospark, WexEmbet, BeefSupreme, Hessesian, whydoyoulook, cdpirate, DnA-Ender, CaNcEr, zheincnoob, Vengeance987, justforfun363, RawTeefecycle, Squissesk, aVoid, SaMTHG, neodude, Marion1p, Ops, ddxc, Klosse, khamhou, samsatHD80, PauffPubadvic, AnnaNoult, SexyCreerve, newb1, robster1977, Blizer, Dudleypagrove, Mr_KaLiMaN, FirewallPenetrator, GMo, Seasharp, mrchicken1, Zaxem, N4g4c3N, MaxMeier, Ian, sander.ashwin, Predatorc, lonely.connection, ElEnfermado, wavyd, dirkdanblue, cve916, kalak55, a1los, jell0, Exclaw, veceattainc, Muselele, Mr Pacifist, stylish007, zach, closednetwork99, soroimmuror, PlaneReaction, Wamemanytex38, DieAble, d0seN_36b, jeremy.whitson, lol, nefeolnb, Noticon, statix, anandoump, RomeoG, advilapyday, snorapa, Gkjt, autotuneuser, beanulpinee, 2142, kiklopas, door51, Pizza, deepakkumar, makler2004, M4rcy, Xargos, bdkoenig, Blavatsky, m4f10, Huasca, itsme, xu_lain, Nikhil, ChewBigRed, samxoxo, incicaMaidits, toudioria, Chidokage, Jigoku, cesecyclelm, schn1ffl3r, sam20000, learning, kentora, San Marino, Nightraven, zanydouner, FrofErrodslot, FatalEror, wheaties, akki, AlexDiru, unclejos666, override101, blink_212, uncowstientee, lilkpoigogs, Innonaenupt607, Killshot, ZheIncKnight, ActictGlync, acarseflalk, ___, trashsporn, Memartent, Zoorsornaks, z3z3, heyhey123, Ghajnm, usaliaPels, Ordeptpen, pelly, quellense, Szuba, lamb, x1rt4m, ToutousaRulty, vipervince2002, mannavard1611, BinaryShinigami, Duchdund, afgnumgt, Anatissa, darkfire1515, bennyblanco5000, Mmmett50 |
| |
|
|
|
|
|