lhe Code Project - A C++ Implementation of lhe Blowfish EncryptiowDeetyption melhod - / MITC Página I de 6
e 70, n • 110.57tor + I) TO nound (Unir ) C43. 00i fffif MAR
•
g deitei • lnStr (17 01 nter. 5 ftet 0 . ".") ",) ' 900)
2 W~Iiiigi4§.4—e.W41:44441:114 Mit•44'4.
tefC / C++ ss C• / MOC as CeVIROtnauf C++ (VOS)
~dosa (9Vtn95, 1+095, NTS,
A C++ Implementation of the Blowfish Encryption/Decryption W
VZ2
32K,) VS
Deu
method %MINI 270a0 zoo).
By George Anescu •not,les cottus eu:Sse
03,306 News
An eructe presenting a Cr.. implernentation of tio niownsn encryption/decryotion metriod
Seer, ~M.M
. Natal ~ides Nmage Board. Storefront Mures.
Toolbox 43 member, have rated tele ertscN. Result. ein=i
Popo:nor., 7.39. Retino: 4.51 out OCO.
• Boo, .1n Unksi
s %NCT
Vt . 2003 for NowfIsh.zip (19.9 Kb)
t MSON Univ.
frorn $1950 Introduction
dilOso «mon
BIOW11511 Is ao encryption algorlthm that can be used as a replacernent for lhe DES or IDEA algorIthms. II is a symrnetric
Os.nci cl ,
ti.e. uses lhe same secret key for both encryptkm and decryption) block cipher (encrypts data In 8-byte blocks) that uses a
varlable-length key, from 32 (4 bytes) bits to 448 bits (56 bytes). Blowfish was designed is 1993 by Bruce Schneier as an
Sigo ft-, ,r si gn isp alternatiye to existing encryptIon algorithrns. Designed with 32-bit instruction processors in mind, It is significantly faster
than DES. Since its origin, has been analyzed considerably. BlowfIsh Is unpatented, licenseiree, and available free for ali
E+2111
uses. lhe algorithm consisto of two parto: a key-expansion part and a data-encryption part. Key expansion converto a
PR. f variable key of at least 4 and at most 56 bytes Into severa) subkey arrays totalling 4168 bytes. Blowfish has 16 mundo.
Rensertber roo Each round consisto of a kerdependent permutation, and a key and data-dependent substitution. Ali operatIons are XORs
eá.i ng) em and additions on 32-bit words. lhe ordy addltional operations are four indexed array data lookups per round. Blowfish uses
Seeossofdf
a large number of subkeys. These keys must be precomputed before any data encryption or decryption.
lost soer
A more detalled enleie describing the Blowfish afgorithm can be found at littP;liwwiy..Sehnelec,conglgowfigIttnol
The C+ Implementation presented Si this ande vias tested against lhe test vectors provided by Eric Veung at
littp://www.rOunterpane.ConlfveCt0f,txt. lhe resulto Mem identical with one exCeption which in my opinion could be a
typing error In the referenced Internet tile.
hup://www.codeprojectconVcpprblowlish.asp 02109:2004
The Code Project - A Cf-. Implementation of the Blowfish EncryptioteDeeryption method - It4PC Página 3 dc 6
lhe use of class Is very easy. to lhe first code snippet example a key of 8 bytes In sito Is applled to an 8 byte
block. The initial chain block is a null block. The block' Is encrypted and then decrypted back.
É
cher .00011+1;
CR lesei els onlosrPtehl )5.no.T fl)sr• "elssioton • tf
cher es.pee•Inli • •eaashbbb'
• xCat•Out 11T) • .).):0 ), \ 0\0,,
y(s.:
01310WItleh. Enerypt 1 lusos or.e0 02.0 : • eROnseln, (ons,,f,ed o:.n r• ) ornato,.
CherSte2R000ts (unaluned char•)ezDatatn. eslíex, el
ocos.. •zliefc and])
CharSts-214exStr 1 tonosgmd enor w) ~atenta . suRrot, 01
« szNez es endl
remoce (esnaeatn, O, 81:
al(siFieh.Deerypt ,:hor•)etuDeteOut , funesone..). vitus .1 exDate In, 4) t
CharStr203e0tr (uno loned •) eollatatn, peites, 01,
eout « edlex e< endl:
e«ntexcep60004 roiscepCionl
col. se roRxeopcion.whest) se •ndl;
In the next code snlppet example a key 07 16 bytes In sito Is applied to a tanger block of data 01 48 bytes sino (lhe block of
data size should be a multiple of Lhe block size which Is always 8 bytes). lhe 'ninai chaln block Is a null block. lhe block
• nksr.babob0000ce7 e ost.7 Co, cocc.77 , ,abo.)ff.0a1700,, ,, Is encrypted and then decrypted back In ali lhe operation modes
(PCB, CBC and CFB). Notice that for lhe chaining operating modos lhe chain block bus to be reset before decrypting back.
C5100Pbal, onotePieh I (une sgne3 eltar • 1 .12 f .1i5,897.12345Os, 16);
esDal.lnl 1091 • .n .r..abefsob.yeeeocrenr.otselastsoccosecenhobolsorecrec,r.,
thor esDete In (4,1
COor 11.0.3tft01.1t
weefeet (esOat•In. O, 491;
MIAM. (133D4 ■ 011t , 5, 49):
http://wv.v.codeproject com/cppfblowfish.asp 02)09/2004
The Code Project - A 0I-1- Implementation of lhe Blowlish Encryption/Denyption method - OH. / MPC Página 2 de 6
Implementation
Vi sual The public user interface of Lhe c:Diouf isr. class is elven bellow:
Assist roem Chlowrieh
rvshLi
,, ,,,:evtotzucCor In/419144n ,he ond $ hoxeo 1hr 4 g/von 444
celowittatiiuninvhex exare ucxey, eize_t r.,
Upgrade conec Mocho roChein SDloM
ilkoretticg [te cha:ning clock
A
OULUL)),
Your VO.id ibblffitehãir.0
Kn.,4>pc,'.0,:enype euffor rt4.44
Microsoft void Encrype(unx,yood cher. buE. eice_t n, :nt iniodevDMI):
void Decrypt(unotsaned cher. buí. eice_t n, int iNodevEC6):
IDE ZnotypCiDeczypI Xama Ovt,:mr Cnuput Sur:fr,
void IncrY0C(conot untngned ohocv in, Unkel,pwd chftr , 0.t.
Today 8121LE n, Int IMoOM.000I:
vold Decrypt(cocet cha4. In, ucclo.ted cher. out.
efte_t n, cc iModevIICOI:
In lhe constructor, a user-supplied key material of specified soe is used to generate Lhe subkey arrays. Riso Lhe chain block
Is initialized with lhe specified value.
lhe function Uva CUa ir, II is used to reset Lhe chaining block before starting a new encryption ar decryption operation.
lhe first variant of Lhe Encrypt function is used for In (Mace encryption of a block of data of lhe specified size applying
Lhe specified operation mode. lhe block sue should be a multiple of 8. This function can operate In Lhe following medes:
ECB, CBC ar CFB. Ia ECB mede, chaining is not used. II Lhe same biock is encrypted twice with Lhe same key, lhe resulting
ciphertext blocks are the same. In CBC mode a ciphertext block is obtained by first X0R-Ing the plalntext block with Lhe
previous ciphertext block, and encrypting the resuiting valse. In CFB mede a ciphertext biock is obtained by encrypting Lhe
previous ciphertext biock and X0R-Ing lhe resuiting value with the plaintext. The operation mode Is specified In lhe imedv
parameter with ECB being Lhe default valse. For Lhe second varlant of the function Lhe encryption result is
deliverecl In ao output buffer.
The Deerypr II functions are tire reversa of lhe :"..r.crypt.:. functions presented above.
Usage Examples
http://www.codeproject.comlepplblowfish.asp 02/09/2004
The Cede Project - AC-I-+ Implementation of thc Blowfish EncryptionVccryption method Cl MFC Página 4 de 6
4 tr 9PY( 4404aa/n. ecnotaIn1::
c00eet(e4Cet0Out, 4. 491:
oBlowneh.EnoryptIlunvigned on94.).:DetaIn.
[une4:9491 ehatv,e40e1e0ut, 45. COloyfteh.:8C19):
comeet(e40etaIn. O. 191;
onl000ieh.0e0ryptIl007845eed charo)e4DataCut.
lunviueed cheto)ecnotaln, 4E. ClilovVieh:AECW:
onlowPioh.eopetChainf):
9,9 05, ( 80 0et 4 In, o400taIn11:
ceme5(9000000ut, O, 4 9 1:
oBlowneh.fincryptilono,uned ch.e.S.Detale.
lant,govd cher”..DateOut, 45, CelowFloh..C9C):
memeet(orDeta/n, 0. 491:
ohlovvioh.ReeetChain():
0.,..,i4n.78009YPOfiennogno0 ch,re}ozDataOut,
1.14:gued chevw}o4notaIn. 4E. Celovvieh..C9CI:
oDloweleh.80peCChea90:
ocropy(e4DetaIn, uPétaln11;
comeeet(ezDateOut, 0, 491:
oelovFleh.Encryptflune,gnea cha,./040.4.taIn,
lunsIgned whorecOeteOuC, Si, ChlowPieh..C90):
meneet(e4Deteln, O. 491:
cffilow0ioh.ReeocChaan();
calooFieh.Decrypt(lune45ned ch4.44CeutOut,
ium44gro4 ch4,14.40a.taIn, 48, ChlovVIeh.CE110:
coes « endl:
cotoklexceptIoni roExc.ption)
Obus cc •6.4cop..1,vo •
cc roException.whatO cç
I am interested In any opinlons and new ideas about this Implementation. lhe project NowEsh.zip attached to this articie
inciudes the salame code of lhe presented ciass and some test code.
George Anescu
ClIck Saro to voo George Anosois ordin• pron14.
http://www.codeproject.comkpp/blowlish arp 02/09/2004
The Code Project - A C++ Implementation of the Blowfish Enerption/Decryption method • C++ f MFC Pagina 5 de G
Other popular C++ / MFC articles:
131~11,h Encrypt.
• How a C+ compiler implements eaception hancfling Um** to 120-AO 851. Enerypoon Proact loroonont
An Inatpth asolaton of how +Ca. Irak:tants ***** ban handlIng. Sara coda 1 Ela -Lean Ma.
Meadas anamon lanam/ atroa for
• scaling of mernory Intensiva multl-threaded applIcations to SMMP
cornputers Bus Encryption Softwbro
Th. artkle Manas Impact alho multithraded mmtlm• Ilbaty't mentor/ matador 128 Elit.Wodo on any Windows Any Cata. Any PC
on salino manory-Interalst amor opolationt to Sha050 Samoa ..I.Praema Frear.
amputas. li
• Using MSHTML Edning o VC6 DociYiew applications
•
How to *ata 1.514119. alho; In • Ylew In VCd
C++
Pmentb
wrapper for Gilles Vollant's Unzip AP1
a atenda at .100.a0.e Intata. to manono dant:9.nd atractIn9
multa. Ma from 1711 arara
I W11108tertIN
Connottyour mama lothoNotwidasmplea securIbt II
Crop1 Sigo In to vote for (1115 4r11c1e: Poorr fere Exceent
D punidasVe..doen
Pfbniten Sognoco
'
*FAQ Nato levai convnbnet Efeen
tnev., IAtou.4 10*1. .;11 For pago 125
Now thrami Mu, I to 25 of 58 (Total: 58) (:, ,ro,) Fust Pr.0 Sleol Lg5t
SubMa author Date
g I.Icbbs. r hrnaliarardevoloper 1359 50 Aup . 04
g prosamo with Impa boa tf kanothoterrIbla 10:55 O Aug '04
á why Veia. -Q 0104r11u2sain MS IS NI .04
g Probl... relth ImplmnantatIon -Q Cor /Unau, 11:00 7 Apr .04
g R, Progforn with Implgonontaton ont,nr. 10:37 B ApI
http://www.codeprojectcomicppfblowtish asp 02/0912(104
The Code Project - A C14 Implementation «lhe Blowfish Encryption/Dectyption method - C+4 i MFC Página 6 de 6
á Need a C5t409 Interface/ * Anonyrnoue 14:05 19 Atar . 04
g C5Inn9 :Mofa" vmh 71010 060009 e-- hm* p polynr69 10:110 Apr '04
ej 1 don't 95111 lo . 2 Zipmer 16:5121 May '04
I throad eafe.... 9 trOok 16:02 17 Mar '04
:á Re: thread ode.. 2 0080069 3:21 14 Apr '04
á meterem* 990h mferenoe 0119 10.008007.7 12 •ndru123 9:463 Mar 924
g !caril deerypt :ming this algo * A0007. 00 . 15:51 31 lan .04
11 8-byte 0440ing7 g 30eo90s Coop., 16:55 24 Dee .03
á Multlpiee o, 8 Prohlato 2 Nermaphrodyte 17:26 14 930 .03
á Constructor quostion 2 NOckey 11:22 3 Dec .03
á Re: Constrocter gewaten 2 040:94 Mosco 11:423 Dec '03
I 11010 nwr oleoso?? 2 tothlrnanatur 5:095 9.9, 03
rá Nove 10 ufa the eneryption/deeryptIon with ¡Ming with 1e0990e not a multlpie o( 8 bytes7 28 beeakpoint 7:30 7 °et .03
g Re' 044: tO use the er.ovPtaiucleeeyphon voto st , trtp .10h leng, ,, np, ,, n,,,, p5, 01$ 0,000 , 4 C.. L...... 7:10 5 11. '03
á 0090 19 add p0ddi40 90090117 9 vek0n 6:19 15 Sep :03
á elifteaMt to emito (Ode 2 llre.. 2:0530 144y . 03
4 5099e00I00 ror a utility that 9909r4003 849.7 * AnOnymowe 10,2111 Oct '02
ál Re. 5uppea1coe Se: a o01ty the% pesem.: keys , * Anonwnous 0:5031 Mar '04
g Mlnor eug9ea9ion 9 964_91uen• 15:34 29 Oet .02
4 Pe. Miner wmgemon p George AIMICu 93:404 Nev '02
1910 VIII,: 17:16 Thurulay ano 549090be1, 2004 First Prev 141. Lua
AI lopo, Mfr: .: Co- o> Ce• 7 MN: >> Cermet:mo.. Ande coment 90900990 01090 Anual, 2001
updated: 77~7001 tommythhp dm apye195t O 0.'0,4,1.1999-2006.
Filverbse or 'Ne Ude Pmegt 1 Priva.
MIOU Cqns,•nynit. 1 0.54140.10b • 045410pe PePoo • DerGort: • Prvjnenurreet 000490 • Nbnet Soara COO< • keleuice Ind. • Tek-nos Forums • 900a0 e %MV • 0.01Bulialet •
2VOti • 33101: l30
http://wv.w.codeprojecteornIcpp/blowfishasp 02/09/2004