Portable Cryptography API for Triple DES

DES (Data Encryption Standard) is an industrial strength symmetric block cipher.

Included is an implementation of DES and triple DES (which is much stronger than DES) cryptography. It can be used to encrypt/decrypt using CBC (chain block ciphering) or ECB (Electronic Code Book). CBC is a stronger method because the results of each 64 block encryption are used for the next.

It's implemented in ANSI C++, so it can be compiled on any platform. I've also included an ANSI C version for platforms without a C++ compiler). The C++ version has been written as a template class simply because it negates having to include a seperate Cpp file (and I'm lazy); it doesn't require any template parameters.

DES requires a private 8-byte key for encryption/decryption. Triple DES requires two private 8-byte keys for encryption/decryption. To use it in its simplist form, follow this code:

#include "McbDES2.hpp"
#include &ltstdio.h>

void McbTestTripleDES()
{
   unsigned char * lpKey1 = (unsigned char*)"11111111";
   unsigned char * lpKey2 = (unsigned char*)"22222222";

   McbDES desEncrypt;

   desEncrypt.McbSetKey1(lpKey1);
   desEncrypt.McbSetKey2(lpKey2);

   if (desEncrypt.McbEncrypt("Encrypted with triple DES"))
   {
      McbDES desDecrypt;

      desDecrypt.McbSetKey1(lpKey1);
      desDecrypt.McbSetKey2(lpKey2);

      desDecrypt.McbDecrypt(desEncrypt.McbGetCryptogram(),
         desEncrypt.McbGetCryptogramSize());

      printf("Decryption (%d) bytes: %s, \n",
             desDecrypt.McbGetPlainTextSize(),
             desDecrypt.McbGetPlainText());
   }
}

The above example uses the default options of triple DES and PKCS#5 padding to encrypt a block of text. For clarification, the cryptogram is allocated and managed in an instance of the DES class then passed to another instance that performs the decryption. Obviously, this is not a real world example because typically the cryptogram would be squirreled away somewhere or transmitted over a network. Usually, the keyz would be stored elsewhere or perhaps generated from a hashing function based on some user input.

A buffer also can be supplied to the object rather than having the object manage the cryptogram or plaintext. An example of this can be seen in McbMain.cpp, where a stl string is used as the buffer.

Enjoy...



Downloads

Comments

  • gque muligt kan nyde beats by dr. dre

    Posted by wanzixiao on 06/04/2013 09:57pm

    [url=http://www.beatsbydrehretelefoner.weebly.com/]beats by dre høretelefoner[/url] Det kan ikke være potentiel, at du er en total musik-freak, og du måske ikke tænker højtydende trådløse hovedtelefoner! Disse gadgets er de korrekte kammerater specielt inde du lytter til musik bestræbelser. Der er en række organisationer, først og fremmest de velkendte mærker, som Sony, Philips og Samsung osv., der tilfældigvis er i massiv organisering af elektroniske varer og tjenesteydelser og hovedtelefoner med Monstor Diddybeats White trådløse bestemmelser er en af dem. Du vil finde bestemte funktioner og faktorer, som har at blive alvorligt tages i betragtning, når 1 vælger denne fantastiske enhed. Målet er normalt at støde på en sund god kvalitet, der er helt sikkert virkelig vidunderlig og afslappende mod sindet også. [url=http://www.beatsbydrdredanmark.350.com/]beats by dre danmark[/url] Som en atlet de ‘træning, som’, jeg gør, hvad jeg skal gøre for at blive klar “kan hovedtelefonen hjælper mig til at føle jeg er så meget tættere på min musik, der hjælper mig udføre, hjælper mig med at finde ud af, om jeg vil at være intens? Uanset hvad jeg ønsker at være på banen den dag, musik hjælper mig derhen. Da de sagde ja, vil produktet blive valgt og hjælpe dem med at opretholde den bedste tilstand I spillet.Ifølge en talsmand for selskabet, ved Dre endnu ikke har haft en dialog med IOC om “ambush marketing” praksis af atleter iført og twitte om de sanktioneret hovedtelefoner Beats. Men Omar Johnson, Beats senior VP for markedsføring, fortæller Billboard.biz at virksomheden arbejder med atleter året rundt. [url=http://www.kbhretelefonerbillig.webstarts.com/]beats høretelefoner[/url] BIII booo din troede involverer let jazz, med essentials involverer normal, god ole ‘, sammen med digitalkameraer sange for dig at lave en ny specifikt eksklusiv lyd. BIII øjeblikket omdefinerer private musik ekspertise til at gøre dine musikernes øretelefoner. Enhver observere, hver eneste nuance, kan optaget med aldrig-hørt-før realistisk look, plus iøjnefaldende design og stil trådløse høretelefoner bestemt ved en ny trompet mundstykke har som en installation vidnesbyrd om den mestre kunsten. Disse former for sædvanligvis er ikke kun de bedste ørepuder vedrørende jazz. Uanset hvad nogen hører, vil BIII sikkert vokset til betragtes som en af dine nuværende all-time musikalske teknologi højder.

    Reply
  • Concise post exposes the incontestable facts about chanel and the way that it can harm everyone.

    Posted by emeseesip on 05/06/2013 04:14pm

    Essentially The Most Complete adidas E-book You Ever Read Or Your Cash Back [url=http://www.guccija.biz/]gucci 財布[/url] Omg, astounding solution. Your corporation must take a look at adidas now while it's still in stock ! ! ! [url=http://www.guccija.biz/]gucci キーケース[/url] nike assists every one of us by simply adding plenty of unique capabilities and attributes. Its a unvaluable item for every fan of gucci. [url=http://www.guccija.biz/]gucci バッグ[/url] Third party blog post provides Three fresh stuff on gucci that no-one is covering. [url=http://www.chanelja.biz/]シャネル 財布[/url] This is why no one is debating nike and as a consequence the actions one ought to perform immediately. [url=http://www.chanelja.biz/]シャネル 長財布[/url] Different queries about nike resolved and therefore reasons why you should definitely analyze each term within this expose. [url=http://www.chanelja.biz/]chanel 財布[/url] The fundamentals behind nike that you will take full advantage of beginning today.[url=http://www.nikeja.biz/]ナイキランニング[/url] The correct way to fully understand all the stuff there is to find out regarding nike in 4 basic steps.

    Reply
  • http://www.oakleysunglassesoutc.com/ mxuioe

    Posted by http://www.oakleysunglassesoutc.com/ Suttonswa on 03/31/2013 09:51am

    Fleet all the way to quiet the split wave advancing rapidly, Deng Shichang fleet in accordance with the original plan to Beijing arrived in Jeju Island waters near stronghold send a bon voyage telegram. Deng Shichang know ghd hair straightener after this a safe journey telegram was received, that is, to the verge of rupture of Sino-Russian relations again hit on a hammer thoroughly fragmented - Beijing on the morning of July 14, the Chinese Foreign the Minister Kou Green officially proposed to the Russian minister Kaxi Ni severance of diplomatic relations between the two countries, three p.ghd,m.ghd straightener, to Russia declared war.ghd sale, The two countries have officially entered the war.ghd hair straightener, Four o'clock, a specially modified armored train slowly slid into the Jilin government station, train station early yesterday afternoon by the Army all closely monitoring them. Although the in station station platform infantry have stood more than three hours, straight backs but still tightly holding the hands of the hands of the rifle, the soldier's helmet will slightly dim lights reflected on the color of a piece of metal, a bayonet on the rifle adding one-third of the chill of the air in the summer night.

    Reply
  • Interesting

    Posted by snareenactina on 12/22/2012 07:37pm

    The sum of Gross Value Added in various economic activities is known as GDP at factor cost. reject Best Regards, underparts biochemical batch gems bokonon

    Reply
  • UGG Boots,UGG Boots Sale at Kalaro

    Posted by JedsHerearide on 10/25/2012 03:09pm

    Kalaro [url=http://kalarosale.com]ugg boots[/url], high-quality, high discount, free shipping, the best choice for you to buy [url=http://kalarosale.com]sheepskin shoes[/url].

    Reply
  • Genuine UGG Boots sale

    Posted by WamiWamywrosy on 10/22/2012 03:46am

    [url=http://kalarosnowboots.com]Genuine UGG Boots sale[/url]? UP TO 80% Off Buy From Factory Outlet 7 days/week, Kalaro provide better Sheepskin Boots, Slippers, Shoes & Apparel

    Reply
  • Problems with zeros ?

    Posted by juanqui on 11/14/2009 06:22pm

    Martin you have done an excellent work, thanks for the source. I have been working with the ansi c implementation, it works fine in some cases, in others not. Here are some examples: Algorithm DES, encrypted with a 8 bytes key and 8 bytes source. Example 1 works fine Source: 6421EC8AD8F60E66 Key: 5741544348444154 Result: 306FA82F385B2971 Example 2 doesn't work Source: 780565C000098000 Key: 5741544348444154 Result: D88EB6F7BCB8EDBE The valid result should be: BAC52CCA7FA7893A I need your help to do it work, could you please help me ? If you need I can send you more examples or the complete source to test it. Thanks in advance, Juan.

    Reply
  • Adding a third key to triple DES?

    Posted by CharlesGrossman on 09/23/2008 11:03am

    I've enjoyed this article and source code that demonstrates DES and Triple DES. I'm just learning about encryption, so I have a beginner's question: If I want to add a third key to Triple DES encryption, is that just a matter of creating a third subkey? Or are there further complications to worry about?

    • You only works with 2 keys

      Posted by juanqui on 11/14/2009 06:31pm

      Hi, the des algorithm doesn't work with 3 keys. The triple des algorithm doesn't means that you can have 3 keys. If you want to apply the triple des variation of des algorithm it works so: You need 2 keys (each key of 8 bytes), then the triple des algorithm do 3 calculations. First calculates source encrypted des with key1, second calculates the first result decrypted des with key2, and third calculates the second result encrypted with key1. The result is the triple des algorithm.

      Reply
    Reply
  • Sending Cryptogram over network

    Posted by shrodikan on 01/21/2008 02:28am

    Hello Martyn,
    I love this easy-to-use DES library! It is very simple to use and fast also. The problem that I am having is I cannot seem to get the Cryptogram to come out on the other side of a Socket. 
    CODE - Server Side:
    //I init the proper keys, etc and then:
    err = send(c, (const char *)des_e.McbGetCryptogram(), des_e.McbGetCryptogramSize(), 0);
    CODE - Client Side
    //Do the same initialization, etc:
    recv(s, buff, sizeof(buff), 0);
    des_d.McbDecrypt((unsigned char *)buff, strlen(buff));
    //this doesn't output anything right! When I call des_d.McbGetPlainText() later. 
    
    I really appreciate all that you did with the code and completely understand if you are too busy to give me a hand. Thanks a lot Martyn and good luck with your job(you probably have one already with the quality of work that you do)! Peace, Zach

    • Thanks Martyn!

      Posted by shrodikan on 01/27/2008 11:50am

      Just to let you know it was pebkac. I was initializing the keys (1 && 2) to be of length 9 by accident. As soon as I broke it down to its functional parts, I found this issue. Thanks for your fast response and keep up the good work!

      Reply
    • strlen bad for binary

      Posted by Fazer1000 on 01/22/2008 06:01am

      Hi Shrodikan, On brief perusal I would imagine that your problem is related using strlen to determine the length of the cryptogram from the receiving socket. Don't forget that the cryptogram is encrypted text and will contain binary. strlen uses ANSI based strings which are NULL (0) terminated. It's probable and highly likely that the cryptogram will contain a 0 in its payload. Therefore the length is being incorrectly interpreted and your deciphered text will not be correct. I use one of two basic options when I'm writing socket code to dermine stream lengths. Option 1 would be to use a postfix that you look for in the stream to determine when a complete message has been obtained. This option is best suited for data types such as XML where by you can expect a particular delimiter. Another option I often use is to first send the length of the data in the first DWORD (or unsigned long if your not coding on Windows) then follow the DWORD with the data. I reckon this is the best way to deal with binary messages including the cryptogram which you are dealing with. Regards, Martyn

      Reply
    Reply
  • Martyn Brown looking for work

    Posted by Fazer1000 on 10/19/2007 08:31am

    I'm currently looking for a position which allows me to program from home. Alternatively, I'm contemplating a new challenge and lifestyle change with a permanent/contracting position in a nice warm country other than the UK (any serious offer considered). Please contact me if you would like to see my CV. Techical skills below... C/C++ (10+ years), C#/.NET, COM/ATL, STL, MFC/wxWidgets, IBM MQSeries (6+ years) (including MQI/Admin), Windows NT (10+ years) (including RPC/Services/GUI development/ TCP/IP/ multithreading/etc), Visual Basic/VBA, UNIX daemons (ANSI C), x86 Assembler (inline/MASM), Cryptography, SQL Server, Microsoft Access V2 (5 years), Java.

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • When it comes to desktops – physical or virtual – it's all about the applications. Cloud-hosted virtual desktops are growing fast because you get local data center-class security and 24x7 access with the complete personalization and flexibility of your own desktop. Organizations make five common mistakes when it comes to planning and implementing their application management strategy. This eBook tells you what they are and how to avoid them, and offers real-life case studies on customers who didn't let …

  • With JRebel, developers get to see their code changes immediately, fine-tune their code with incremental changes, debug, explore and deploy their code with ease (both locally and remotely), and ultimately spend more time coding instead of waiting for the dreaded application redeploy to finish. Every time a developer tests a code change it takes minutes to build and deploy the application. JRebel keeps the app server running at all times, so testing is instantaneous and interactive.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds