0% found this document useful (0 votes)
67 views

K L Decryption Routines in C: EE OQ

Uploaded by

ognarf
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

K L Decryption Routines in C: EE OQ

Uploaded by

ognarf
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

TB041

KEELOQ® Decryption Routines in C


The KEELOQ Decryption Algorithm was designed to
Author: Lucio Di Jasio operate on a 32-bit message (block) and to be fully
Microchip Technology Inc. configurable by a 64-bit decription key. Its working com-
prised some 528 encryption stages (loops).
At the beginning, a 32-bit shift register is loaded with
OVERVIEW the message to be decrypted. Than in each stage (of
This Technical Brief describes the implementation of 528) 5 bits from the shift register are entered in a Non
the fundamental Decryption Algorithm used in most Linear Function (NLF), combined with two more bits
KEELOQ applications in the C programming language. from the same shift register (XORed) and one bit from
the key to produce a new bit that is then rotated into the
Three implementations are presented. In the first one,
shift register. Finally, the 64-bit key itself is rotated so
the code is written in the most generic form and is suit-
that every bit in the key gets used at least 8 times.
able for implementation on high end processors and
desktop computers using standard C compilers (e.g. At the end of the process, the decrypted message
Microsoft® or Borland®). In the other two implementa- (plain text) is available in the 32-bit shift register itself
tions, the code is optimized for speed of execution on (see Figure 1).
8-bit PICmicro® microcontroller and C compilers (e.g.
HITECH PIC C and CCS PIC C). STANDARD C IMPLEMENTATION
The first implementation is aimed at personal comput-
INTRODUCTION ers with vast resources of RAM and program memory,
In KEELOQ Technology, the Decryption Algorithm is not and targets mainstream compilers (like Borland and
really part of the original specification and could be in Microsoft). Therefore, the source (available in appendix
fact anything (e.g. DES, Rijndael) if it is considered A), is not optimized. Optimization is left to the compil-
solid enough for the application and conforms to a ers. To hold and manipulate the shift register and the
basic set of rules that goes more or less like this: key (split in two), 32-bit integers are used. Bit manipu-
lation is performed “defining” three simple functions
1. Block cypher
(inline) based on shifting and spacing bit logic opera-
2. Key configured tors for maximum portability. All in all, the simplicity of
3. Uses a symmetric key (the same key is used the implementation is evident while the performance
during encryption and decryption ) will be very dependent on the compiler, target proces-
The algorithm discussed in this Technical Brief is refer- sor type and clock speed.
ring to the most popular algorithm implemented in the
first set of HCS2XX and HCS3XX Encoders and PICmicro C IMPLEMENTATION
HCS5XX Decoders (and Application Notes) released
The second and third listings (appendix B and C) refer
from Microchip. For simplicity from now on, we will refer
to versions of the same Decryption Algorithm specifi-
to it as the Decryption Algorithm,
cally optimized for the popular HITECH and CCS C
compilers for the PICmicro family of 8-bit microcontrol-
ALGORITHM OVERVIEW lers.
The KEELOQ Decription Algorithm was originally The code has been optimized for space using the
designed for optimal performance on 8-bit PICmicro smallest number possible of RAM locations, and has
microcontrollers (MCU) that run at 4 MHz only. The been further optimized for execution speed considering
design specifications dictated a 64-bit key length and the typical constraints of an embedded control design.
as in every good modern encryption algorithm, the
Eight bit variables and arithmetic have been used to
security of the application had to depend uniquely on
better exploit the potential of the 8-bit RISC architec-
the secrecy of the key. In other words, if we assume the
ture of the PICmicro MCU. Since the standard C lan-
“enemy” knows the algorithm but not the secret key, the
guage syntax would not allow the expression of the
system must still be secure.
rotation with a sufficient level of efficiency for small
8-bit microcontrollers, and to streamline the Non Linear
Function computation, different optimization tech-
niques had to be used for the two compilers.

 2001 Microchip Technology Inc. Confidential DS91041A_C-page 1


TB041
The CCS implementation makes use of compiler spe- ning at 4 MHz. This compares quite nicely with the
cific library functions like SHIFT_LEFT(), SWAP() speed of comparable assembly language implementa-
and BIT_TEST(), while the HITECH implementation tions with a speed difference in the range of a 30%.
requires the use of single line assembly inserts
asm(), or multiple lines inserts #asm .. #endasm. REFERENCES
Further, in order to optimize the 64-bit key manipulation
An Introduction to KEELOQ Code Hopping TB003
(the key is actually stored in an array of 8 x 8-bit inte-
gers), the main loop has been broken in two nested Secure Learning RKE Systems Using TB001
loops so that the key is accessed and rotated one byte KEELOQ Encoders
at a time. The added advantage of this method is that KEELOQ Decryption & IFF Algorithms TB030
at a end of the computation, the key is still aligned and
Interfacing a KEELOQ Encoder to a TB042
ready for the next use, while in a rotation scheme like
PLL Circuit
the generic C code, the key has to be reloaded or
rotated 16 more times for realignment. KEELOQ CRC Verification Routines TB043
Considering the small amount of code, there is almost
MEMORY USAGE
no difference in the efficiency of the two compilers in
terms of code space. Memory usage is dependent on C compiler used.
In terms of speed efficiency, both versions get more or
less to the same level achieving some 25 ms for a full KEYWORDS
decryption on a generic mid-range PICmicro MCU run- KEELOQ, Decoder, Decryption, C Language

FIGURE 1: THE KEELOQ DECRYPTION ALGORITHM


bit 7
MSB Code Shift Register LSB
bit 7
3 2 1 0
bit 6 bit 1 bit 3 bit 0 bit 0

NLF

XOR

bit 7
7 6 5 4 3 2 1 0
MSB Key Register LSB

TABLE 1: NON-LINEAR FUNCTION OUTPUT


I4 I3 I2 I1 I0 NLF I4 I3 I2 I1 I0 NLF
0 0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 1 1 1 0 0 0 1 0
0 0 0 1 0 1 1 0 0 1 0 1
0 0 0 1 1 1 1 0 0 1 1 1
0 0 1 0 0 0 1 0 1 0 0 1
0 0 1 0 1 1 1 0 1 0 1 0
0 0 1 1 0 0 1 0 1 1 0 1
0 0 1 1 1 0 1 0 1 1 1 0
0 1 0 0 0 0 1 1 0 0 0 0
0 1 0 0 1 0 1 1 0 0 1 1
0 1 0 1 0 1 1 1 0 1 0 0
0 1 0 1 1 0 1 1 0 1 1 1
0 1 1 0 0 1 1 1 1 0 0 1
0 1 1 0 1 1 1 1 1 0 1 1
0 1 1 1 0 1 1 1 1 1 0 0
0 1 1 1 1 0 1 1 1 1 1 0

DS91041A_C-page 2 Confidential  2001 Microchip Technology Inc.


TB041

Software License Agreement


The software supplied herewith by Microchip Technology Incorporated (the “Company”) for its PICmicro® Microcontroller is
intended and supplied to you, the Company’s customer, for use solely and exclusively on Microchip PICmicro Microcontroller prod-
ucts.
The software is owned by the Company and/or its supplier, and is protected under applicable copyright laws. All rights are reserved.
Any use in violation of the foregoing restrictions may subject the user to criminal sanctions under applicable laws, as well as to civil
liability for the breach of the terms and conditions of this license.
THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATU-
TORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICU-
LAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR
SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.

APPENDIX A: GENERIC C SOURCE CODE


//
// Module GENC.C
//
// Keeloq Decryption Algorithm
// generic implementation in C language
//
//
// INPUTS:
// mpik, mpin 64 bit decryption key (preloaded)
// csr 32 bit shift register (preloaded with text to decrypt)
// OUTPUT:
// csr 32 bit plain text (decrypted message)
//
#include <stdio.h>

typedef unsigned int word;


typedef unsigned long dword;

#define setbit( b, n) ((b) |= ( 1 << (n)))


#define getbit( b, n) (((b) & (1L<<n)) ? 1 : 0)
#define ifbit(x,y) if (getbit(x,y))

dword mpik,mpin; // decryption key


dword csr; // shift register

dword decode(dword csr)

{
dword lut[32] =
{ 0,1,1,1, 0,1,0,0, 0,0,1,0, 1,1,1,0, 0,0,1,1, 1,0,1,0, 0,1,0,1, 1,1,0,0 };
/* E 2 4 7 C 5 A 3 */

dword pik,pin,bitin,keybit,keybit2;
word bitlu;
int ix;

// Load Key

pik = mpik;
pin = mpin;

for(ix=0; ix < 528; ix++)


{
// Rotate Code Shift Register

 2001 Microchip Technology Inc. Confidential DS91041A_C-page 3


TB041

bitin = getbit(csr,31);
csr<<=1;

// Get Key Bit

keybit2=getbit(pin,15);

// Rotate Key Right

keybit=getbit(pik,31);
pik=(pik<<1)|getbit(pin,31);
pin=(pin<<1)|keybit; /* 64-bit left rotate */

// Get result from Non-Linear Lookup Table

bitlu = 0;
ifbit (csr, 1) setbit(bitlu,0);
ifbit (csr, 9) setbit(bitlu,1);
ifbit (csr,20) setbit(bitlu,2);
ifbit (csr,26) setbit(bitlu,3);
ifbit (csr,31) setbit(bitlu,4);

// Calculate Result of XOR and shift in

csr = csr ^ bitin ^ ((csr&0x10000L)>>16) ^ lut[bitlu]


^ keybit2;
}
return csr;
}

DS91041A_C-page 4 Confidential  2001 Microchip Technology Inc.


TB041
APPENDIX B: CCS C COMPILER SOURCE CODE
//-------------------------------------------------------------------------
// Keeloq Decryption Algorithm
//
// optimized for CCS PIC C compiler v. 2.535
//
// version 1.00 01/09/2001 Lucio Di Jasio
//
// INPUTS:
// DKEY[0..7] 64bit decryption key (pre loaded)
// Buffer[0..3] 32bit shift register (pre loaded with text to decrytp)
// OUTPUTS:
// Buffer[0..3] 32bit plain text (decrypted message)
//
//=========================================================================
unsigned int DKEY[8];
unsigned int Buffer[3];

void Decrypt()
{
unsigned int i, j, key, aux; // 8bit variables
signed int p; // 7bit +sign

p = 1;

for (j=66; j>0; j--)


{
key = DKEY[p--];
if (p<0)
p+=8;

for (i=8; i>0; i--)


{
// NLF
if ( BIT_TEST( Buffer[3],6))
{
if ( !BIT_TEST( Buffer[3],1))
aux = 0b00111010; // 10
else
aux = 0b01011100; // 11
}
else
{
if ( !BIT_TEST( Buffer[3],1))
aux = 0b01110100; // 00
else
aux = 0b00101110; // 01
}

// move bit in position 7


if ( BIT_TEST( Buffer[2],3))
SWAP( aux);
if ( BIT_TEST( Buffer[1],0))
aux<<=2;
if (BIT_TEST( Buffer[0],0))
aux<<=1;

// xor with Buffer and Dkey


aux ^= Buffer[1] ^ Buffer[3] ^ key;

// shift in buffer
SHIFT_LEFT( Buffer, 4, BIT_TEST( aux,7));

key<<=1;

 2001 Microchip Technology Inc. Confidential DS91041A_C-page 5


TB041
} // for i

} // for j
} // decrypt

DS91041A_C-page 6 Confidential  2001 Microchip Technology Inc.


TB041
APPENDIX C: HITECH C SOURCE CODE
//-------------------------------------------------------------------------
// Keeloq Decryption Algorithm
//
// optimized for HITECH PIC C compiler v.7.85
//
// version 1.00 01/09/2001 Lucio Di Jasio
//
// INPUTS:
// DKEY[0..7] 64bit decryption key (pre loaded)
// Buffer[0..3] 32bit shift register (pre loaded with text to decrytp)
// OUTPUTS:
// Buffer[0..3] 32bit plain text (decrypted message)
//
//=========================================================================
unsigned char DKEY[8];
unsigned char Buffer[4];

#define BIT_TEST( b, n) (( (b) & (1<<(n))) != 0)

unsigned char aux; // keep it global for simple use in asm()

void Decrypt()
{
unsigned char i, j, key; // 8 bit unsigned
signed char p; // 8 bit signed

p = 1;

for (j=66; j>0; j--)


{
key = DKEY[p--];
if ( p < 0)
p += 8;
for (i=8; i>0; i--)
{
// NLF
if ( BIT_TEST( Buffer[3],6))
{
if ( !BIT_TEST( Buffer[3],1))
aux = 0b00111010; // 10
else
aux = 0b01011100; // 11
}
else
{
if ( !BIT_TEST( Buffer[3],1))
aux = 0b01110100; // 00
else
aux = 0b00101110; // 01
}

// move bit in position 7


if ( BIT_TEST( Buffer[2],3))
asm(“swapf _aux,f”);
if ( BIT_TEST( Buffer[1],0))
aux<<=2;
if (BIT_TEST( Buffer[0],0))
aux<<=1;

// xor with Buffer and Dkey


aux ^= Buffer[1] ^ Buffer[3] ^ key;

// shift in buffer

 2001 Microchip Technology Inc. Confidential DS91041A_C-page 7


TB041
#asm
rlf _aux,w
rlf _Buffer,f
rlf _Buffer+1,f
rlf _Buffer+2,f
rlf _Buffer+3,F
#endasm

// rotate Dkey
key<<=1;
} // for i
} // for j
} // decrypt

DS91041A_C-page 8 Confidential  2001 Microchip Technology Inc.


TB041
NOTES:

 2001 Microchip Technology Inc. Confidential DS91041A_C-page 9


TB041
NOTES:

DS91041A_C-page 10 Confidential  2001 Microchip Technology Inc.


TB041

“All rights reserved. Copyright © 2001, Microchip Trademarks


Technology Incorporated, USA. Information contained
in this publication regarding device applications and the The Microchip name, logo, PIC, PICmicro,
like is intended through suggestion only and may be PICMASTER, PICSTART, PRO MATE, KEELOQ,
superseded by updates. No representation or warranty SEEVAL, MPLAB and The Embedded Control
is given and no liability is assumed by Microchip Solutions Company are registered trademarks of
Technology Incorporated with respect to the accuracy Microchip Technology Incorporated in the U.S.A. and
or use of such information, or infringement of patents or other countries.
other intellectual property rights arising from such use
or otherwise. Use of Microchip’s products as critical Total Endurance, ICSP, In-Circuit Serial Programming,
components in life support systems is not authorized FilterLab, MXDEV, microID, FlexROM, fuzzyLAB,
except with express written approval by Microchip. No MPASM, MPLINK, MPLIB, PICDEM, ICEPIC,
licenses are conveyed, implicitly or otherwise, under Migratable Memory, FanSense, ECONOMONITOR,
any intellectual property rights. The Microchip logo and SelectMode and microPort are trademarks of
name are registered trademarks of Microchip Microchip Technology Incorporated in the U.S.A.
Technology Inc. in the U.S.A. and other countries. All
Serialized Quick Term Programming (SQTP) is a
rights reserved. All other trademarks mentioned herein
service mark of Microchip Technology Incorporated in
are the property of their respective companies. No
the U.S.A.
licenses are conveyed, implicitly or otherwise, under
any intellectual property rights.” All other trademarks mentioned herein are property of
their respective companies.
© 2001, Microchip Technology Incorporated, Printed in
the U.S.A., All Rights Reserved.

Microchip received QS-9000 quality system


certification for its worldwide headquarters,
design and wafer fabrication facilities in
Chandler and Tempe, Arizona in July 1999. The
Company’s quality system processes and
procedures are QS-9000 compliant for its
PICmicro® 8-bit MCUs, KEELOQ® code hopping
devices, Serial EEPROMs and microperipheral
products. In addition, Microchip’s quality
system for the design and manufacture of
development systems is ISO 9001 certified.

 2001 Microchip Technology Inc. Confidential DS91041A_C-page 11


WORLDWIDE SALES AND SERVICE
AMERICAS New York ASIA/PACIFIC (continued)
150 Motor Parkway, Suite 202
Corporate Office Korea
Hauppauge, NY 11788
2355 West Chandler Blvd. Microchip Technology Korea
Tel: 631-273-5305 Fax: 631-273-5335
Chandler, AZ 85224-6199 168-1, Youngbo Bldg. 3 Floor
Tel: 480-792-7200 Fax: 480-792-7277 San Jose Samsung-Dong, Kangnam-Ku
Technical Support: 480-792-7627 Microchip Technology Inc. Seoul, Korea
Web Address: http://www.microchip.com 2107 North First Street, Suite 590 Tel: 82-2-554-7200 Fax: 82-2-558-5934
San Jose, CA 95131
Rocky Mountain Singapore
Tel: 408-436-7950 Fax: 408-436-7955
2355 West Chandler Blvd. Microchip Technology Singapore Pte Ltd.
Chandler, AZ 85224-6199 Toronto 200 Middle Road
Tel: 480-792-7966 Fax: 480-792-7456 6285 Northam Drive, Suite 108 #07-02 Prime Centre
Mississauga, Ontario L4V 1X5, Canada Singapore, 188980
Atlanta
Tel: 905-673-0699 Fax: 905-673-6509 Tel: 65-334-8870 Fax: 65-334-8850
500 Sugar Mill Road, Suite 200B
Atlanta, GA 30350 Taiwan
Tel: 770-640-0034 Fax: 770-640-0307 Microchip Technology Taiwan
ASIA/PACIFIC 11F-3, No. 207
Austin
Analog Product Sales Australia Tung Hua North Road
8303 MoPac Expressway North Microchip Technology Australia Pty Ltd Taipei, 105, Taiwan
Suite A-201 Suite 22, 41 Rawson Street Tel: 886-2-2717-7175 Fax: 886-2-2545-0139
Austin, TX 78759 Epping 2121, NSW
Tel: 512-345-2030 Fax: 512-345-6085 Australia
Boston Tel: 61-2-9868-6733 Fax: 61-2-9868-6755 EUROPE
2 Lan Drive, Suite 120 China - Beijing Denmark
Westford, MA 01886 Microchip Technology Beijing Office Microchip Technology Denmark ApS
Tel: 978-692-3848 Fax: 978-692-3821 Unit 915 Regus Business Centre
New China Hong Kong Manhattan Bldg. Lautrup hoj 1-3
Boston
No. 6 Chaoyangmen Beidajie Ballerup DK-2750 Denmark
Analog Product Sales
Beijing, 100027, No. China Tel: 45 4420 9895 Fax: 45 4420 9910
Unit A-8-1 Millbrook Tarry Condominium
Tel: 86-10-85282100 Fax: 86-10-85282104
97 Lowell Road France
Concord, MA 01742 China - Shanghai Arizona Microchip Technology SARL
Tel: 978-371-6400 Fax: 978-371-0050 Microchip Technology Shanghai Office Parc d’Activite du Moulin de Massy
Room 701, Bldg. B 43 Rue du Saule Trapu
Chicago
Far East International Plaza Batiment A - ler Etage
333 Pierce Road, Suite 180
No. 317 Xian Xia Road 91300 Massy, France
Itasca, IL 60143
Shanghai, 200051 Tel: 33-1-69-53-63-20 Fax: 33-1-69-30-90-79
Tel: 630-285-0071 Fax: 630-285-0075
Tel: 86-21-6275-5700 Fax: 86-21-6275-5060
Dallas Germany
Hong Kong Arizona Microchip Technology GmbH
4570 Westgrove Drive, Suite 160
Microchip Asia Pacific Gustav-Heinemann Ring 125
Addison, TX 75001
RM 2101, Tower 2, Metroplaza D-81739 Munich, Germany
Tel: 972-818-7423 Fax: 972-818-2924
223 Hing Fong Road Tel: 49-89-627-144 0 Fax: 49-89-627-144-44
Dayton Kwai Fong, N.T., Hong Kong
Two Prestige Place, Suite 130 Germany
Tel: 852-2401-1200 Fax: 852-2401-3431
Miamisburg, OH 45342 Analog Product Sales
India Lochhamer Strasse 13
Tel: 937-291-1654 Fax: 937-291-9175
Microchip Technology Inc. D-82152 Martinsried, Germany
Detroit India Liaison Office Tel: 49-89-895650-0 Fax: 49-89-895650-22
Tri-Atria Office Building Divyasree Chambers
32255 Northwestern Highway, Suite 190 Italy
1 Floor, Wing A (A3/A4)
Farmington Hills, MI 48334 Arizona Microchip Technology SRL
No. 11, O’Shaugnessey Road
Tel: 248-538-2250 Fax: 248-538-2260 Centro Direzionale Colleoni
Bangalore, 560 025, India
Palazzo Taurus 1 V. Le Colleoni 1
Los Angeles Tel: 91-80-2290061 Fax: 91-80-2290062
20041 Agrate Brianza
18201 Von Karman, Suite 1090 Japan Milan, Italy
Irvine, CA 92612 Microchip Technology Intl. Inc. Tel: 39-039-65791-1 Fax: 39-039-6899883
Tel: 949-263-1888 Fax: 949-263-1338 Benex S-1 6F
United Kingdom
Mountain View 3-18-20, Shinyokohama
Arizona Microchip Technology Ltd.
Analog Product Sales Kohoku-Ku, Yokohama-shi
505 Eskdale Road
1300 Terra Bella Avenue Kanagawa, 222-0033, Japan
Winnersh Triangle
Mountain View, CA 94043-1836 Tel: 81-45-471- 6166 Fax: 81-45-471-6122
Wokingham
Tel: 650-968-9241 Fax: 650-967-1590
Berkshire, England RG41 5TU
Tel: 44 118 921 5869 Fax: 44-118 921-5820

01/30/01

All rights reserved. © 2001 Microchip Technology Incorporated. Printed in the USA. 3/01 Printed on recycled paper.
Information contained in this publication regarding device applications and the like is intended through suggestion only and may be superseded by
updates. It is your responsibility to ensure that your application meets with your specifications. No representation or warranty is given and no liability is
assumed by Microchip Technology Incorporated with respect to the accuracy or use of such information, or infringement of patents or other intellectual
property rights arising from such use or otherwise. Use of Microchip’s products as critical components in life support systems is not authorized except with
express written approval by Microchip. No licenses are conveyed, implicitly or otherwise, except as maybe explicitly expressed herein, under any intellec-
tual property rights. The Microchip logo and name are registered trademarks of Microchip Technology Inc. in the U.S.A. and other countries. All rights
reserved. All other trademarks mentioned herein are the property of their respective companies.

DS91041A_C-page 12 Confidential  2001 Microchip Technology Inc.

You might also like