Edipermadi Thesis

  • Uploaded by: Edi Permadi
  • 0
  • 0
  • June 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Edipermadi Thesis as PDF for free.

More details

  • Words: 31,308
  • Pages: 167
THE APPLICATION OF RC4 STREAM CIPHER IN SECURE COMMUNICATION OVER PUBLIC SWITCHED TELEPHONE NETWORK USING ATMEGA32

By Edi Permadi

A Thesis Submitted to the Faculty of President University in Partial Fulfillment of the Requirements for the Degree of Bachelor of Science in Electrical Engineering in the Faculty of Engineering Cikarang Baru, Bekasi, Indonesia May 2009

© Copyright by Edi Permadi 2009

THE APPLICATION OF RC4 STREAM CIPHER IN SECURE COMMUNICATION OVER PUBLIC SWITCHED TELEPHONE NETWORK USING ATMEGA32

By Edi Permadi Approved:

_______________________________ Dr.-Ing. Erwin Sitompul Thesis Advisor

_______________________________ Dr.-Ing. Erwin Sitompul Program Head of Electrical Engineering

_____________________________ Hendra J. Tarigan, M.S. Dean of Faculty of Engineering

ABSTRACT

The

thesis

presents

an

implementation

of

secure

and

affordable

communication device by employing voice compression and stream cipher over sampled speech signal through public switched telephone network. The information limiting through obscuring is used to attain securing task. Speech signals are sampled, compressed and obscured before through passing the communication line. The two communicating parties initially share secret cipher key as a starting point of establishing secure communication channel. The overall system is implemented as a standalone embedded system geared by the ATMega32 with analog interface and user interface attached. Most of signal processing is done in software using C programming language. The experiment showed a satisfactory secure communication with low bandwidth consumption, lightweight computation, secure and intelligible resulting signal.

i

ÉΟŠÏm§9$# Ç⎯≈uΗ÷q§9$# «!$# ÉΟó¡Î0

’Îû Ÿωuρ ÇÚö‘F{$# ’Îû &™ó©x« ⎯ÏΒ «!$# ’n?tã 4‘xøƒs† $tΒuρ 3 ß⎯Î=÷èçΡ $tΒuρ ’Å∀øƒéΥ $tΒ ÞΟn=÷ès? y7¨ΡÎ) !$oΨ−/u‘

Ï™!$yϑ¡¡9$#

O our Lord! Certainly, You know what we conceal and what we reveal. Nothing on the earth or in the heaven is hidden from Allâh. [Ibraaheem : 38]

ii

DEDICATION

I would like to dedicate my effort to both my parents, Darsono Gunawijaya and Oom Rohimah, also for everyone who interested in embedded cryptography.

iii

ACKNOWLEDGEMENT

First I thank Almighty Allah for allowing me to finish this thesis. His mercy gave me enough time, resource, health and inspiration to keep moving on this thesis. I hope that my effort on doing thesis would be good and useful think for myself and others. I would like to express my gratitude to my thesis advisor, Dr.-Ing. Erwin Sitompul for giving me a chance to work on this thesis. I also thank him for many valuable suggestions and inspiring discussion he provided. It would have been quite hard for me to complete this thesis without his extensive guidance. I would thank my parents for their warmth, love, support, facility, capital and everything you gave me that significantly help through my thesis completion. I would like to express my love and appreciation to my adored sweetheart, Putri Ira Saraswati Ridhoantika. She is the one that fire up my spirit through the completion of this thesis. It would be difficult to run all those tedious work without your warmth and moral support. Finally, I must thank my friends and my juniors at the faculty of Electrical Engineering at President University, for giving me cheers and moral support. I hope you guys are doing good and happy now and forever.

iv

TABLE OF CONTENT

  DEDICATION ............................................................................................................. iii  ACKNOWLEDGEMENT ............................................................................................ iv  TABLE OF CONTENT ................................................................................................. v  LIST OF FIGURES .....................................................................................................xii  LIST OF TABLES ....................................................................................................... xv  LIST OF EQUATIONS .............................................................................................xvii  LIST OF SNIPPETS ................................................................................................ xviii  INTRODUCTION ......................................................................................................... 1  1.1. 

Problem Background ....................................................................................... 1 

1.2. 

Legal Issue....................................................................................................... 2 

1.3. 

Technology Challenge..................................................................................... 3 

1.4. 

Thesis Statement ............................................................................................. 5 

1.5. 

Thesis Objective .............................................................................................. 5 

1.6. 

Thesis Scope .................................................................................................... 6 

1.7. 

Thesis Methodology ........................................................................................ 7 

1.8. 

Thesis Outline ................................................................................................. 8 

LITERATURE REVIEW ............................................................................................ 10  2.1. Speech Coding System ...................................................................................... 10  2.1.1. 

An Introduction ...................................................................................... 10 

2.1.2. 

The Structure of A Speech Coding System ........................................... 11 

2.1.3. 

The Properties of a Speech Coder .......................................................... 12  v

2.1.4. 

The Cryptophone as an Application of Speech Coding System ............ 12 

2.1.5. 

The Structure of a Cryptophone ............................................................. 13 

2.2. 

The Lowpass Filter ........................................................................................ 17 

2.2.1. 

An Introduction ...................................................................................... 17 

2.2.2. 

The Basic Lowpass Circuit .................................................................... 17 

2.2.3. 

The Sallen-Key Second Order Lowpass Filter ...................................... 18 

2.3. 

ADC .............................................................................................................. 20 

2.3.1. 

An Introduction ...................................................................................... 20 

2.3.2. 

The Maximum Sampled Frequency ....................................................... 21 

2.4. 

ADPCM......................................................................................................... 21 

2.4.1.  2.5. 

An Introduction ...................................................................................... 21 

RC4 Stream Cipher ....................................................................................... 22 

2.5.1. 

Introduction ............................................................................................ 22 

2.5.2. 

History.................................................................................................... 24 

2.5.3. 

Legal Issue ............................................................................................. 24 

2.5.4. 

Specification .......................................................................................... 24 

2.5.5. 

Security Issue ......................................................................................... 25 

2.6. 

RS-232........................................................................................................... 25 

2.6.1. 

An Introduction ...................................................................................... 25 

2.6.2. 

The RS-232 Signaling Standard............................................................. 26 

2.6.3. 

The RS-232 Communication Schemes .................................................. 29 

vi

2.7. 

PWM ............................................................................................................. 30 

2.7.1. 

An Introduction ...................................................................................... 30 

2.7.2. 

The PWM as DAC ................................................................................. 30 

2.7.3. 

The Application Consideration .............................................................. 30 

2.8. 

ATMega32 .................................................................................................... 30 

2.8.1. 

An Introduction ...................................................................................... 30 

2.8.2. 

The Feature ............................................................................................ 33 

2.8.3. 

The Device Architecture ........................................................................ 33 

2.9. 

LM386 Power Amplifier ............................................................................... 34 

2.9.1. 

Introduction ............................................................................................ 34 

2.9.2. 

Power Amplifier Schematic ................................................................... 35 

2.10. 

M1632 LCD Module ................................................................................. 36 

2.10.1. 

An Introduction .................................................................................. 36 

2.10.2. 

The Pin Layout ................................................................................... 36 

2.10.3. 

The Interfacing Mode ......................................................................... 37 

2.10.4. 

The Codevision Interfacing Standard ................................................. 38 

2.10.5. 

The Instruction Set ............................................................................. 39 

2.11. 

Diffie-Hellman Key-Exchange Algorithm ................................................ 39 

2.11.1. 

Introduction ........................................................................................ 39 

2.11.2. 

The Mathematical Approach .............................................................. 40 

SOFTWARES AND METHODS ................................................................................ 41  3.1. 

Software ........................................................................................................ 41  vii

3.1.1. 

An Introduction to Embedded C Programming Language .................... 41 

3.1.2. 

The Codevision AVR C Compiler ......................................................... 48 

3.1.3. 

Hercules ................................................................................................. 57 

3.2. 

Encryption Based Secure Communication Device ....................................... 60 

3.2.1. 

Overview ................................................................................................ 60 

3.2.2. 

The Idea ................................................................................................. 61 

3.2.3. 

The Advantages ..................................................................................... 64 

3.3. 

Device Development ..................................................................................... 65 

3.3.1. 

Functional Analysis ............................................................................... 65 

3.3.2. 

Resource Analysis.................................................................................. 66 

3.3.3. 

Prototyping............................................................................................. 66 

3.3.4. 

Sub-circuit Development ....................................................................... 67 

3.3.5. 

Kernel Application Development .......................................................... 68 

3.3.6. 

Sub-circuit Integration ........................................................................... 68 

3.3.7. 

User Application Development.............................................................. 68 

3.3.8. 

Quality Assurance .................................................................................. 69 

DESIGN AND IMPLEMENTATION ........................................................................ 70  4.1. 

An Overview ................................................................................................. 70 

4.2. 

The RC4 Stream Cipher Module ................................................................... 72 

4.2.1. 

An Overview .......................................................................................... 72 

4.2.2. 

Functional Requirement ......................................................................... 73 

4.2.3. 

The RC4 Stream Cipher Initialization ................................................... 73  viii

4.2.4.  4.3. 

The Pseudo-random Generation Algorithm (PRGA) ............................ 75 

Pseudo-random Number Generator ............................................................... 77 

4.3.1. 

An Overview .......................................................................................... 77 

4.3.2. 

The Source of Random Number ............................................................ 78 

4.3.3. 

The Functional Requirements ................................................................ 79 

4.3.4. 

The Implementation ............................................................................... 79 

4.4. 

The Keypad Hardware Module and Driver ................................................... 80 

4.4.1. 

Keypad Hardware Module ..................................................................... 80 

4.4.2. 

Keypad Driver........................................................................................ 81 

4.5. 

The M1602 LCD Hardware Module and Driver ........................................... 83 

4.5.1. 

The LCD Hardware Module .................................................................. 83 

4.5.2. 

The LCD Driver ..................................................................................... 84 

4.6. 

Diffie-Hellman Key-Exchange Algorithm .................................................... 86 

4.6.1. 

An Introduction ...................................................................................... 86 

4.6.2. 

Functional Requirement ......................................................................... 87 

4.6.3. 

The Addition Routine ............................................................................ 88 

4.6.4. 

The Adjustment Routine ........................................................................ 89 

4.6.5. 

The Right Shifting Routine .................................................................... 90 

4.6.6. 

The Multiplication Routine .................................................................... 92 

4.6.7. 

The Implementation ............................................................................... 92 

4.7. 

ADC Hardware Module and Driver .............................................................. 92 

ix

4.7.1. 

The ADC Hardware Module.................................................................. 92 

4.7.2. 

ADC Driver............................................................................................ 94 

4.8. 

PWM-based DAC Hardware Module and Driver ......................................... 95 

4.8.3. 

The PWM-based DAC Hardware Module ............................................. 95 

4.8.4. 

The PWM-based DAC Driver ............................................................... 95 

4.9. 

ADPCM Voice Compression Module........................................................... 95 

4.10. 

Modem Driver ........................................................................................... 96 

4.11. 

Microphone Preamplifier........................................................................... 96 

4.12. 

RS232-TTL Level Converter..................................................................... 98 

4.13. 

PWM Lowpass Filter ................................................................................. 99 

4.14. 

Power Amplifier ...................................................................................... 100 

TEST AND RESULT OF HARDWARE AND SOFTWARE .................................. 102  5.1. 

Introduction ................................................................................................. 102 

5.2. 

Hardware Test ............................................................................................. 103 

5.2.1. 

Power Amplifier................................................................................... 103 

5.2.2. 

Microphone Preamplifier and Post (Passive Lowpass) Filter .............. 104 

5.2.3. 

PWM Lowpass Filter ........................................................................... 106 

5.2.4. 

RS-232 / TTL Converter ...................................................................... 106 

5.2.5. 

Keypad Matrix and Driver ................................................................... 109 

5.2.6. 

LCD 16x2............................................................................................. 112 

5.2.7. 

ADC and PWM .................................................................................... 114 

5.3. 

Software Test............................................................................................... 116  x

5.3.1. 

The RC4 Stream Cipher ....................................................................... 116 

5.3.2. 

The Diffie-Hellman Key-Exchange Algorithm ................................... 121 

CONCLUSION .......................................................................................................... 124  6.1. 

Further Development Direction .................................................................. 124 

BIBLIOGRAPHY ...................................................................................................... 126  APPENDICES ........................................................................................................... 128 

xi

LIST OF FIGURES

Figure 2-1: A Typical Speech Coding System ............................................................ 11 Figure 2-2 : The Block Diagram of a Cryptophone ..................................................... 13 Figure 2-3 : The Illustration of Parallel XOR Process ................................................. 15 Figure 2-4 : The Response of an Ideal Lowpass Filter ................................................ 17 Figure 2-5 : The First Order Passive RC Based Lowpass Filter .................................. 17 Figure 2-6 : The Sallen-Key Second Order Lowpass Filter Topology ........................ 18 Figure 2-7 : The RC4 Taxonomy ................................................................................. 23 Figure 2-8 : DTE to DCE Communication over The RS-232 Interface ..................... 26 Figure 2-9 : Various DTE-DCE and DTE-DTE connection ........................................ 29 Figure 2-10 : The AVR ATMega32 Pin Layout .......................................................... 32 Figure 2-11 : The ATMega32 Architecture ................................................................. 34 Figure 2-12 : The LM386 Pin Layout .......................................................................... 35 Figure 2-13 : The LM386 Equivalent Circuit .............................................................. 35 Figure 2-14 : The LM386 Basic Schematic ................................................................. 36 Figure 2-15: The Illustration of Key-Exchange Process.............................................. 40 Figure 3-1 : The Illustration of an Array ..................................................................... 46 Figure 3-2 : The Illustration of a Null Terminated String ........................................... 47 Figure 3-3 : The Screenshot of Codevision IDE .......................................................... 49 Figure 3-4 : The Windows Menu ................................................................................. 55 Figure 3-5 : The Help Menu ........................................................................................ 55 Figure 3-6 : The Main Toolbar .................................................................................... 56 Figure 3-7 : The Serial Tab Screenshot ....................................................................... 58 Figure 4-1: The Illustration of Kernel Application, User Application and Hardware Module .............71

xii

Figure 4-2: The Relation between Application Software and Hardware Connected Through Driver... 72

Figure 4-3: The Interface of RC4 Stream Cipher Module ........................................... 73 Figure 4-4: The Flowchart of the RC4 Inner State Buffer Initialization ..................... 74 Figure 4-5: The Flow Chart of the RC4 Pseudo-Randomization Generation Algorithm ....... 77

Figure 4-6: The Interfacing Scheme of PRNG Module ............................................... 78 Figure 4-7: The Flowchart of Pseudo-Random Number Generation Routine ............. 80 Figure 4-8: The Schematic of Keypad Hardware Module ........................................... 81 Figure 4-9: The Interfacing Scheme of Matrix Keypad Driver ................................... 82 Figure 4-10: The Interfacing Scheme of DHKEA Module ......................................... 87 Figure 4-11: The Function Reusability Structure of Diffie-Hellman Routines ........... 87 Figure 4-12: The Flowchart of Addition Routine Used in DHKEA ............................ 88 Figure 4-13: The Flowchart of Result Adjustment in DHKEA ................................... 90 Figure 4-14: The Illustration of Bit Stream Scanning by Byte Right-Shifting ............ 90 Figure 4-15: The Illustration of Byte Array Shift Emulation ...................................... 91 Figure 4-16: The Flowchart of Byte Array Shift Emulation........................................ 91 Figure 4-17: The Relation between Data Placement and Types of Alignment ........... 94 Figure 4-18: The Schematic of Microphone Preamplifier ........................................... 97 Figure 4-19: The RS232/TTL Level Converter ........................................................... 98 Figure 4-20: The PWM Lowpass Circuit..................................................................... 99 Figure 4-21: The Power Amplifier Circuit ................................................................ 101 Figure 5-1 : The Configuration of Power Amplifier Test .......................................... 103 Figure 5-2 : The Configuration of Microphone Preamplifier Test ............................ 105 Figure 5-3 : The Test Configuration of the RS-232/TTL Level Converter ............... 108 Figure 5-4 : The Screenshot of RS-232/TTL Level Convertor Test .......................... 109 Figure 5-5 : The Configuration of the Matrix Keypad Test....................................... 111

xiii

Figure 5-6 : The Screenshot of the Matrix Keypad Test ........................................... 112 Figure 5-7 : The Configuration of LCD Test ............................................................. 113 Figure 5-8 : The Configuration of ADC PWM Test .................................................. 115 Figure 5-9 : The Configuration of RC4 Test ............................................................. 118 Figure 5-10 : The RC4 Known Value Test ................................................................ 119 Figure 5-11 : The Screenshot of Inner State Buffer Content ..................................... 120 Figure 5-12: The Screenshot of RC4 Generated Byte Stream ................................... 120 Figure 5-13: The Screenshot of RC4 Generated Byte Stream ................................... 121 Figure 5-14: The Configuration of Diffie-Hellman Test ........................................... 122 Figure 5-15 : The Screenshot of Diffie-Hellman Test ............................................... 123

xiv

LIST OF TABLES

Table 2-1 : The XOR Truth Table ............................................................................... 14 Table 2-2 : The Pseudo Code of RC4 Stream Cipher Implementation........................ 25 Table 2-3 : The RS-232 Physical Interface .................................................................. 27 Table 2-4 : The RS232 Pin Location and Assignment ................................................ 28 Table 2-5 : The ATMega32 Feature Summary ............................................................ 33 Table 2-6 : The M1632 LCD Module Pin Out ............................................................ 37 Table 2-7 : The Codevision LCD Interfacing Standard ............................................... 38 Table 2-8 : The LCD 16x2 Instruction Set .................................................................. 39 Table 3-1 : The list of AVR-Based Embedded C Data Type ...................................... 42 Table 3-2 : The Operators of C Programming Language ........................................... 44 Table 3-3 : The Menu Bar ............................................................................................ 50 Table 3-4 : The File Menu ........................................................................................... 51 Table 3-5 : The Edit Menu ........................................................................................... 52 Table 3-6 : The View Menu ......................................................................................... 53 Table 3-7 : The Project Menu ...................................................................................... 53 Table 3-8 : The Tools Menu ........................................................................................ 54 Table 3-9 : The Settings Menu..................................................................................... 54 Table 3-10 : The Toolbar ............................................................................................ 56 Table 4-1: The Design and Implementation of the RC4 Inner State Buffer ................ 73 Table 4-2 : The Connection of LCD Hardware Module to ATMega32 ...................... 84 Table 4-3: The Codevision LCD API .......................................................................... 85 Table 4-4: The Characteristics of ATMega32 Analog to Digital Converter ............... 93 Table 4-5: ADC Driver Software Design Requirement ............................................... 94

xv

Table 5-1 : The Diffie-Hellman Known Test Reference ........................................... 121

xvi

LIST OF EQUATIONS

Equation 2-1 : The Illustration of Ciphering and Deciphering using XOR ................. 15 Equation 2-2 : The Calculation of The First Order Passive RC Filter ......................... 18 Equation 2-3 : The Applied KCL Law to the Intersection of Z1 and Z2..................... 19 Equation 2-4 : The Applied KCL Law to the Non-Inverting Input ............................. 19 Equation 2-5 : The Combination of Equation 2-4 and Equation 2-3 ........................... 19 Equation 2-6 : The Transfer Function of a Sallen-Key Lowpass Filter ....................... 19 Equation 2-7 : The Simplified Transfer Function of a Sallen-Key Lowpass Filter ..... 20 Equation 2-8 : The Cutoff Frequency of a Sallen-Key Lowpass Filter ....................... 20 Equation 2-9 : The Quality Factor of a Sallen-Key Lowpass Filter ............................ 20 Equation 4-1: The Illustration of Multiplication Decomposition ................................ 86 Equation 4-2 : The Calculation of Output Voltage of Microphone Preamplifier ........ 97 Equation 4-3 : The Cutoff Frequency of Microphone Preamplifier ............................ 98 Equation 4-4 : The Cutoff Frequency of Passive Lowpass Filter ................................ 98 Equation 4-5 : The Calculations of The PWM Lowpass Filter ................................. 100    

xvii

LIST OF SNIPPETS Snippet 4-1 : The RC4 Inner State Initialization ....................................................... 128 Snippet 4-2 : The RC4 Pseudo-Random Generation Algorithm (PRGA) Routine ... 128 Snippet 4-3 : The Pseudo-Random Number Generator (PRNG) Routine ................. 129 Snippet 4-4 : The Implementation of Keypad Driver ................................................ 129 Snippet 4-5 : The Implementation of DHKEA .......................................................... 131 Snippet 4-6 : The ADC Driver Implementation ........................................................ 133 Snippet 4-7 : The PWM-Based DAC Driver ............................................................. 135 Snippet 4-8 : The ADPCM Voice Codec Module ..................................................... 135 Snippet 5-1: The RS-232/TTL Test Code.................................................................. 138 Snippet 5-2 : The Matrix Keypad Test Code ............................................................. 139 Snippet 5-3: The LCD Test Code .............................................................................. 141 Snippet 5-4: The ADC-PWM Test Code ................................................................... 141 Snippet 5-5: The RC4 Test Code ............................................................................... 142 Snippet 5-6: The Diffie-Hellman Test Code.............................................................. 144

xviii

CHAPTER I INTRODUCTION

1.1. Problem Background In this information age, information is like a coin that has two contradictive sides. On the one hand information could be very useful or even very dangerous on the other hand. Since information is significant, it is true that information needs to be protected. The term protection is generally associated to the spread of the information. The bigger the information, the more vulnerable it would be. Communication is a process of transmitting information from sender to receiver through a medium or channel. The information from the sender first encoded and transmitted to the receiver side that will consequently decode the information back into an intelligible shape. The encoding process is necessary to ease the transmission so that all information can be passed over communication channel easily. A communication channel might be public or private. A private communication channel is a point-to-point communication channel that made available only for a sender and a receiver. A private communication channel is also called a secure communication channel, since it can limit the information exposure to the sender and the receiver only. On the other hand, a public communication channel is a communication channel that is open to everyone who wants to use it, either as a sender or a receiver. A public communication channel is simply insecure and not suitable for passing sensitive information. From security point of view, information might be leaked at three positions which are the sender, the receiver and the channel. Assuming that the sender and the receiver trust each other, now the problem is becoming clear that the communication

1

channel is the root of the problem, especially in using public communication channel. A common attack to a communication process is called a “man in middle attack”. This happens when someone is trying to gain information by listening a conversation between the sender and the receiver in the middle of communication channel through eavesdropping, wiretapping and so on. However, establishing a secure (private) communication channel is somewhat expensive and impractical. Therefore, there must be a way to utilize a widely available public communication channel so that it is virtually accessible only to the sender and the receiver (i.e. to make the communication channel secure). Instead of modifying the communication channel, there is an alternative way to provide secure communication by protecting the endpoint communication devices. The device which is built to attain the securing task is then called a secure communication device. The main function of a secure communication device is to obscure what are sent and received. This requirement is generally solved by employing an encryption. Back to the communication channel, Public Switched Telephone Network (PSTN) is a public communication channel that is widely available and cheap. Hence, designing a secure PSTN communication device would be very useful. It becomes the focus of this thesis. A secure communication device can be engaged for a variety of uses such as banking call and secure fax transmission, secure broadcasting, secure private network, secure data exchange, user validation and so on.

1.2. Legal Issue Initially, cryptography is a free science that everyone can learn and practice. Everyone has the same right to conceal or reveal their secret. As an effect, the usage

2

of a secure communication device is supposed to be voluntary, since secrecy is a part of human right that must be respected and protected. However, since cryptography is very powerful, it can become a very useful tool on one time but it also can become a very dangerous one on the other time. On the one hand, secrecy needs to be protected while on the other hand government security is far away more important. The compromising way to this dilemma is to allow public to access cryptographic material that is under the control of the government, meaning that the device should be secure enough from all kinds of public attack but still, easily breakable by the government. In this case, a line interception is necessary for the government to ensure that it will not lose the control due to the secrecy issues raised by the public. The interception enables the government to monitor all civilian activity to avoid criminal disasters. Cryptography may not be used for corruption, crime, terrorism, or any other activities that are against the religion, the law and the ethics. The usage of cryptography must be controlled wisely. All attempts to use cryptography against the law are totally violent and unethical in anyway. The use of cryptography must be strictly used for protecting good things only. All algorithms used in this thesis is widely used in public, meaning that the implementation of the secure communication device outlined in this thesis is generally secure for public use and of course breakable by the government.

1.3. Technology Challenge Currently, the trend of voice oriented secure communication device is focused on the digital representation of the sampled voice signal. The algorithm mainly used

3

in the manipulation includes key-exchange algorithm, stream cipher, pseudo-random number generator, voice compression and some digital signal processing algorithm as the accessory. This trend is becoming so popular since digital signal is robust, simple and easy to handle. In addition, the usage of stream cipher in a secure communication device is very popular due to its performance. But, the usage of several digital signal processing is necessary to limit the bandwidth consumption and to limit unwanted effects such as jittering and echo. The latest trend of asymmetric was started to move away from the conventional exponential modulo calculation to an elliptic platform which has the same strength but lower computational requirements. The usage of asymmetric cipher in a secure communication device is very significant, especially in a key-exchange process that will determine the security of the rest of the process. The other trends of a secure communication device are that it has to be fast, secure, use low power, affordable and use dynamic key management. All these characteristics will value the quality of a secure communication device in terms of performance, secrecy, portability, and cost. Among several programmable device candidates, AVR ATMega32 is the one that sounds near to suit requirements, since it is widely available, cheap, fast and powerful. In order to implement a dynamic key sharing scheme, an environment driven pseudo-random number generator and a Diffie-Hellman key-exchange algorithm are implemented in such a way so that a cipher key is always changed on each call. In programming view, implementing a complex system using AVR assembly would be very good in term of performance. However, assembly-based deployment

4

lacks of time effectiveness. Generally, the assembly codes are harder to read and to debug. Hence, the choosing of C programming language as the development platform is the best approach in terms of time and simplicity.

1.4. Thesis Statement The thesis will be focusing on the development of a secure communication based on the RC4 stream cipher algorithm over Public Switched Telephone Network. A dynamic key management is implemented as a pseudo-random based regular keyexchange through a Diffie-Hellman key-exchange. The transmitted and received voice signals are compressed using a 4-bit ADPCM at 8 KHz sampling rate. The ciphering is implemented using the RC4 stream cipher at 128-bit cipher key length. The telephone interface is done by an external modem which is connected to a microcontroller through a serial asynchronous connection, using AT command. The line event as well as user response are handled by the microcontroller. The overall system consists of an AVR ATMega32 development board, a 16x2 Character LCD, a 4x4 matrix keypad, a microphone preamplifier, a lowpass filter, a power amplifier, an RS-232/TTL level converter and external modem.

1.5. Thesis Objective The objectives of this thesis are summarized as follows: ƒ

To show the applicability of a fast, affordable, and secure communication device based on ATMega32.

ƒ

To emerge the importance of secrecy in voice based communication, especially in banking call.

5

ƒ

To introduce a field of applied embedded cryptography that is currently still alienated in Indonesia.

ƒ

To introduce the microcontroller based secure communication device development in order to help the learning process of communication system in President University.

1.6. Thesis Scope In order to grasp a focused view, the thesis will be constrained to the following topics. •

The thesis only discusses the system of exchanging encrypted and compressed voice signal with microcontroller help.



The microcontroller used is AVR ATMega32 at 16MHz working frequency.



Programming platform is focused on Codevision 1.25.3 AVR C Compiler.



The thesis will not discuss the strength of RC4 stream cipher due to testing complexity issues.



The thesis will not discuss the optimization of lowpass filter, microphone preamplifier and power amplifier design.



The thesis will not discuss the strength analysis of Diffie-Hellman keyexchange algorithm.



The thesis will not discuss the detail of modulation scheme used to exchange data through Public Switched Telephone Network (PSTN).



The thesis will not discuss the optimization of adaptive pulse code modulation as voice signal compressing function.



The thesis will not discuss the C coding optimization for embedded system.

6

1.7. Thesis Methodology The methodology used in this thesis includes literature study, functional analysis, resource analysis, prototyping, sub-circuit development, kernel application development, sub-circuit integration, user application development and quality assurance. The detail of development phases are given below. Literature Study Describing the secure communication concept as well as hardware, software, mathematical background, theories and algorithms which are relevant. Functional Analysis Defining the specific functional requirements that implicitly figured by the ideal secure communication device. Resource Analysis Covering the analysis of available hardware and software resources that are relevant for secure communication device construction. Prototyping The process of gathering theory and reality by exploiting available resource to masquerade functional requirements and compromising ideal theories to be adaptable in real life situation without losing the essence. Sub-circuit Development The process of the assembling correlated sub-circuits defined previously in prototyping phase.

7

Kernel Application Development The process of creating sub-circuit software drivers as well as specific algorithm related functions. Sub-circuit Integration The process of interconnecting and validating the sub-circuits and software drivers against compatibility issues that might happened. User Application Development The process of developing the main software which will control subcircuits, software drivers, and algorithms as a unified secure communication device entity. Quality Assurance The process of verifying the implementation of sub-circuits, kernel application, and user application in order to guarantee the whole functional of a secure communication device.

1.8. Thesis Outline The thesis is organized as follows: Chapter I introduces the thesis in terms of problem background, legal issue, technology challenge, thesis statement, thesis objective, thesis scope, thesis methodology and thesis outline. Chapter II outlines the fundamental information required to understand the conceptual of hardware and software. Chapter III outlines the method and software used by this thesis during design, development and verification.

8

Chapter IV outlines the design and implementation of hardware and software modules. Chapter V provides the result verification of hardware and software module. The verification process is presented as a package of test plan and test result with step by step guide. Chapter VI provides the conclusion of overall discussion and device development.

9

CHAPTER II LITERATURE REVIEW

2.1. Speech Coding System 2.1.1. An Introduction Speech coding is generally defined as a procedure to represent a digitized speech signal using a few bit as possible, maintaining at the same time a reasonable level of speech quality [3]. Speech coding is actually a type of process that involves input, output and processing function. In this case, the applied input is a plain digitized speech sample and the result is an encoded version of digitized speech signal. The processing function is called the speech encoder or simply speech coder. Speech coding system is a class of communication system. Speech coding is performed systematically using an algorithm which is defined as a well defined computational procedure that takes some value or a set of values, as input and produces some value, or a set of values, as output [3]. Speech encoding is generally described as a mathematical model. Therefore, the numerous systematic mathematical computations done in speech coding algorithm is actually a sign of engineering process to exploit available mathematical operation implemented in a programmable device to achieve the functional specification of the speech coder. Thus, the process of implementing speech coder requires an effort to meet the theoretical specifications given by the mathematical model and the available resources given by the programmable hardware. Specified parameters must be compromised such that a minimal drawback can be achieved.

10

2.1.2. The Structure of A Speech Coding System A speech coding system is generally a set of system that enables the speech processing in terms of encoding and decoding. Philosophically speaking, a speech coding system is also a class of communication system since there is a process of information encoding and decoding and information transmission sent from the sender side to the receiver side. Encoding and decoding function belong to the sender and the receiver side respectively. Based on [3], a typical block diagram of a speech coding system is depicted at figure 1-1.

Figure 2-1: A Typical Speech Coding System

In the system above, a speech signal taken from a speech source is first filtered by a Lowpass Filter (LPF) to avoid aliasing, by limiting the band of incoming signal and the Nyquist frequency

[11]

. The expected cutoff frequency of that LPF is about

close to a half of sampling frequency done by the sampler. A periodically sampled speech signal is then quantized and translated by an ADC into digital form. The function of the source encoder is to reduce the baudrate consumption by reducing redundancy through a digital signal compression, as necessary. The existence of this encoder is necessary to increase channel effectiveness. On the other

11

hand, the purpose of the channel encoder and channel decoder is to transform processed digital signal so that it can be effectively transmitted through the communication channel. At the final stage, another lowpass filter is attached to reduce noise from the signal reconstruction done by a pulse width modulation (PWM). Filtered PWM output is then amplified by a power amplifier for loudspeaker driving purpose.

2.1.3. The Properties of a Speech Coder The main goal of speech coding is either to maximize the perceived quality at a particular bit-rate, or to minimize the bit-rate for a particular perceptual quality. The appropriate bit-rate at which a speech should be transmitted or stored depends on the cost of transmission or storage, the cost of coding (compressing) of the digital speech signal, and the speech quality requirements. In almost all speech coders, the reconstructed signal differs from the original one. The bit-rate is reduced by representing the speech signal (or parameters of a speech production model) in a reduced precision and by removing inherent redundancy from the signal, resulting therefore in a lossy coding scheme [3]. The desirable properties of speech coder include: low bit rate, high speech quality, robustness across languages, robustness in the presence of channel error, good performance on non-speech signals, low memory size and low computational complexity, and low coding delay [3].

2.1.4. The Cryptophone as an Application of Speech Coding System Cryptophone is generally a voice oriented secure communication device which enables two users to securely communicate through a public switch telephone network

12

(PSTN) by enabling a digitally compressed speech signal to be encrypted and transmitted over the line. Philosophically, a cryptophone is an application of speech coding system since it processes speech signal through sampling, quantizing, and encoding, with the addition of ciphering and deciphering functionality.

2.1.5. The Structure of a Cryptophone The structure of cryptophone used in this thesis is depicted at figure 2-2.

ATMega32

(6)

RC4

Pre (1)

(2)

LPF

ADC

ADPCM

(3)

(4)

(5)

+ (7)

RS232

V92

(9)

(8)

(10)

ISDN

(14)

PA (19)

(18)

LPF

PWM

ADPCM

(17)

(16)

(15)

+

RS232

V92

(12)

11

RC4

External Modem

(13)

Figure 2-2 : The Block Diagram of a Cryptophone

The block numbered (1) is a device to pick up a physical signal produced by the vibration of air molecules from the environment. The device used is a condensed microphone. Blocks numbered (2) and (18) will perform the amplification to suit the required signal amplitude in the next step. Block numbered (2) specifically amplifies signal produced by the microphone to suite the range of voltage sampling performed by ADC. The block numbered (18) will amplify the voltage and the current produced by PWM, shaped down by LPF, to drive loudspeaker.

13

The block numbered (4) is responsible in converting the speech signal captured by the microphone into a digital signal through sampling and quantizing. The sampling is performed in rate 8 KHz with 256 quantization levels. The hardware of the block is buried inside the ATMega32 microcontroller. The block numbered (5) is responsible of compressing the digital speech signal produced by the ADC. The implementation of this block is done in software, planted in the ATMega32 microcontroller. The compression is done using a 4-bit ADPCM voice coder algorithm that will lower the bandwidth consumption by 50%. The compressed speech sample is then packed back as a byte and sent to the next stage. Blocks numbered (6) and (13) are responsible of generating a pseudo-random byte sequence for ciphering and deciphering use. The sequence of the generated byte stream is determined by a cipher key used to initialize the inner state of the pseudorandom byte stream generator. The cipher key is shared and agreed by two communicating parties through a key-exchange algorithm. Blocks numbered (7) and (14) are responsible of performing ciphering and deciphering process respectively. Ciphering and deciphering is actually a process of concealing and revealing information. One of the common functions beside addition is XOR. XOR is widely used due to its simplicity and reversibility. The truth table of XOR is shown below. a 0 0 1 1

b 0 1 0 1

y = a⊕b 0 1 1 0

Table 2-1 : The XOR Truth Table

14

In XOR ciphering scheme, the cipher text is produced by XORing the plain text with the stream byte, in addition the plain text is produced by XORing the cipher text with the stream byte. The illustration of ciphering and deciphering process is illustrated by the equation 2-1 below.

y n = xn ⊕ z n xn = y n ⊕ z n Equation 2-1 : The Illustration of Ciphering and Deciphering using XOR

Since the width of the plain text, the cipher text and the stream byte are equal, thus ciphering and deciphering process can be done in parallel. The illustration is depicted by the figure 2-3 below.

Figure 2-3 : The Illustration of Parallel XOR Process

In this thesis, since the XORing value is taken from the output of an RC4 stream cipher, it is necessary to maintain the synchronization between two communicating parties otherwise the resulting data will not be readable.

15

Blocks numbered (8) and (12) provide the serialization and the de-serialization respectively. Serialization is necessary to interface external modem that uses asynchronous RS232 as its way of communicating with the data terminal equipment (DTE), the ATMega32. In addition, there has to be an RS232 to TTL voltage converter or vice versa, that interfaces the external modem and ATMega32 microcontroller, since the asynchronous transmission sent and received by ATMega32 is in TTL level. The external modem transmits and receives data from the ISDN/PSTN line through a V92 modulation. In addition, the modulation and demodulation to and from V92 is done by an external modem and it has nothing to do with the ATMega32 microcontroller in anyway. In the receiver side, the ADCM, which is block (15), will decompress a plain data given by the result of de-whitening a series of whitened data taken from the external modem. The PWM block, which is block (16), is responsible of transforming the decompressed speech data given by ADPCM into analog. In addition, the resulting analog signals need to be processed through a lowpass filer and a power amplifier to be ready for driving the loudspeaker. For the sake of operability, the cryptophone secure communication device has to be equipped with an LCD and a keypad for basic interaction with the user. The handling task of the LCD and the keypad are done by the ATMega32 microcontroller.

16

2.2. The Lowpass Filter 2.2.1. An Introduction A lowpass filter is a type of frequency selective filter that passes low frequencies below a given cutoff frequency. Cutoff frequencies are the frequencies defining the boundaries between frequencies that are passed and frequencies that are rejected, i.e. the frequencies in the passband and stopband [10]. The ideal response of a lowpass filter is depicted by figure 2-4 below.

⎧⎪1, ω ≤ ω c H ( jw ) = ⎨ ⎪⎩0, ω > ω c

Figure 2-4 : The Response of an Ideal Lowpass Filter

2.2.2. The Basic Lowpass Circuit A typical lowpass filter is formed when an RC circuit is taken off the capacitor [1]

. In other words, the simplest lowpass filter is made from a voltage divider

constructed by a resistor and a capacitor. In this circuit, the load impedance is very high so that there is no loading at circuit

[7]

. The simplest lowpass circuit is depicted

by the figure 2-5 below.

Figure 2-5 : The First Order Passive RC Based Lowpass Filter

17

The output amplitude, transfer function and cutoff frequency is shown by the equation 2-2 below.

1 XC jωC v vo = vi = 1 i R + XC R+ jωC

1 v 1 jωC H (ω ) = o = = vi R + jωC 1 + jωRC

ωc =

1 RC

Equation 2-2 : The Calculation of The First Order Passive RC Filter 2.2.3. The Sallen-Key Second Order Lowpass Filter Sallen-Key is a topology of a second order filter introduced by R.P. Sallen and E. L. Key of MIT Lincoln Laboratory in 1955. The Sallen-Key topology is configurable as a lowpass filter or a highpass filter. The basic schematic of the SallenKey lowpass filter is shown below.

Figure 2-6 : The Sallen-Key Second Order Lowpass Filter Topology

For highpass usage, both Z1 and Z2 are substituted by capacitors. On the other side, substituted components for a lowpass filter are Z3 and Z4 [15].

18

Since the negative input is connected to the output, thus v− = v+ = vo . By applying the Kirchhoff current law (KCL) to the intersection of Z1 and Z2 named Vx, the equation 2-3 is obtained.

vi − v x v x − v o v x − v o = + Z1 Z2 Z4 Equation 2-3 : The Applied KCL Law to the Intersection of Z1 and Z2

By Applying KCL at the non inverting input, giving an equation 2-4 below

v x − vo vo − 0 = Z2 Z3

⎞ ⎛Z v x = vo ⎜⎜ 2 + 1⎟⎟ ⎠ ⎝ Z3

Equation 2-4 : The Applied KCL Law to the Non-Inverting Input Applying the equation 2-4 to the equation 2-3 yields ⎛Z ⎞ ⎛Z ⎞ ⎛Z ⎞ vi − v o ⎜⎜ 2 + 1⎟⎟ vo ⎜⎜ 2 + 1⎟⎟ − vo vo ⎜⎜ 2 + 1⎟⎟ − vo Z ⎝ Z3 ⎠ = ⎝ Z3 ⎠ ⎠ + ⎝ 3 Z1 Z2 Z4

Equation 2-5 : The Combination of Equation 2-4 and Equation 2-3

The transfer function is given by the equation 2-6 below.

vo Z3Z4 = v i Z 1 Z 2 + Z 3 Z 4 + Z 4 (Z 1 + Z 2 ) Equation 2-6 : The Transfer Function of a Sallen-Key Lowpass Filter

Since Z R = R and Z C =

1 1 , in addition, Z3 and Z4 in lowpass = sC jω C

schematic filter are ZC, thus the equations are changed to the following

19

ωc 2 H (s ) = 2 , 2 s + 2ζω c + ω c Equation 2-7 : The Simplified Transfer Function of a Sallen-Key Lowpass Filter

fc =

1 2π R1 R2 C3C 4

Equation 2-8 : The Cutoff Frequency of a Sallen-Key Lowpass Filter

2ζ =

1 = Q

R1 R2 C3C 4 ⎛ R1 + R2 ⎜⎜ C3 ⎝ R1 R2

⎞ ⎟⎟ ⎠

Equation 2-9 : The Quality Factor of a Sallen-Key Lowpass Filter

The Q factor determines the height and width of the peak of the frequency response of the filter. As this parameter increases, the filter will tend to "ring" at a single resonant frequency near f c [15]. In other words, the Q factor also determines the space between the 0dB line and the peak response. The higher the Q, the longer the space from 0dB line to the peak is, and the more a filter inclines to instability [8].

2.3. ADC

2.3.1. An Introduction ADC stands for analog to digital conversion. The main task of an ADC is to interface a digital processing circuit to be able to read analog signals. The conversion is made by quantizing sampled analog signals periodically. Sampling is implemented by periodically reading and holding an analog signal. This approach is commonly known as a zero order hold sampling. A zero hold sample will hold a previously sampled signal until a new sampled signal is ready. In

20

addition, the quantizing process is done by comparing the sampled signal into a weighted voltage reference. The conversion will result a periodically generated stream of bit string that represents the quantization result at a given time. The size of a bit string is determined by the resolution of ADC or the number of voltage level combination recognized in the quantizing phase. The recognized voltage levels are distributed homogenously along the voltage sampling range, from zero up to the maximum recognized voltage which is the voltage reference of the quantizer. The unit of voltage step is determined by the division of voltage reference with the number of recognized voltage levels. The number of voltages is always in form of 2n.

2.3.2. The Maximum Sampled Frequency The sampling theorem stated that the maximum frequency of the sampled signals is supposed to be lower or equal to a half of the sampling frequency. On the other words, the sampling frequency is supposed to be twice or higher than the maximum frequency of the sampled signal. This rule is commonly known as the Nyquist theorem [10].

2.4. ADPCM

2.4.1. An Introduction ADPCM which stands for adaptive differential pulse code modulation is a derivative of pulse code modulation (PCM). ADPCM uses adaptive quantization and adaptive prediction to represent a sampling difference in 4 bit. The term adaptive means being responsive to changing level and spectrum of the input speech signal [6].

21

2.5. RC4 Stream Cipher

2.5.1. Introduction The term cryptology is literally stands for “hidden word”. The term cryptology is derived from the Greek words “kryptos” and “logos”. Thus cryptology is simply stands for a science that investigates information hiding. The cryptology science is divided into three mainstreams which are cryptography, steganography and cryptanalysis [12]. The term cryptology literally means “secret writing”. The term is originated from Greek words “kryptos” and “graphein”. Thus, cryptography is a part cryptology that deals with secret writing of hidden information

[12]

. Cryptography is identical to

manual “paper and hand” method in early use. The cryptography science has branched its main discussion to public-key ciphering scheme, private-key ciphering scheme, and protocol. In computer age nowadays, modern cryptography also includes semi automatic and automatic processes that enable the usage of electro mechanical and programmable devices. In the case of programmable device platform, cryptography is implemented as a deterministic behavioral system using a systematic computational procedure called algorithm. The private-key ciphering scheme is a cryptographic scheme that enables data encryption and decryption using a particular algorithm, to an arbitrary data, with a given secret key shared by the encryption and the decryption side. Based on its working mode, private-key encryption schemes are classified into block and stream ciphers. Stream ciphers are ciphers that encrypt individual characters (usually binary digit) of a plaintext message at a time, using an encryption transformation which

22

varies which time

[9]

. Stream ciphers are generally grouped into byte-oriented stream

ciphers and bit-oriented stream ciphers. However, based on its internal structure, stream ciphers are divided into LFSR based stream cipher and non-LFSR based stream cipher. RC4 is a private-key byte-oriented stream cipher that uses non-LFSR structure. Due to its orientation, RC4 generates pseudo-random byte stream at a time. The pseudo-random byte sequence is the interface used by the RC4 to perform the encryption and the decryption. The hierarchical map of RC4 in cryptology is shown at figure 2-7.

Figure 2-7 : The RC4 Taxonomy

23

2.5.2. History RC4 a.k.a. ARC4 (Alleged RC4) is invented and developed by Professor Ronald Rivest of MIT for the RSA Security Company at 1987. This stream cipher is initially kept as a trade secret until its first release to public at 1994 [12].

2.5.3. Legal Issue Although RC4 is registered to RSA Data Security Inc, RC4 was not patented anyway. Therefore RC4 algorithm is very well known since anyone can use it as long as they mention the registered owner of the algorithm.

2.5.4. Specification The RC4 stream cipher can be seen as a finite state machine that synchronously generate a pseudo-random byte sequence regarding its internal state [14]

. The internal state of RC4 is made of 256 cells of byte array, thus it has

theoretically 22048 possible states. This massive number of internal state is made to limit the possibility of repeated pseudo-random byte sequence, since the number of possible inner state denotes the period of the stream cipher itself. The longer the period, the less the probability of repetition occurs. In ideal situation, the period of encrypted data is much shorter than the period of the stream cipher to ensure that data is encrypted not using a repeated pseudo-random byte sequence. The RC4 stream cipher consists of two main routines which are keyed inner state buffer initialization and pseudo-random generation. The first routine is intended to initialize the inner state buffer with some customization defined by the given cipher key. The second routine is intended for generating the pseudo-random byte sequence based on the condition of the inner state buffer. In relation to the given cipher key, the

24

inner state buffer initialization can also be categorized as a key-scheduling process. Based on

[14]

, the inner state buffer initialization and the pseudo-random generation

are illustrated below. Inner State Buffer Initialization

Pseudo-random Generation

1: j ← 0 2: for i = 0 to 255 do 3: S[i ] ← i 4: end for 5: for i = 0 to 255 do 6: j ← j + S[i ] + K[i mod l ] 7: swap S[i ] and S[ j ] 8: end for 9: i ← 0 10: j ← 0

1: i ← i + 1 2: j ← j + S[i ] 3: swap S[i ] and S[ j ] 4: output S[S[i ] + S[ j ]]

Table 2-2 : The Pseudo Code of RC4 Stream Cipher Implementation

2.5.5. Security Issue A previous study about RC4 stream cipher has recommended the discard of the first 256 bytes generated pseudo-random byte sequence for security issue [5].

2.6. RS-232

2.6.1. An Introduction RS-232 is a scheme of asynchronous binary communication that uses pulse modulation organized in a polar non-return-to-zero signaling. The term asynchronous binary communication reflects the usage of a clock-less serial bi-voltage level transmission / reception for interchanging information, while the term polar nonreturn-to-zero pulse modulation describes the usage of modulation that uses pulses, swinging from negative to positive and vice versa, as its representation of information.

25

RS-232 is designed to handle the communication between two devices with a distance limit of 50 to 100 feet, depending on the bit rate and cable type. RS-232 uses unbalanced lines, meaning that the signal voltage is applied in one wire line and all voltage signals are referenced to a common ground [2]. In RS-232 communication, point-to-point communicating devices are configured in master-slave configuration. A master device is known as data terminal

equipment (DTE) while a slave device is known as data communication equipment (DCE). DTE are commonly refer a personal computer (PC), a laptop, a microcontroller or any other programmable devices that handles more functionality than other devices connected to the other side of RS-232 cable. The opposite side of DTE is DCE, the devices that has a specific function that uses RS-232 serial interface such as external modem, plotter, printer, fax, cell phone, and so on. The illustration is shown at figure 2-8.

Figure 2-8 : DTE to DCE Communication over The RS-232 Interface

2.6.2. The RS-232 Signaling Standard The RS-232 standard is published by the Telecommunications Industry

Association (TIA). The standard includes signal functions, pin locations and other characteristics of the interface. The standard has been through several revisions since its introduction in 1960, with the latest version RS/TIA/EIA-232-F, dated 1997 [2].

26

The RS-232 interface is commonly available in 9 (DB9) and 25 (DB25) pins male/female (M/F) interfaces in PCB/socket layout. The illustration is given at table 2-3 below. Types

Male

Female

DB25

DB9

Table 2-3 : The RS-232 Physical Interface

27

The location and the function of RS-232 pins are described in the table 2-4. DB9 (M/F)

DB25 (M/F)

Signal

Direction

Function

1

8

CD

DCE to DTE

Carrier Detect

2

3

RX

DCE to DTE

Received Data

3

2

TX

DTE to DCE

Transmitted Data

4

5

20

7

DTR

GND

DTE to DCE

Data Terminal Ready

-

Common Ground

Additional Information ƒ

Active when DCE detected carrier signal from another remote DCE, indicating the communication to remote DCE is succeed

ƒ

Active when DTE ask DCE to connect to communication line. Rose when DTE ask DCE to receive incoming call. Rose on power up to indicate that DTE is present and powered.

ƒ ƒ

ƒ 6

6

DSR

DCE to DTE

Data Set Ready

7

4

RTS

DTE to DCE

Request to Send

8

5

CTS

DCE to DTE

Clear to Send

9

22

RI

DCE to DTE

-

1, 9-19, 21, 23-25

-

-

Ring Indicator

ƒ

Active when DCE is connected to communication line. Rose on power up to indicate that DCE is present and powered.

ƒ

Active when DTE has to send data to DCE.

ƒ

Active when DCE is ready to receive data from DTE.

ƒ

Active when DCE detect an audible ring from communication line and deactivated to pause between two rings.

Table 2-4 : The RS232 Pin Location and Assignment

28

2.6.3. The RS-232 Communication Schemes In RS-232, DTE and DCE can be connected in various configurations, with or without handshaking. When handshaking is not used, it is necessary to turn off the hardware flow control or to fake it by using the DTR to DSR loopback and the CTS to RTS loopback, with the assumption that the opposite part has the same baudrate and always be ready. Various DTE-DCE and DTE-DTE wiring are depicted by the figure 2-9 below.

(a) DTE-DCE Connection with handshaking

(b) DTE-DCE Connection without handshaking

(c) DTE-DTE Null Modem without handshaking

(d) DTE-DTE Null Modem without handshaking Figure 2-9 : Various DTE-DCE and DTE-DTE connection

29

2.7. PWM

2.7.1. An Introduction Pulse Width Modulation (PWM) or Pulse Duration Modulation (PDM) is a type of modulation where the input samples of the message signals are used to vary the duration of individual pulses in the carrier

[6]

. The duration change is interpreted

as the change of duty cycle of a carrier signal at given particular frequency. The change of duty cycle will affect the output voltage average.

2.7.2. The PWM as DAC PWM is a cheap way to perform a digital to analog conversion (DAC) over a limited resource. PWM-based DAC is very popular in microcontroller platform since it does not require a dedicated part, uses low pin count and easily integrated into internal timer. Thus, most of PWM function can be defined as a specific application of a timer.

2.7.3. The Application Consideration Since PWM uses high frequency carrier, it is necessary to filter the resulting signal to crop the carrier signal. The filtering task is performed by a lowpass filter.

2.8. ATMega32

2.8.1. An Introduction The ATMega32 is a high performance, low power, and single cycled 8-bit CMOS RISC microcontroller manufactured by Atmel. The term CMOS stands for

Complementary Metal Oxide Semiconductor while the term RISC stands for Reduced

30

Instruction Set Computer. This microcontroller was designed by using Harvard architecture, separating memory busses of the data and the program, to gain more parallelism. The ATMega32 can be operated in a wide working frequency range, started from 0 MHz up to 16 MHz. In addition, it can handle supply voltage deviation up to 10% with the main working voltage set to 5V. The ATMega32 requires single power supply, i.e. it does not require negative power supply. The ATMega32 is a rich microcontroller in terms of storage, instruction, and hardware peripheral including timer, analog comparator, 10-bit 8 channels of analog to digital converter, programmable Watchdog Timer (WDT), Serial Communication Interface (SCI), and JTAG Interface for debugging-purpose. Types of Serial Communication Interfaces (SCI) natively supported by ATMega32 are Universal Serial Asynchronous Transceiver (USART), Two Wire

Interface (TWI), and Serial Peripheral Interface (SPI). In addition, USART can be configured in various baudrate in synchronous and asynchronous mode. However, TWI and SPI can only be configured in various baudrate in synchronous mode. ATMega32 has 3 timers which are named timer0, timer1 and timer2. Timer0 and timer2 are 8 bit timers while timer1 is 16 bit timer. Each of those timers can be configured to work in normal mode, CTC (Clear Timer on Compare Match) mode, and PWM (Pulse Width Modulation) mode with individually customizable clock source and clock prescalar. ATMega32 is available in 40 pin Plastic Dual in Line Package (PDIP) and 44 pin Thin Profile Plastic Quad Flat Package (TQFP) version. Due to the soldering issue, this thesis will only focus into one type of package which is PDIP. The pin layout of PDIP package of ATMega32 is depicted by figure 2-10 below.

31

Figure 2-10 : The AVR ATMega32 Pin Layout

In order to keep the pin count low while maintaining rich feature, ATMega32 has multiplexed several function in each port. In initial condition, all 32 pin GPIO (General Purpose Input Output) ports are configured as 4 8-bit ports named PORTA, PORTB, PORTC, and PORTD. In attempt to use a specific GPIO pin as its secondary function, it is necessary to decide the port direction first before activating the secondary function flag. If an alternative function of a particular pin is activated then the basic function of that pin will be overridden by the alternative function. ATMega32 can be easily programmed serially in low voltage (5V) using the ISP (In System Programming) via SPI (Serial Peripheral Interface).

32

2.8.2. The Feature The table 2-5 below summarizes the ATMega32 features: Feature Name

Value

Instruction Set

131 unit

General Purpose 8 bit Register

32 unit

Working Frequency

0 – 16MHz

Flash Memory

32 Kbyte

EEPROM

1 Kbyte

SRAM

2Kbyte

8 Bit Timer

2 unit

16 But Timer

1 unit

ADC 10 Bit

8 Channel

PWM

4 Channel 2

TWI / I C Bus

1 Channel

SPI Bus

1 Channel

USART

1 Channel

Programmable Watchdog Timer 1 Unit Analog Comparator

1 Unit

GPIO Line

32 Line

Operating Voltage

4.5 Volt – 5.5 Volt

Table 2-5 : The ATMega32 Feature Summary

2.8.3. The Device Architecture The AVR on the chip system is basically built from the AVR CPU core module, GPIO buffer/driver modules, analog interfaces (comparator and ADC) module, serial communication interfaces (USART, TWI, and SPI) modules, timer (WDT, timer0, timer1, and timer2) modules, an oscillator circuit (internal and external) module, and a timing and control module. The picture 2-11 below describes the block diagram of the ATMega32 inner architecture.

33

Figure 2-11 : The ATMega32 Architecture

The complete description of the AVR ATMega32 can be investigated in the datasheet available at http://www.atmel.com/

2.9. LM386 Power Amplifier

2.9.1. Introduction LM386 is a low power monolithic power amplifier chip manufactured by National Semiconductor. This integrated circuit has low pin count and low quiescent power, making the chip suitable for low power application.

34

LM386 is available in 8 pin Small Outline Package (SOP), Molded Mini Small

Outline Package (MMSOP), and Plastic Dual in Line Package (PDIP). LM386 has a gain value which is internally set to 20 in a minimum external component mode. However, the internal gain can be raised up to 200, by adding some external RC components. LM386 can be operated in a voltage, ranging from 4 up to 12 volts. The pin layout of LM386 and its equivalent circuit are depicted by figure 2-12 and 2-13 respectively.

Figure 2-12 : The LM386 Pin Layout

Figure 2-13 : The LM386 Equivalent Circuit

2.9.2. Power Amplifier Schematic LM386 can be operated as a power amplifier with internal gain of 20, by using a minimum external component requirement. The typical schematic is given by the figure 2-14.

35

Figure 2-14 : Thhe LM386 Basic B Schem matic

2.10. M16332 LCD Mod dule 2.10.1. An Inttroduction The M1632 M is ann intelligent dot matrix LCD module powered by HD447880 L LCD Controlller Chip. Thhis module has h 20 x 2 daata memory to display 16 1 columns of o 2 lines of chharacters. Inn addition, this modulee also has a user defin ned characteer generator to display d the custom c charaacters defined by user. The M1632 M uses Motorola bbus interfacee with the reead and the write controol a thee M1632 LC CD module has h a separaated backlighht tied in the saame pin. In addition, coontrol and an a adjustablee LCD contrrast where the t contrast is set to maaximum wheen thhe setting contrast pin is grounded.

2.10.2. The Pin P Layout The M1632 M is avvailable as an LCD module with 16 pins in a single linne m of eeach pin is explained e by the table 2-66. coonnector. Thhe function mapping

Pin Number 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

Pin Name GND VCC VLCD RS RW E D0 D1 D2 D3 D4 D5 D6 D7 LEDVCC LEDGND

Type Power Power Control Data Data Data Data Data Data Data Data Data Data Data Power Power

Direction NA NA NA I I I I/O I/O I/O I/O I/O I/O I/O I/O NA NA

Value (volt) 0 +5V 0 … +5 0 or +5 0 or +5 0 or +5 0 or +5 0 or +5 0 or +5 0 or +5 0 or +5 0 or +5 0 or +5 0 or +5 +5V 0

Table 2-6 : The M1632 LCD Module Pin Out

2.10.3. The Interfacing Mode The M1632 LCD module can be interfaced in two fashions which are 4-bit interfacing or 8-bit interfacing. An 8-bit interfacing require the microcontroller to uses [D0 up to D7] pin LCD as the data bus, however a 4-bit LCD interfacing requires the microcontroller to use the higher nibble pin [D4 : D7] as data bus. In 8-bit interfacing mode, data can be retrieved and sent by a single E pulse, while the 4-bit interfacing mode require all operation to be done in a couple of E pulse. The 4-bit interfacing mode is more common since it is less complicated.

37

2.10.4. The Codevision Interfacing Standard In order to be able to interface the M1632 LCD with the Codevision API, it is important to follow the standard of Codevision LCD interface. The standardized Codevision interface is given by the table 2-7. Pin Number

Pin Name

Connected To

Pin Number

Pin Name

Connected To

1

GND

GND

9

D2

-

2

VCC

VCC

10

D3

-

3

VLCD

GND

11

D4

PORTX.4

4

RS

PORTX.0

12

D5

PORTX.5

5

RW

PORTX.1

13

D6

PORTX.6

6

E

PORTX.2

14

D7

PORTX.7

7

D0

-

15

LEDVCC

VCC

8

D1

-

16

LEDGND

GND

Table 2-7 : The Codevision LCD Interfacing Standard

38

2.10.5. The Instruction Set The M1632 LCD module has instruction sets defined by table 2-8 below Instruction

D7

D6

D5

D4

D3

D2

D1

D0

Description

Clear Display

0

0

0

0

0

0

0

1

Home

0

0

0

0

0

0

1

X

Mode

0

0

0

0

0

1

I

S

I=1 I=0 S=1 S=0

Increment Decrement Shift No Shift

Configuration

0

0

0

0

1

D

C

B

D=1 D=0 C=1 C=0 B=1 B=0

Display On Display Off Cursor On Cursor Off Blink On Blink Off

Shifting

0

0

0

1

Sc

L

X

X

Sc = 1 Sc = 0

Screen Shift Cursor Shift

L=1 L=0

Shift Left Shift Right

DL = 1 DL = 0 N=1 N= 0 F=1 F=0

8 Bit 4 Bit Double Line Single Line Font 5x10 Font 5 x 8

Function

0

0

1

DL

N

F

X

X

Set CGRAM Address

0

1

ACG

ACG

ACG

ACG

ACG

ACG

Set DDRAM Address

1

ADD

ADD

ADD

ADD

ADD

ADD

ADD

Table 2-8 : The LCD 16x2 Instruction Set

2.11. Diffie-Hellman Key-Exchange Algorithm

2.11.1. Introduction Diffie-Hellman is a public cipher-based algorithm that enables several parties to safely exchange their secret shared key over unsecured communication channel. This algorithm was first published publicly by Whitfield Diffie and Martin Hellman in 39

1976. The key-exchange is virtually performed by agreeing the computational result sent by the other party. The security of this algorithm is determined by the difficulty of taking factor of a large number [13].

2.11.2. The Mathematical Approach The Diffie-Hellman key-exchange algorithm relies on the modular exponent calculations y = a b mod c . The key-exchange process is described by figure 2-15 below.

Figure 2-15: The Illustration of Key-Exchange Process

40

CHAPTER III SOFTWARES AND METHODS

3.1. Software

3.1.1. An Introduction to Embedded C Programming Language 3.1.1.1.

An Overview

Embedded C programming language is a derivative of C programming language which is optimized for embedded system use. The only difference between an ordinary C programming language and an embedded C programming language is that the C programming language is downsized to match the specification of the embedded system processor in terms of system limitation. In this thesis, the microcontroller involved is the ATMega32. Hence, the discussion of the embedded C programming language will be limited to ATMega32 only.

3.1.1.2.

The Preprocessing

Preprocessing is a technique of customizing source code by providing substitution and conditional compilation. The preprocessing is necessary to maintain the portability, the simplicity, the readability of the written codes. Preprocessors are preserved identifiers (keywords) used by a compiler to identify a specific action to perform. The common preprocessor used in C programming includes #define, #undef, #if, #else, #endif, #elif, #ifdef and #ifndef. Generally, definitions are located centrally in a header file. In addition, the C compiler also supports expression and operator.

41

The #define preprocessor declares a particular keyword to be replaced by a given value or string. The #define preprocessor is very helpful in defining widely used constants which might be modified in a particular circumstance. On the other hand, the preprocessor the #undef is useful to undeclare keywords that are previously associated to a value. The #if, #else and #endif are the basic building for conditional compilation process. In addition, the preprocessor #ifdef and #ifndef are just the short term to evaluate whether a given keyword is defined previously or not, while the preprocessor #elif is the short term of expressing an “else if”.

The Data Type

3.1.1.3.

In AVR-based embedded system, the data types of the C compiler are modified to match the architecture of the AVR. Data types in the AVR embedded C programming are redefined by the table 3-1 below. Name

Bits Bytes

Range

bit

1

-

0,1

char

1

1

-128 to 127

signed char

8

1

-128 to 127

unsigned char

8

1

0 to 255

int

16

2

-32768 to 32767

short int

16

2

-32768 to 32767

signed int

16

2

-32768 to 32767

long int

32

4

-2147483648 to 2147483647

signed long int

32

4

-2147483648 to 2147483647

unsigned long int

32

4

0 to 4294967295

float

32

4

±1.175e-38 to ±3.402e38

double

32

4

±1.175e-38 to ±3.402e38

Table 3-1 : The list of AVR-Based Embedded C Data Type

42

3.1.1.4.

The Storage Class Modifier

The ATMega32 supports three types of storage such as flash, EEPROM, and SRAM. Hence, the AVR embedded C compiler has provided a storage class modifier which enables a particular declared variable to be located on each of those three storage types. Variables are initially declared in SRAM, unless a correct storage class modifier is declared. A “flash” class modifier will ask C compiler to reserve part of flash memory for variable declaration. In addition, an “eeprom” class modifier will ask C compiler to reserve part off EEPROM memory for variable declaration.

3.1.1.5.

The Operator

The embedded AVR C compiler supports various types of operator including unary and binary operator. The list of supported operator is given by the table 3-2 below.

43

Name

Operator

Type

Meaning

Sign

+

Unary

sign flag of a number

+5

Set data type range to positive

Sign



Unary

sign flag of a number

–5

Set data type range to negative

Addition

+

Binary

Add values

5+4

Add 5 and 4

Subtraction



Binary

Subtract values

7–4

Subtract 4 from 7

Multiplication

*

Binary

Multiply values

13 * 21

Multiply 13 and 21

Division

/

Binary

Divide values

34/7

Divide 34 by 7

Modulus

%

Binary

Take Modulo

7%3

modulo 3 of 7

Binary OR

|

Binary

Take byte wise OR

8|4

Byte wise OR of 8 and 4

Binary AND

&

Binary

Take byte wise AND

7&1

Byte wise AND of 7 and 1

Binary XOR

^

Binary

Take byte wise XOR

4^3

Byte wise XOR of 4 and 3

Binary NOT

~

Unary

Take 1’s complement

~4

1’s complement of 4

Assignment

=

Binary

Load a value

A=7

Load A by 7

Shift Left

<<

Binary

Binary Shift Left

8 << 2

Shift 8 2 unit to the left

Shift Right

>>

Binary

Binary Right

5 >> 1

Shift 5 1 unit to the right

Equalization

==

Binary

Logical equality

1 == 0

Evaluate whether 1 is equal to zero

Non Equalization

!=

Binary

Logical Inequality

1~=3

Evaluate whether 1 is not equal to three

Less Than

<

Binary

Comparison

4<6

Evaluate whether 4 is smaller than 6

Greater Than

>

Binary

Comparison

1>9

Evaluate whether 1 is greater than 9

Less or Equal

<=

Binary

Comparison

2 <= 7

Evaluate whether 2 is smaller or equal to 7

>=

Binary

Comparison

5 >= 9

Evaluate whether 5 is bigger or equal to 9

&&

Binary

Logical AND

Evaluate the equality of two logical statements

||

Binary

Logical OR

Evaluate the alternative of two logical statements

Greater equal Logical AND Logical OR

or

Shift

Example

Description

Table 3-2: The Operators of C Programming Language

44

3.1.1.6.

The Control Statements

The C programming language can be configured to process a part of codes in particular condition. The control statements in C programming language are categorized into two big groups which are the loop statement and the conditional statement. The loop and the conditional statements are identified by the existence of reserved words that are known by the compilers as control statement identifiers. The loop block is a set of codes which is executed iteratively until an expected condition is occurred, while conditional block is a set of codes which will be executed if the expected condition is met. In C programming language, the allowed conditional statements are “if” conditional and “switch” conditional. The “if” conditional statement enables a nested code to be executed only at the accomplishment of the expected condition is done, while the “switch” conditional statement enable a software to gives different response to a set of conditions. The “switch” conditional is the simplification of nested if-elseif structure. In addition to the conditional statement, the loop statements that are available in C includes “for” loop, “while” loop, and “do-while” loop. Those loops are basically providing the same things which are the execution of the codes under the expected circumstances.

3.1.1.7.

The Variable

In C programming language, a variable is used to store the calculation results. Prior to the data type’s diversity, variables were made configurable. The size of variable will be differentiated by the data type keyword applied.

45

In positional view, variables can be classified into local and global. Local variables are variables located inside a function while global variables are variables located outside a function. A local variable is accessible on that function only, however a global variable is accessible everywhere. The term accessible means readable and writable. Global variables are commonly used to represent the values which have to be accessible by any functions. However, it is not encouraged to declare specific temporary variable as a global variable.

3.1.1.8.

The Array

Array is a class of variable which treats a reserved contiguous location in memory as a unity. Each element of an array is homogenous and configurable in terms\ of size. For example, an integer array will have bigger element than a character array. The element of array is accessible by defining a subscript value. The leftmost element is subscripted zero while the rightmost element is subscripted by the size of array minus one. The Illustration of an array is given by figure 3-1 below.

Figure 3-1 : The Illustration of an Array

3.1.1.9.

The String

String is a special case of array where the data type involved is character. It has to be null terminated. The term “null-terminated” represent the requirement that all presented character must be terminated by a null (‘\0’) character. The illustration is given by the figure 3-2 below.

46

Figure 3-2 : The Illustration of a Null Terminated String

In string, the null character is employed as a boundary that defines the end of a string. Functions that deal with string scanning commonly have a null character detection to determine whether the operation is terminated or not.

3.1.1.10.

The Pointer

A pointer is a special type of variable that points the address location of a variable, an array or an element of an array. Pointer is widely used in functions which use references to interchange argument. Beside pointing a variable, a pointer is also applicable to point an array, a string, a structure, a function or even another pointer. In case of array, since the elements of array are located contiguously, an action of incrementing a pointer which is initially pointed to an array will move the pointer to the next element of the array. In addition, the address of an array is equal to the address of the first element of the array itself. Dereference of a pointer is the content of the pointed address itself. The dereference operator used in C is an asterisk (*) while the operator to retrieve address is an ampersand (&).

3.1.1.11.

The Structures and Union

Structure is a set of several data types which are located contiguously and treated as a new custom data type entity. An instance of a structure will inherit members defined by the structure. The members of a structure are accessible using dot notation.

47

On the other hand, the union is exactly similar to the structure except that the members of the union are overlaid and share the same memory location [13].

3.1.1.12.

The Function

A function is a set of codes that are created to implement a particular function, processing an input data into an expected return value. Data might be supplied directly to a function by value or reference. In addition, data can be indirectly propagated to a function through global variables. Writing function is necessary to reduce repetitive task. A function can also be treated as an interface that bridges software and software as well as software and hardware. In this sense, the function is interpreted as an Application Programming Interface (API).

3.1.2. The Codevision AVR C Compiler 3.1.2.1.

An Overview

Codevision is an integrated AVR C Compiler developed by Pavel Haiduc, H.P. Infotech s.r.l. This Compiler has an integrated IDE (Integrated Development Environment), a code generator, a chip programmer, a terminal monitor and also a common device driver. The Codevision being used in this thesis is of Version 1.25.3.

3.1.2.2.

Feature

Codevision offers an attractive IDE which has code coloring and code folding. These two features will ease a programmer to code and read the program. Codevision also provides powerful project management tools as well as programming and serial debugging capability.

48

3.1.2.3.

Installation

The Codevision AVR C compiler provides an installation wizard that helps user through the installation process. The installation wizard will only ask the user to determine the installation path. The rest of the installation task will be done automatically.

3.1.2.4.

User Interface

In General, Codevision IDE main window is divided into five parts which are menu bar, toolbar, left pane, main pane and bottom pane. The left pane is responsible of providing sort of shortcut panel to access critical resource. The main panel is the place where a current opened file is displayed and edited. The bottom pane is responsible of providing compilation result and syntax errors. The Codevison IDE is illustrated by the figure 3-3 below.

Figure 3-3 : The Screenshot of Codevision IDE

49

3.1.2.4.1.

Menu Bar

Codevision has an attractive menu bar that includes File, Edit, View, Project, Tools, Settings, Windows and Help. Each of those menus has their own specific function. The contents of the menu bar and its function are shown by table 3-3 below. Menu

Function

Access Key

File

File and Project Management

Alt +F

Edit

Editing Tools

Alt + E

View

Menu, Toolbar and Dialog Management

Alt + V

Project

Project Configuration, Compilation, and Syntax Detection Alt + P

Tools

Codevision Add-on Shortcut and Management

Alt + T

Settings

Codevision Add-on Configuration

Alt + S

Windows Windows Selection and Management

Alt + W

Help

Alt + H

Help and Licensing Table 3-3 : The Menu Bar

File Menu

The file menu contains thirteen submenus which are New, Open, Reopen, Save, Save As, Save All, Close, Close Project, Convert to Library, Page Setup, Print Preview, Print, and Exit. The detail of each submenu is shown by table 3-4 below.

50

Icon

Name

Description

Access Key

New

New Project or File

Alt + F, N

Open

Open Project or File

Alt + F, O

Reopen

Reopen Project or File

Alt + F, R

Save

Save Current File

Alt + F, S

Save As…

Save Current File As

Alt + F, A

Save All

Save All File

Alt + F, E

Close

Close File

Alt + F, C

Close Project

Close Project

Alt + F, L

Convert to Library

Convert Current Project to Library

Page Setup

Setup Printing Parameters

Alt + F, G

Print Preview

Print Preview

Alt + F, V

Print

Print File

Alt + F, P

Exit

Exit from Codevision

Alt + F, X

Shortcut

Ctrl + O

Ctrl + S

Ctrl + P

Table 3-4 : The File Menu

Edit Menu

The edit menu has 23 submenus which are Undo, Redo, Cut, Copy, Copy to Code Templates, Paste, Delete, Select All, Print Selection, Indent Block, Unindent Block, Comment Block, Uncomment Block, Find, Find Next, Find Previous, Find in Files, Replace, Replace in Files, Toggle Bookmark, Jump to Bookmark, Goto Line, and Match Braces. The detail of edit sub menu is shown by table 3-5 below.

51

Icon

Name

Description

Access Key

Shortcut

Undo

Cancel Last Action

Alt + E, U

Ctrl + Z

Redo

Repeat Last Action

Alt + E, E

Ctrl + Shift + Z

Cut

Move Selected Text to Clipboard

Alt + E, T

Ctrl + X

Copy

Copy Selected Text to Clipboard

Alt + E, C

Ctrl + C

Copy to Code Templates

Copy Selected Text to Code Template

Paste

Copy Text Clipboard

Delete

from

Alt + C Alt + E, P

Ctrl + V

Clear Selected Text

Alt + E, D

Ctrl + Del

Select All

Select All Text in Current Opened File

Alt + E, S

Ctrl + A

Print Selection

Print Selected Text

Alt + E, N

Indent Block

Indent Selected Text to the Right

Alt + E, I

Unindent Block

Remove Indent Selected Text

Comment Block

Add Comment Sign -into Selected Text

Ctrl + [

Uncomment Block

Remove Comment Sign from Selected Text

Ctrl + ]

Find

Find Given String

Find Next

Go to String

Find Previous

Go to Previous Matched String

Find in Files

Find Given Several Files

Replace

Overwrite Given Text

Replace in Files

Replace Given String in Several Files

Toggle Bookmark

Toggle Bookmark

Jump to Bookmark

Jump to Bookmark

Go to Line

Go to Given Line Number

Alt + E, G

Alt + G

Match Braces

Match Braces

Alt + E, M

Ctrl + M

Next

from

Ctrl + U

Alt + E, F

Matched

String

Ctrl + I

Ctrl +F Ctrl + F3 F3

in Alt + E, R

Ctrl + R

Alt + E, B

Table 3-5 : The Edit Menu

52

View Menu

The View Menu has four submenus, including Toolbar, Navigator/Code Templates/Clipboard

History,

and

Messages,

Information

Window

after

Compile/Make. The detail of each submenu is shown by table 3-6 below. Name

Description

Access Key

Toolbar

Hide or Show Toolbar

Alt + V, T

Navigator/Code Templates/Clipboard History

Hide or Show Left Pane

Alt + V, N

Messages

Hide or Show Bottom Pane

Alt + V, M

Information Window after Compile/Make

Hide or Show Info Popup

Alt + V, I

Table 3-6 : The View Menu

Project Menu

The Project Menu has seven submenus including Check Syntax, Compile, Make, Stop Compilation, Information, Notes and Configure. The detail is shown by table 3-7 below. Icon

Name

Description

Access Key

Shortcut

Check Syntax

Check Coding Syntax

Alt + P, N

Compile

Convert Project into Intermediate

Alt + P, C

F9

Make

Convert Project into Native Hex

Alt + P, M

Shift + F9

Stop Compilation

Stop Compilation Process

Alt + P, S

Information

Show Project Information

Alt + P, I

Notes

Open Project Notes

Configure

Project Configuration

Ctrl + N Alt + P, G

Table 3-7 : The Project Menu

53

Tools Menu

The Tools Menu contains five submenus including CodeWizardAVR, Debugger, Chip Programmer, Terminal, and Configure. Since debugger is not natively available on Codevision thus it will be taken from AVR Studio. The Tools Menu is shown by table 3-8 below.

Icon

Name

Description

Access key

Shortcut

CodeWizardAVR

Open AVR C Code Generator

Alt + T, W

Shift + F2

Debugger

Open COFF Debugger (require AVR Studio)

Alt + T, D

Shift + F3

Chip Programmer

Open Chip Programmer

Alt + T, P

Shift + F4

Terminal

Open Serial Terminal Monitor

Alt + T, T

Shift + F5

Configure

Manage Add-On

Alt + T, C

Table 3-8 : The Tools Menu

Settings Menu

The Setting Menu contains five submenus to individually configure Codevision’s Add-On including Editor, Assembler, Debugger, Programmer, and Terminal. Each of those submenus will point user to setting menu of corresponding tools. The Screenshot of Settings Menu is shown by table 3-9 below. Name

Description

Access Key

Editor

Configure Editor

Alt + S, E

Assembler

Configure Assembler

Alt + S, A

Debugger

Configure Debugger

Alt + S, D

Programmer

Configure Programmer

Alt + S, P

Terminal

Configure Terminal

Alt + S, T

Table 3-9 : The Settings Menu

54

Windows Menu

The Windows Menu is used to manage several windows such as tiling and cascading. In some cases, where line by line comparison is important, horizontal tiling or vertical tiling may help much. The bottom part of help menu contains links to all files included in a project. The screenshot of Windows menu is depicted by figure 3-4 below.

Figure 3-4 : The Windows Menu

Help Menu

The Help Menu contains six submenus to view Help Topic, Tutorial, Reference, Licensing, Company Profile and Credit. Some of those menus are just shortcut to a webpage; hence it is necessary to configure internet and browser dependency issue. The screenshot of the Help Menu is shown by figure 3-5 below.

Figure 3-5 : The Help Menu

55

3.1.2.4.2.

Toolbar

Codevision’s toolbar can be categorized into eight parts which are, IDE Management, File operation, Editing, Searching, Compilation, Tools, Window Management and Help. The whole picture of toolbar is shown by figure 3-6 below.

Figure 3-6 : The Main Toolbar

The detail of each toolbar group is explained by table 3-10 below. Group Name

Icon

Function(s)

IDE Management

Show / Hide Left Pane

File Operation

New, Open, Save, Print

Editing

Undo, Redo, Cut, Copy, Paste

Searching

Find, Replace

Compilation

Check Syntax, Compile, Make, Stop Compilation, Project Information, Project Configuration

Tools

Code Wizard, Terminal

Windows Management

Tile Horizontal, Tile Vertical, Cascade

Help

Open Help Topic

Debugger,

Chip

Programmer,

Table 3-10 : The Toolbar

3.1.2.5.

Advantages

Codevision offered attractive Integrated Development, large hardware support, coding guide as well as optimized binary code. All these benefits will really helps programmer to develop software correctly, effectively and rapidly.

56

3.1.2.6.

Software Application

The Codevision AVR C Compiler takes three significant tasks which are software development, compilation and burning.

3.1.3. Hercules 3.1.3.1.

An Overview

Hercules is a hardware setup utility authored by HW group and released as freeware. Instead of its original function, Hercules is also applicable for RS232 monitoring purpose, as a replacement to HyperTerminal.

3.1.3.2.

Feature

Hercules offered connectivity to various type of protocol with simple configuration. In addition, Hercules also provided custom terminating line and connection logging for debugging-purpose.

3.1.3.3.

Installation

Hercules is portable software which does not require installation. An extracted executable Hercules file is ready for use without any prerequisites.

3.1.3.4.

Advantages

Hercules is more powerful compared to HyperTerminal. The main advantages of using Hercules came from the flexibility of configuring and establishing connection. In addition, the software is small, portable.

57

3.1.3.5.

User Interface

Hercules is dialog based software with seven specific functional tabs which are UDP Setup, Serial, TCP Client, TCP Server, UDP, Test Mode and About Tab. In this thesis, the discussion will focus on the usage of Serial Tab Only. The Serial Tab Screenshot is shown by figure 3-7 below.

Figure 3-7 : The Serial Tab Screenshot

3.1.3.6.

Software Usage

In order to use the software properly, the user has to define port location, baudrate, data size, parity type, handshaking feature and operating mode. All of those settings are available on the right side of the window. The “port name” dropdown defines the name of the serial communication port in PC which will be used to transmit and receive data. The serial port name is available from COM1 to COM100. The default port name is COM1. The baudrate dropdown is used to configure the connection speed. The connection speed is measured in bit or baud per second. Hercules supports standard

58

baudrate varying from 600 bps to 115200 bps. The available speed options are 600, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 56000, 57600 and 115200 bps. The actual byte rate is the division result between actual baudrate and 12 which represents the 8-bit data size, a start bit, a parity bit, a stop bit and a guard bit. The data size dropdown provides the number of data bits packed in a single frame. The options are available to 7 and 8-bit only. The parity dropdown size provides the configuration of a parity bit in a single data frame. According to the list of parity mode supported by Hercules software, the parity bit can be configured to none, odd, even, and mark. The “none” option will configure the Hercules software to ignore parity bit from the incoming data frame and remove the parity bit from the outgoing frame. The “odd” and “even” options will configure the Hercules software to calculate the parity bit based on the number of logic one, whether it is odd or even respectively. Last, the “mark” option will force the Hercules software to read or write all incoming or outgoing parity as a mark (“1”) signal. The handshake dropdown configures the behavior of Hercules in terms of data admission. The available options are “off”, “RTS/CTS”, and “XON/XOFF”. First, the “off” configuration will force the Hercules software to receive and transmit data without considering the RTS/CTS control signal. In the other words, a data will be automatically processed when an incoming signal is recognizable as a valid data frame. Second, the RTS/CTS configuration will set the Hercules software to consider RTS/CTS signal during a transmission. Third, the “XON/XOFF” configuration will set the behavior of Hercules software to acknowledge incoming and outgoing signal by the XON/XOFF characters which are defined in the ASCII table.

59

The last dropdown button belongs to the specific hardware that is designed to be interfaced with Hercules. In this thesis, this option is not used. The open button is used to activate connection over serial port with setting given in the right side panel. If the connection is already established, the label will change to close. The three text boxes at the bottom of the window are intended for transmitting a custom data which could be formatted as a plain text format or a hexadecimal format. The hexadecimal format is intended for transmitting the ASCII characters which are not available on the keyboard.

3.1.3.7.

Software Application

The Hercules software will be used through the testing phase of hardware and software in this thesis. The software will be mainly used to capture dumped data from the microcontroller board. In general, the test applications are connected in 19200,8,n,1 configuration.

3.2. Encryption Based Secure Communication Device

3.2.1. Overview The concept of a secure communication device is to blur up the communication signal. The main goal is to hidden the transmitted information by limiting exposure to unintended users. The blurring process can be done in many ways including frequency scrambling, encryption, and frequency hopping, and so on. In this thesis the information hiding will be focused to encryption only. Transmitted signal are encrypted into a digital form to simplify the processing. As an

60

effect, the Analog to Digital and Digital to Analog converter has to be located at the incoming and the outgoing line respectively. The encryption signal used in this thesis belongs to symmetric cipher which requires the same key to be owned by two communicating parties. As a consequence, there has to be a way to enable the two communicating parties to share and agree the secret shared key. This task will be done by the key-exchange algorithm.

3.2.2. The Idea 3.2.2.1.

Signal Quantization

Philosophically, signal quantization is a way of signal representation by means of representing analog signals in digital way so that the analog signal is digitally intelligible. Quantization is a lossy way of representing signal due to the continuous to discrete conversion issue. However this is not a big problem to deal with. The main concept of signal quantization is to translate or to associate voltage levels into binary symbols. The binary symbols are created by combining several bits so that all available outcomes can represent all expected voltage levels. The more the bit number, the smaller the voltage level gap and the more precise will the quantization be. For example, the 8-bit quantization will enable the signal to be quantized in 256 levels of signal. The combination is commonly done systematically in an ascending order, meaning that the lower voltage level will correspond to the lower binary representation. The symbol is made systematic so that the resulting binary combinations mathematically make sense mathematically. In addition, each voltage level should correspond to a unique binary symbol to maintain data integrity.

61

The quantization is commonly done in many ways, either by comparison with weighted voltage reference, iterative comparison or voltage measurement.

3.2.2.2.

Signal Compression

Since the transmitted signal mainly contains speech signal, then the term signal compression can be interpreted as speech or voice compression. The aim of the compression is to reduce the voice signal redundancy that will lead to lowering the bandwidth consumption. Compression is generally divided into lossy compression and lossless compression. Lossless compression algorithms are intended for data compression which requires data integrity. Lossy compression algorithms are intended for data compression which does not consider data integration seriously. The voice signal compression is accomplished by manipulating the way voice signal is represented, so that the amount of data required to represent the signal is minimum. Voice signal compressions are lossy since the reconstructions of a compressed signal may not be exactly the same as the original uncompressed signal. There are dozens of voice signal compression. However, they are generally constrained by the computational cost and the bandwidth size which are trade-off. The lower the resulting bandwidth size, the higher the computational cost will be. A high computational cost is valued in terms of resource and cycle time that will lead to high delay time. Due to the limitation of the hardware used in this thesis, the selection of voice signal compression will be prioritized to the one that has a low computational cost and a medium bandwidth cutback.

62

3.2.2.3.

Signal Encryption

The term signal encryption here is exclusively used for the case of voice or speech signal encryption. Encryption and decryption are actually a keyed encoding and decoding process respectively. In addition the term keyed may lead to the implementation of encryption in private and public key approach. The term “private keyed” represents the requirement of two identical keys used in ciphering and deciphering, while the “public keyed” represents the opposite. In private keying scheme, the identicality of the ciphering and deciphering key are very significant, otherwise data may not be convertible to its original. The private keyed encryption scheme generally requires less computational resource than the public keyed encryption scheme. Therefore, the encryption used in this thesis will mainly focus on the usage of private (symmetric) encryption scheme. The goal of encryption is to obscure plain data for the purpose of exposure limiting. By limiting the exposure, the coverage of sensitive information may be controlled to trusted parties only.

3.2.2.4.

Key-Exchange Algorithm

The key-exchange algorithm is actually a way to secretly exchange a shared key. An ideal key-exchange algorithm provides a secure key-exchange over an unsecure communication channel with an acceptable computational requirement. The key-exchange algorithm is used in this thesis to setup a secure communication channel. The key-exchange algorithm is generally implemented in a public keyed encryption scheme and is known to demand high computational cost. In addition, the size of exchanged key will affect the execution time proportionally.

63

Due to the limitation of hardware resource, the key-exchange will be fixed for 128-bit key-exchange only.

3.2.3. The Advantages The advantages of processing signal in digital form are listed below.



Cheaper Digital signal processing is commonly cheaper than analog signal processing. The main reason is because the flexibility of the programmable device that can natively handle digital signal as well as its ability to masquerade signal processing in software which is low cost. In addition, the component count will be lower since almost all signal processing are implemented in software which is space effective.



More Flexible Since the digital signal are processed by a programmable device then the current implemented signal processing algorithm can be changed or updated easily without worrying about the hardware replacement issue.



More Robust Digital signals are generally more robust than analog signals. The main reason is that digital signals have two discrete levels which

64

are separated by a noise margin. The noise margin will ensure that the digital signal is almost noise resistant.

3.3. Device Development

3.3.1. Functional Analysis The aim of functional analysis is to collect the functional requirements of an ideal cryptophone secure communication device. The requirements include the device behavior and capabilities. The result of this step includes general ideas that describe the device a functional view. The resulting requirements are: ƒ

The device has to be able to interface a telephone line

ƒ

The device has to be able to modulate and demodulate the standard modulation used in the communication over a telephone line.

ƒ

The device has to be able to capture and generate voice signal

ƒ

The device has to be able to provide basic functionality of a telephone such as dial, hook on, hook off, ring detection, call wait and so on.

ƒ

The device has to provide basic user interface such as keypad and LCD

ƒ

The device has to be able to provide A/D and D/A conversion

ƒ

The device has to be able to encipher and decipher digitized voice signal

ƒ

The device has to be able to provide basic secure key-exchange process

ƒ

The device has to be able to support pseudo-random number generation

ƒ

The device may support advanced functionality of telephone line such as voice recording, caller detection, call log, phone book, black listing and so on.

ƒ

The device may support advanced cryptographic functionality such as selectable key length, selectable cipher algorithm as well as advanced secure key-exchange process.

65

3.3.2. Resource Analysis The aim of this step is to summarize the chance of implementation in terms of device limitation and feature. The result will limit the ideal specification given by functional analysis to outfit available resource given by the chosen programmable device. The programmable device used in this thesis is AVR ATMega32, thus the constraints are given below. ƒ

All algorithms have to be implemented in native byte processing or implementable in byte processing.

ƒ

The ATMega32 does not support standard modulation such as V90 and V92; however it supports TTL level asynchronous communication.

ƒ

The ATMega32 does not support native telephone line interfacing.

ƒ

The ATMega32 support basic user interface handling such as keypad and LCD.

ƒ

A/D and D/A conversion can be implemented natively in ATMega32.

ƒ

All binary implementations have to be mounted in at most 32 Kbyte of flash memory.

ƒ

All processing have to be implementable in 2 Kbyte of RAM.

3.3.3. Prototyping This step summarizes the approach of implementing the cryptophone secure communication device based on the ideal specification given by the functional analysis compromised with the constraints given by the resource analysis. The approach towards the cryptophone secure communication device is outlined below.

66

ƒ

Telephone line interfacing, modulation and demodulation are introduced using an external modem connected to ATMega32 through an asynchronous serial connection.

ƒ

The TTL level asynchronous communication of the microcontroller is interfaced to the RS-232 level asynchronous communication of the external modem using a TTL/RS-232 level converter.

ƒ

The user interface is implemented as an LCD and keypad, connected through the GPIO ports.

ƒ

Telephone line events are detected by the external modem and handled by ATMega32 microcontroller.

ƒ

The A/D and D/A processing is implemented natively using ATMega32 with the addition of lowpass filter and pre-amplifier.

ƒ

Ciphering and deciphering are implemented in software using the RC4 stream cipher algorithm which is byte-oriented and lightweight.

ƒ

The voice compression algorithm is implemented in software using the 4-bit ADPCM which can be done in byte-oriented operation.

ƒ

The key-exchange algorithm is implemented using the Diffie-Hellman keyexchange Algorithm which is applicable to 8-bit systems with the addition of integer arithmetic tricks.

3.3.4. Sub-circuit Development The sub-circuits required by the cryptophone secure communication device is listed below. ƒ

Preamplifier and lowpass filter for microphone amplification and anti aliasing.

ƒ

RS-232/TTL voltage converter circuit for external modem interfacing

67

ƒ

Lowpass filter for filtering of the resulting audio signal.

ƒ

Power amplifier for driving the loudspeaker.

ƒ

4x4 keypad and LCD module for user interface purpose.

3.3.5. Kernel Application Development Kernel applications are applications that provide low level access to a certain hardware module and software module. The required kernel applications are listed below: ƒ

The 4x4 Matrix keypad driver

ƒ

The LCD driver

ƒ

The ADPCM voice codec

ƒ

The The RC4 stream cipher

ƒ

The Diffie-Hellman Key-Exchange Module

ƒ

The pseudo-random Number Generator Module

3.3.6. Sub-circuit Integration In this phase, sub-circuits and their drivers are tested and integrated. The aim of this phase is to verify that all sub-circuits and their drivers are combinable without any problem.

3.3.7. User Application Development The user application development is focused on the high level implementation of the cryptophone secure communication device. The development is directed to manipulate the behavior of the developed device to suit the actual implementation.

68

3.3.8. Quality Assurance Finally,

the

quality

assurance

verifies

all

hardware

and

software

implementation. In ideal situation, the test is supposed to be performed in several cases including normal case, error case, and stress case. Normal case tests are tests applied to verify whether the implementation runs properly under normal condition, without any error occurred. Philosophically, a right treatment should lead to a correct result. An error case test is the opposite of a normal case test where the implementations are treated in a wrong way. The test is performed to verify that the device is fault tolerant, meaning that the wrong usage of the device will not cause a significant harmful result. The stress test is basically a normal test which is iterated massively. This test is performed to verify the implementation stability. However, due to time and resource limitation, this thesis only geared to the basic qualitative normal test to verify the implementation.

69

CHAPTER IV DESIGN AND IMPLEMENTATION

4.1. An Overview

The design and implementation phase in this thesis will be mainly divided into two sections which are the hardware part and the software part. Hardware and software are developed separately in modular way to simplify the debugging process. The software module is designed to be reusable and open for further development. The hardware development will be started by constructing an analog interface related to ADC and PWM and consequently followed by the construction of RS232/TTL level converter. In fact, some of software tests may require a particular hardware to work properly, therefore it is important to construct and verify hardware module at the beginning. In addition to the device development, the software development is mainly divided into the kernel space development and the user space development. The user kernel is the space where the application can gain high level access to the supporting software modules located on it. While in the user space, the application focuses on the management of the whole device functionality. On the other side, the supporting modules (such as device drivers) which are located on the kernel space have to perform low level access to the hardware or some specific operations such as RC4 stream cipher, Pseudo-random Number Generator (PRNG), and so on. By separating the software into kernel space and user space, the software part of the device development can be focused on the functionality of the device as a whole without worrying the low level tasks, once the kernel space applications are

70

verified. The Illustration of Kernel Application, User Application and Hardware Module is shown by figure 4-1 below.

Figure 4-1 : The Illustration of Kernel Application, User Application and Hardware Module

Some parts of the software development have a strong relation to the hardware development, due to the interfacing issues, meaning that a particular hardware has to be interfaced in a systematic way. This is implemented by the hardware driver and specified by the hardware datasheet. All in all, the application software is connected to the hardware through the Application Programming Interface (API) which is provided by the hardware driver. The indirect hardware handling (i.e. via driver) is intended for the software reusability purpose. The connection between the application software, the hardware driver and the hardware itself is illustrated by figure 4-2 below. 71

Figure 4-2 : The Relation between Application Software and Hardware Connected Through Driver

4.2. The RC4 Stream Cipher Module

4.2.1. An Overview From the RC4 specification it is clear that an implementation of the RC4 stream cipher requires an initialization and a pseudo-random byte generation routine. The initialization routine is necessary to prepare a virgin RC4 inner state and to process the supplied cipher key which in turn will modify the initialized RC4 inner state buffer. The RC4 stream cipher uses 256 cells of byte array as its inner state, which will be kept modified during the initialization and the usage. The inner state of the RC4 defines the state that will affect the sequence of the generated byte stream. The RC4 module will be interfaced to the application software by using two

Application Programming Interfaces (APIs) for the initialization (RC4_init) and the byte stream generation (RC4_out). The illustration is shown by figure 4-3 below.

72

Figure 4-3 : The Interface of RC4 Stream Cipher Module

4.2.2. Functional Requirement Since the inner state must be accessible, modifiable, and resident to both the initialization and the generation routine, it is important to define the design constraint and the characteristics of the RC4 inner state implementation. The design constraint and the implementation characteristics are shown by table 4-1 below. Design Constraint

Implementation Approach

Cell of 256 bytes

Array of Byte

Modifiable

Located on SRAM

Accessible from several function Global Variable Table 4-1: The Design and Implementation of the RC4 Inner State Buffer

4.2.3. The RC4 Stream Cipher Initialization The initialization process of the RC4 stream cipher can be explained into two processes entitled: “the inner state buffer initialization” and “the inner state buffer pseudo-randomization”, which are based on the supplied cipher key. Those two processes are necessary to prepare the inner buffer state before any stream generation process.

73

4.2.3.1.

The Inner State Buffer Initialization

The inner state buffer initialization is the process of filling up the inner state buffer by an increasing value from 0 to 255 (i.e. 0x00 to 0xff in hexadecimal). After the inner state buffer initialization is completed, the leftmost cell is loaded with 0 and the rightmost cell is loaded with 255. Since this process is repetitive, it can be simplified into a loop that will increase an incrementing variable from 0 to 255 while loading it into the inner state buffer pointed by itself. The flow chart of the inner state initialization is depicted by figure 4-4 below.

Figure 4-4 : The Flowchart of the RC4 Inner State Buffer Initialization

4.2.3.2.

The Inner State Pseudo-randomization

The inner state buffer pseudo-randomization is a process of scrambling an initialized RC4 inner state buffer by processing a given cipher key using an algorithm defined by the specification of RC4 cipher. The scrambling process is made of cells swapping and pseudo-random pointer, updating that task repetitively along the RC4

74

inner state buffer. This means that the pseudo-randomization will apply to all cells inside the inner state buffer. Since the process is repetitive from the leftmost up to the rightmost index of the cells, the pseudo-randomization process can be simplified into a loop that will increase an incrementing variable from 0 to 255 while swapping the cell pointed by it and the other cell pointed by it also. In addition, the pseudo-random pointer is updated iteratively inside the loop by adding the current pointed cipher key and the current pointed cell by the incrementing variable into the previous value of the pseudorandom pointer. Since the length of the key is allowed to be variable from 0 to 255, it is important that the current pointed cipher key is indexed by the result of modulo taken from the incrementing variable and the length of the given cipher key. Since the overall initialization process of the RC4 inner state buffer uses a cipher key and a cipher key length, it is clear that the initialization routine of the RC4 inner state buffer will take two arguments which are the pointer to the supplied cipher key and the length of the supplied cipher key with the assumption that the cipher key is given by reference. In order to simplify the implementation, the argument supplied to the initialization function is assumed to be always true and the output of the inner state buffer initialization can be set to void. The implementation of inner state buffer initialization of RC4 stream cipher is described by snippet 4-1 at appendices section.

4.2.4. The Pseudo-random Generation Algorithm (PRGA) The PRGA routine of the RC4 consists of two processes which are the cell content swapping and the dereferencing of a pointer to the inner state buffer as the resulting pseudo-random byte stream. The PRGA routine is the interface between the

75

RC4 stream cipher module and a part of the application software that requires random byte stream. The cell content swapping of the inner state buffer is done by exchanging the content of two cells of the inner state buffer pointed by the incrementing variable and the accumulating variable. The incrementing variable will be increased on every execution of the PRGA routine and must be resided in the routine during and after the execution. The accumulating variable will be updated on every execution of the PRGA routine and must be resided in the routine during and after the execution. In addition, the update process of the accumulating variable is done by adding the current inner state buffer content pointed by the incrementing variable into the previous value of the accumulating variable by ignoring any occurred overflow. The dereferencing process is done by treating the result of the addition between the content of the inner state buffer pointed by the incrementing variable and the content of the inner state buffer pointed by the accumulating variable as another pointer to the inner state buffer. Afterwards, the pointed content is returned as the pseudo-random byte stream generated by the PRGA routine, which is mathematically described as s[s [i ] + s[ j ]] . In fact, the overall PRGA routine requires that the accumulating and the incrementing variable must reside inside the routine, meaning that the last value of the incrementing and the accumulating variable have to be available for the next function call. Prior to that requirement, it is clear that the accumulating and the incrementing variables must be declared inside the routine with the addition of “static” storage class modifier. The flowchart of PRGA routine is shown by figure 4-5 below.

76

Figure 4-5: The Flow Chart of the RC4 Pseudo-Randomization Generation Algorithm

The implementation of the PRGA routine is described by the snippet 4-2 at appendices section.

4.3. Pseudo-random Number Generator

4.3.1. An Overview The Pseudo-random Number Generator (PRNG) module is a software module that contains a routine for generating 16 bytes random numbers. The PRNG software module is a kernel application that bridges the high level access required by the application software and the low level access accepted by the ADC. On the other hand, this kernel application will translate the low level 8-bit byte stream into 16 bytes of byte stream formatted as hexadecimal string. The resulting hexadecimal string buffer is passed to the application through reference, meaning that the only clue given to the caller is the address of the buffering destination. The PRNG module is interfaced to the application software through the application programming interface (API). The interfacing scheme is shown in figure 4-6.

77

Figure 4-6: The Interfacing Scheme of PRNG Module

A PRNG module is significant for generating random exponent for calculating shared key that will be used by the RC4 stream cipher in both communicating sides. The generated secret exponent must be random enough to protect the key that will be shared to both communicating sides.

4.3.2. The Source of Random Number A pseudo-random number sequence can be generated naturally or artificially. A natural number sequence can be obtained by measuring an analog signal which has small regularity and very long period. On the other hand, an artificial random number generation uses a specific algorithm that results a number sequence with a large period. The measurement (quantization) of analog signal can be done by an Analog to Digital Converter (ADC). This means, that the source of the random variable implemented in this thesis might be taken from the C library or the ADC sampling result. The pseudo-random number generation provided by C is available in the standard library (stdlib.h). The experiment shows that the pseudo-random number taken from the ADC sampling result exhibits a better randomness compared to the pseudo-random number taken from the algorithm given by the C compiler. The one taken from the ADC

78

sampling result shows more irregularity. Hence, the pseudo-random number generator used in this thesis uses the ADC sampling result as the source.

4.3.3. The Functional Requirements Since the PRNG module will be mainly interfaced to the Diffie-Hellman module, while the Diffie-Hellman module requires incoming number to be formatted as string of hexadecimal characters, the output of the PNRG module must follow the requirements given by the Diffie-Hellman module. In addition, the source of the random number must be taken from the ADC sampling result. There has to be a way to copy and synchronize the data produced by the ADC.

4.3.4. The Implementation In order to ease the debugging process, the source of the PRNG is made selectable by activating and deactivating the USE_ADC_PRNG definition. To avoid any definition misinterpretation, the USE_ADC_PRNG definition has to be declared in the beginning, before the decision is made through the definition evaluation. The core process is about copying the 8-bits ADC sampling result into the buffer, which is iteratively implemented in a loop. In addition, the loop also implements a mechanism that will wait until a fresh data is available as well as a nonzero sample in the beginning. The flowchart is given in figure 4-7.

79

Figure 4-7: The Flowchart of Pseudo-Random Number Generation Routine

Since the PRNG module does not require an initialization step, the implementation of the PRNG module will contain a single function only. Moreover, the PRNG routine is only focused on the hexadecimal byte stream by collecting and translating the received sampling signal from the ADC. The detail implementation of the PRNG is described using a C code snippet 4-3.

4.4. The Keypad Hardware Module and Driver

4.4.1. Keypad Hardware Module The 16 buttons of the keypad can be effectively interfaced as a 4x4 matrix. Each key is located in the intersection of every row and column. The concept is to

80

assume either the column or the selector as the input and perform a bit-by-bit scanning with the assumption that the button pressed will conduct electricity from the incoming line to the outgoing line. Technically speaking, the detection can be easily done by activating the particular column and reading the activated row. All column and row selectors are pulled up to guarantee that the floated circuit has a logic one and the selected (activated) line will has a logic zero. The keypad hardware module is shown in figure 4-8.

Figure 4-8: The Schematic of Keypad Hardware Module

4.4.2. Keypad Driver 4.4.2.1.

An Overview

Basically, a matrix keypad driver is software which is designed to sense the mechanical change of the buttons packed in a 4x4 matrix package. In other words, a matrix keypad driver has a duty to interpret the positional symbol given by the matrix into an intelligible symbol known by the application software.

81

The pressed button is defined by the intersection of a column and a row. The intersection of the column and the row is detected by supplying a zero logic to a particular column selector and detecting the resulted zero logic from the row, taking the column selector as the input and the row selector as the output. For example, to detect the intersection of column 3 and row 2, the program has to send a logic zero to the 3rd column selector and detect a logic zero only from the 2nd row selector. Note that the scanning method also works with the inverted configuration, meaning that the row selector can be set as the input and the column selector as the output. In order to access the matrix keypad hardware, the application software has to access the hardware driver that provides a scheduled scanning, and a symbol translation. The Interfacing Scheme of Matrix Keypad Driver is shown by figure 4.9.

Figure 4-9: The Interfacing Scheme of Matrix Keypad Driver

4.4.2.2.

The Functional Requirement

Philosophically, the whole keypad must be scanned line by line, meaning that there must be a routine that periodically supply the column selector with zero logic, one by one, without disturbing the ongoing process handled by the application software.

82

Prior to the compatibility issue, there must be a way to convert the button symbol mapping into an intelligibly shape. In addition, the matrix keypad driver must interpret pressed button properly without worrying the bouncing effect. The translation from the positional symbol to the character has to be done in a customizable way for reserved future use.

4.4.2.3.

The Implementation

In order to simplify the task handling, the keypad scanning is placed inside a timer interrupt. The timer rate is set to a particular value so that it will overflow and trigger the interrupt routine in a fixed time period. In this thesis, the keypad scanning rate is set at 500 per second. In addition, the debouncing process is done by adding the released and pressed counter which are set to 20 and 10 respectively. Since the scanning data must be retained between the key scanning period, all variable related to the key scanning has to be declared as static. Generally speaking, the whole keypad driver is divided into three routines which are the keypad initialization, the keypad read, and the keypad interrupt routine. The interrupt initialization initializes timer2 to a given setting such that it will trigger the interrupt for 500 times per second. The keypad read routine will translate the returned keypad mapping symbol into an intelligibly form defined in the lookup table. The implementation of the keypad driver is shown in a C code snippet 4-4.

4.5. The M1602 LCD Hardware Module and Driver

4.5.1. The LCD Hardware Module The LCD hardware module interfaces the M1602 LCD module to the ATMega32 using the Codevision LCD interface standard. The standard is made to

83

synchronize the LCD driver provided by the Codevision AVR C Compiler to the hardware configuration. The standard employs the M1602 LCD in the 4 bit interface mode, with reading capability enabled. The configuration of the standard LCD interface is shown in table 4.2 Pin Number

Pin Name

ATMega32

Pin Number

Pin Name

ATMega32

1 2 3 4

GND VCC VLCD RS

GND VCC GND PB0

9 10 11 12

D2 D3 D4 D5

PB4 PB5

5 6 7 8

RW E D0 D1

PB1 PB2

13 14 15 16

D6 D7 LEDVCC LEDGND

PB6 PB7 VCC GND

Table 4-2 : The Connection of LCD Hardware Module to ATMega32

4.5.2. The LCD Driver The implementation of the LCD driver is actually provided by the Codevision AVR C Compiler. In order to bridge the software provided, Codevision provides an interface which is accessible to the user of the software called LCD Application

Programming Interface (API). In order to be able to use the LCD APIs, an application software must include a header file entitled “lcd.h”. It is also necessary to define the number of column available in the hardware LCD and the port location where the LCD is connected, to ensure that all APIs run properly. The LCD API provided by Codevision support a wide range of LCD, including 1x8, 2x12, 3x12, 1x16, 2x16, 2x20, 4x20, 2x24, and 2x40. All of those types of LCD can be interfaced as long as it follows the interfacing standard given by Codevision.

84

API is divided into two groups which are the high level API and the low level API. The low level LCD API is intended to gain fundamental access to the LCD, while the high level API is just the encapsulation of several low level APIs that are more familiar to user. The low level and high level APIs are described in a table 4.3. L/H

Description

void _lcd_ready(void)

L

Waits until the LCD module is ready to receive data. This function must be called prior to writing data to the LCD with the _lcd_write_data function.

void _lcd_write_data(unsigned char data)

L

Writes the byte data to the LCD instruction register. This function may be used for modifying the LCD configuration.

unsigned char lcd_read_byte(unsigned char addr)

L

Reads a byte from the LCD character generator or display RAM.

unsigned char lcd_init(unsigned char lcd_columns)

H

Initializes the LCD module, clears the display and sets the printing character position at row 0 and column 0. The numbers of columns of the LCD must be specified (e.g. 16). No cursor is displayed. The function returns 1 if the LCD module is detected and 0 if it is not. This is the first function that must be called before using the other high level LCD Functions.

void lcd_clear(void)

H

Clears the LCD and sets the printing character position at row 0 and column 0.

void lcd_gotoxy(unsigned char x, unsigned char y)

H

sets the current display position at column x and row y. The row and column numbering starts from 0.

void lcd_putchar(char c)

H

Displays the character c at the current display position.

void lcd_puts(char *str)

H

Displays at the current display position the string str, located in SRAM.

void lcd_putsf(char flash *str)

H

Displays at the current display position the string str, located in FLASH.

API

Table 4-3: The Codevision LCD API

85

4.6. Diffie-Hellman Key-Exchange Algorithm

4.6.1. An Introduction In fact, the calculation used in the Diffie-Hellman key-exchange algorithm uses large numbers which are not natively supported by the microcontroller. As an effect, the large number calculation will be implemented using the integer arithmetic. The core concept of integer arithmetic is to decompose the powering calculation into squaring and multiplication. A multiplication, in this case, is decomposed into shifting and addition. The decomposition concept above can be explained heuristically through the equation 4-1 below.

47 x = 32 x + 8 x + 4 x + 2 x + 1 x 47 = x ( 32 +8+ 4+ 2+1) = x 5 ⋅ x 3 ⋅ x 2 ⋅ x 1 ⋅ x 0

Equation 4-1: The Illustration of Multiplication Decomposition Since the RC4 stream cipher used in this thesis will be configured to use a 128-bit cipher key, the default number bit used in the cipher key is 128-bit. It causes the width of g, e, and m key buffer are fixed to (8+1) bytes. The additional byte is given as the buffer boundary during a calculation. The implementation of the Diffie-Hellman key-exchange algorithm would use several routines including initialization, addition and subtraction, adjustment, right shifting, multiplication, hex to binary conversion and vice versa. The interfacing scheme between the application software and the Diffie-Hellman key-exchange Algorithm module is shown in figure 4-10.

86

Figure 4-10: The Interfacing Scheme of DHKEA Module

4.6.2. Functional Requirement Routines involved in the Diffie-Hellman key-exchange Algorithm can be summarized into shifting, addition and adjustment. In addition, the higher level computations such as multiplication and exponentiation are built in the primitive routines. This is the reason why the routines involved in Diffie-Hellman KeyExchange Algorithm have to reuse its primitive functions to construct higher function, for the sake of simplicity and effectiveness. The illustration is shown in figure 4-11.

Figure 4-11 : The Function Reusability Structure of Diffie-Hellman Routines

The calculation would now be expensive in terms of number of cycle. Therefore, primitive routines have to be optimized to skip unnecessary steps.

87

For the sake of reusability, the adding module is implemented in y = a + bx form. The variable x is added as a sign modifier (i.e. it is also applicable for subtraction). In fact, the variable x is only used to store either 1 or -1. When the sign modifier turns to negative, the addition will automatically translated into a subtraction.

4.6.3. The Addition Routine The addition routine scans and adds two key buffers from right to left, from the least significant byte to the most significant byte. It adds lower order byte and automatically process overflows when occurred. The flowchart of the addition routine used in the implementation of the DiffieHellman key-exchange algorithm is depicted by the figure 4-12 below.

Figure 4-12 : The Flowchart of Addition Routine Used in DHKEA

88

4.6.4. The Adjustment Routine The main function of the adjustment routine is to adjust the result of the whole calculation in such a way that it will not be greater than the modulo value given on the

m buffer. The adjustment routine requires a byte-by-byte scanning from the leftmost byte (most significant byte) to the rightmost byte (least significant byte). A subtraction by modulo is necessary when the resulting value determined is greater than the modulo itself. Since one-by-one comparison and subtraction is expensive in term of cycle time, it is a good idea to start the processing by scanning m buffer and the temporary buffer from left to right to skip the corresponding bytes of m buffer and the temporary buffer with the same content, and begin the comparison at two corresponding byte in the m buffer and the temporary buffer which is not equal to zero but greater than or equal to the corresponding temporary buffer. In addition, it is also a good practice to adjust the result of all calculation just after the calculation performed. This is meant to avoid the needs of a dedicated adjustment loop which take additional cycle time. The flowchart is given by the figure 4-13 below.

89

Figure 4-13 : The Flowchart of Result Adjustment in DHKEA

4.6.5. The Right Shifting Routine The next important thing in the Diffie-Hellman key-exchange algorithm is to scan the bit stream from right to left. This scanning is necessary to decide whether and addition and a multiplication are required in the multiplying and the squaring process respectively. The approach to the bit stream scanning used in this thesis is to right shift the scanned byte array and to mask the rightmost bit. The illustration is depicted by the figure 4-14below.

Figure 4-14: The Illustration of Bit Stream Scanning by Byte Right-Shifting

90

The practical approach of the byte right-shifting also requires an overflow bit handling to avoid data loss. The overflow bit generated by the shifting result is supposed to be propagated to the current pointed cell. This approach is completed because the byte array is actually a collection of registers that are located contiguously in a given area of the RAM. Although the theoretical byte array shifting is not natively available in microcontroller, there is a trick to solve the problem. The solution is by emulating byte array shifting into several chained byte shifting. The illustration and flowchart are given by the figure 4-14 and 4-15 respectively.

Figure 4-15: The Illustration of Byte Array Shift Emulation

Figure 4-16: The Flowchart of Byte Array Shift Emulation

91

4.6.6. The Multiplication Routine The next fundamental processing related to the key-exchange algorithm is multiplication. This routine is implemented in form of conditional iterative addition of particular weighted number. The multiplication routine itself is the encapsulation of the addition, the shift-right, and the adjustment. The unit left-shifting or multiplication by two is virtually implemented by using addition of two identical values. To maintain the nature of the modular operation, all addition processes are subsequently followed by adjustment task to ensure that resulting operation will not exceed given modulo value.

4.6.7. The Implementation The whole and actual implementation of DHKEA is given by the snippet 4-5 at appendices section.

4.7. ADC Hardware Module and Driver

4.7.1. The ADC Hardware Module The ADC Module is natively available in the AVR ATMega32. The ATMega32 supports 8 channel of 10-bit ADC with customizable configuration. The complete features of ATMega32 are listed by the 4-4 table below.

92

Feature

Value

Resolution

10-bit

LSB Integral Non Linearity

0.5

LSB Absolute Accuracy

±2

Conversion Time

13 – 260 µs

Speed at maximum resolution

Up to 15kSPS

Single Ended Channel

8

Differential Input Channels

7

Differential Input Channel with Gain

2

Customizable result alignment

Yes

Input Voltage Range

0 to 5V

Customizable Running Mode

Yes

Interrupt on Complete Conversion

Yes

Table 4-4: The Characteristics of ATMega32 Analog to Digital Converter

In order to be able to use the ADC properly, a user application has to configure the part of PORTA that is used for the sampling line as input. Furthermore, a user application has to configure the selected channel, type of voltage reference, the ADC enabling flag, the ADC interrupt flag, the ADC clock prescalar, the ADC alignment mode and the Auto Trigger enabling flag. All of these configurations are available in several register entitled ADMUX, ADCSRA, and SFIOR. The detail of each register can be investigated at ATMega32 datasheet. The 10-bits sampled and quantized data can be taken on ADCH and ADCL registers depending on the type of alignment selected. If the right alignment is selected, the lower 8 bits will be located in ADCL and the rest 2 leftmost bits will be available in 2 rightmost bits of ADCH. If the left alignment is selected, the 8 leftmost bits will be provided in ADCH and the 2 rightmost bits will be available in the 2 rightmost bits of ADCL. In this thesis the type of alignment used is the left alignment

93

since the sampled data will be processes in a byte-oriented processing. The relation between the data placement and the types of alignment is depicted on figure 4-17.

Figure 4-17: The Relation between Data Placement and Types of Alignment

In this thesis, the internal ADC is engaged in the auto trigger mode to attain constant sampling rate of 8 KHz, while the triggering source is taken from the overflow of timer0.

4.7.2. ADC Driver Regarding the issue of constant sampling rate and auto trigger, it is now becoming clear that an ADC driver module must process the features listed by the table 4-5. Feature

Implementation

Init ADC

Initialize ADMUX, ADCSRA and SFIOR

Shutdown ADC

Clear ADCSRA

Enable ADC Scheduler

Initialize TCCR0 and TIMSK

Disable ADC Scheduler

Clear TCCR0

Constant 8KHz Sampling Rate

Reinitialize timer0 on timer0 interrupt

8KHz Synchronization

Set synchronization flag on timer0 overflow interrupt

Fresh ADC Data Synchronization

Set synchronization flag on complete conversion interrupt

Real-time Sampling

Sampled and quantized data will be copied to buffer on complete conversion interrupt

Retrieve Sampling Data

Return ADC data buffer

ADC data buffer must be accessible to several routine

ADC buffer must be declared as a global variable

Table 4-5: ADC Driver Software Design Requirement

94

The implementation of the ADC driver is described by the snippet 4-6.

4.8. PWM-based DAC Hardware Module and Driver

4.8.3. The PWM-based DAC Hardware Module The internal timer of ATMega32 can be configured to work in PWM mode by setting TCCR1A and TCCR1B registers. In addition, it is also necessary to set the pin connected to the timer output as output, to ensure that the duty cycle change of the timer output can be transferred properly. In this thesis, the internal timer configured to work in PWM mode is the timer1, configured in fast PWM mode with 62.5 kHz PWM frequency. A high frequency is chosen to reduce noise from PWM in idle mode. In PWM mode, the output of timer1, in this case OC1B, will be cleared once the counting value of Timer1 is the same as the top value given to OCR1B register. The whole result of this cycle is the change of duty cycle of OC1B pin which will affect the average voltage.

4.8.4. The PWM-based DAC Driver The routine required to handle the PWM-based DAC deal with the activating and the deactivating of timer1. The process of setting up the duty cycle is as simple as initializing OCR1B with an expected value. The implementation of the PWM-based DAC is shown by the snippet 4-7.

4.9. ADPCM Voice Compression Module

The ADPCM voice compressor module is a software module that enables ATMega32 to compress the sampled voice to decrease bandwidth consumption. The

95

ADPCM is selected because it is easy to implement, require less computing power, fast, and requires less microcontroller resource. The ADPCM voice codec is implemented in three parts which are ADPCM initialization, ADPCM encoding routine and ADPCM decoding routine. The encoding routine will compress the supplied data and send the compressed data as necessary. In addition, the decoding routine will decompress and send the decompressed data to PWM to produce the analog signal. Since the encryption process is applied at data which is already encoded by ADPCM module, it is important to note that both ADPCM encoding and decoding routine require the pseudo-random byte stream taken from the RC4 PRGA routine. The implementation of the ADPCM is shown by the snippet 4-8.

4.10. Modem Driver

The modem driver consists of a set of AT Command which is bundled in a module to support the work of the secure communication device, starting from the modem initialization up to the dialing instruction. The driver is mainly dealing with the high level access to the external modem such as dialing, hook setting, peripheral setting, and event detection.

4.11. Microphone Preamplifier

The microphone preamplifier is an application amplifier that enables the amplification of the microphone signal. Since the output of the microphone preamplifier is directly connected to the ADC sampling line, therefore it is important to add low pas filter to limit the bandwidth of incoming signal to avoid anti-aliasing.

96

The amplifying function of the circuit is completed using the LM324 Op-Amp that is configured to work as a first-order inverting difference lowpass filter with variable gain setting. The incoming microphone line is pulled up in case of the condenser microphone usage. The non-inverting input of the Op Amp is connected to the adjustable voltage reference to remove the DC component. It happens by amplifying the difference between the incoming signal and the reference signal given by a voltage divider connected to the non inverting input. The used schematic is based on the previous work done by Jim George, Gautham Krishnamurthy and Venkatesh HB

[4]

. The schematic is given by the figure

4-18 below.

Figure 4-18 : The Schematic of Microphone Preamplifier

The output voltage is defined by

R ⎛ ⎞ ⎜ 1 + jωR2 C 2 + 2 ⎟ R4 ⎟ R v o = 4 ⎜⎜ vi ⎟ R3 H R2 1+ ⎜⎜ ⎟⎟ R3 L ⎝ ⎠

Equation 4-2 : The Calculation of Output Voltage of Microphone Preamplifier 97

At maaximum gain n, the cutoff frequency of o the active lowpass l filteer is

ωc =

1 1 = 1693 6 .14 Hz = 2πRC 2π ⋅ 200000 ⋅ 4470e −12

(

)

Equation 4--3 : The Cuttoff Frequency of Micropphone Pream mplifier

The cu utoff frequenncy of the paassive lowpaass filter is ggiven by:

ωc =

1 1 = 33886.28 Hz = 2πRC 2π ⋅ 10000 ⋅ 4.7e −9

(

)

Equation 4-4 4 : The Cuutoff Frequenncy of Passivve Lowpass Filter

4.12. RS232-TTL Leveel Converteer The RS232 R to TT TL conversion and vicee versa is im mplemented by using tw wo M MAX232 chiips. One MA AX232 contaains two unitts of driver aand two unitts of receiveer. T conversio The on is not appplied to all RS232 R signaals due to thhe pin and chhip limitationn. T schematiic is shown below. The b

Figurre 169 : The RS232/TTL L Level Convverter

4.13. PWM Lowpass Filter

The PWM lowpass filter is built from 3 stages of active lowpass filter to attain a higher order lowpass filter. The first stage is the first order lowpass filter which is buffered by the voltage follower circuit. The second and the third stage are the Sallen–Key second order lowpass filter with inverting unity gain. The overall filter is a 5th order Chebyshev active filter. The schematic used in this thesis is based on the previous work done by Jim George, Gautham Krishnamurthy and Venkatesh HB

[4]

. The author stated that the

circuit was designed using FilterWiz Pro and verified to work at 3.8 KHz cutoff frequency. The schematic is shown below

Figure 170 : The PWM Lowpass Circuit

The calculations related to the above circuit are given by the following equations. fc1 =

Q2 =

fc 2 =

1 1 = = 2132.87 Hz 3 2πRC 2π ⋅ 91 ⋅ 10 ⋅ 820 ⋅ 10 −12

(

R1 R2 C1C 2

C1 (R1 + R2 )

)(

)

(15 ⋅ 10 )(100.10 )(10 ⋅10 )(100 ⋅10 ) = 33.68 ⋅10 (10 ⋅ 10 )([ 15 ⋅ 10 ) + (100 ⋅ 10 )] 3

=

1 2π R1 R2 C1C 2

−9

=

(

−9

3

3

)(

−12

−3

3

1

)(

)(

3 3 −9 −12 2π 15 ⋅ 10 100.10 10 ⋅ 10 100 ⋅ 10

)

= 4109.36 Hz

99

H 2 (s ) =

(2πfc2 )2 fc 2 2 s + (2πfc 2 ) Q

s 2 + 2π

C1 (R1 + R2 )

fc3 =

=

1 2π R1 R2 C1C 2

H 3 (s ) =

(10 ⋅ 10 )(91.10 )(5.6 ⋅ 10 )(560 ⋅10 ) = 94.45 ⋅ 10 (5.6 ⋅ 10 )([ 10 ⋅ 10 ) + (91 ⋅10 )] =

−9

3

−9

3

−12

1

fc 2 2 s + (2πfc3 ) Q

=

−3

3

3 3 −9 −12 2π (10 ⋅ 10 )(91.10 )(5.6 ⋅ 10 )(560 ⋅ 10 )

(2πfc3 )2 s 2 + 2π

666.66 ⋅ 10 9 s 2 + 766.62 ⋅ 10 3 s + 666.66 ⋅ 10 9

3

R1 R2 C1C 2

Q3 =

=

= 2979.28 Hz

350.41 ⋅ 10 6 s 2 + 198.19 ⋅ 10 3 s + 350.41 ⋅ 10 6

Equation 4-5 : The Calculations of The PWM Lowpass Filter

4.14. Power Amplifier

The core of the power amplifier circuit is a low voltage audio power amplifier chip named LM386. The LM386 chip is configured to work at a gain of 20 in minimum external components. The circuit is mainly divided into volume control, power amplifier, and zobel (a.k.a. boucherot cell). The volume control is basically made of a potentiometer configured as a variable voltage divider. A decoupling capacitor is engaged at the input pin to block the DC component. The zobel circuit is actually a series resistor and capacitor parallel to the connected loudspeaker. The function of the zobel circuit is to compensate the inductive effect produce by the loudspeaker. The whole schematic is shown below.

100

Figure 4-21 : The Power Amplifier Circuit

101

CHAPTER V TEST AND RESULT OF HARDWARE AND SOFTWARE

5.1. Introduction

In order to verify the design of the hardware and the software and the implementation used in this thesis, it is important to develop a systematic test plan and to perform a set of test that will be applied to the hardware and software module. This chapter will gradually outline the verification step of the hardware and the software module used in this thesis. The test is categorized into hardware test and software test. Some of tests are purely hardware test while the other are the combination of software tests which are based on the hardware tested previously. The hardware and software in this thesis is developed in modular fashion. Thus, the hardware and the software tests will also be performed modularly. Each of the test module will include overview, objective, assumption, configuration, guide, expected result, test code, and test result. The test will be completed manually using the instruction given in the test guide. Due to the limitation of testing devices, the test will be performed qualitatively, without any numerical result. Tests that require manual check task will require a serial port for displaying the testing values. Afterwards, received data from the serial part will be displayed by the Hercules software and tested manually.

102

5.2. Hardware Test

5.2.1. Power Amplifier 5.2.1.1.

An Overview

A power amplifier amplifies the incoming signal for the purpose of driving a loudspeaker. The test will be completed qualitatively by amplifying the sound produced by an MP4 player using an LM386 power amplifier. If the power amplifier is working well then the loudspeaker can be driven and the sound produced by MP4 player will be louder.

5.2.1.2.

Test Objective

The objective of this test is to verify the functionality of the LM386-based power amplifier, including the functionality of the volume control attached in the circuit.

5.2.1.3.

Test Assumption

The test assumed that both the MP4 player and the loudspeaker are working properly

5.2.1.4.

Test Configuration

In this test, the power amplifier is configured to amplify the signal given by the MP4 player. The illustration is given by the figure 5-1 below.

Figure 5-1 : The Configuration of Power Amplifier Test

103

5.2.1.5.

Test Guide

The following step is used to perform this test. a. Connect the MP4 player output to the power amplifier input. b. Switch on the power supply and the MP4 player. c. Play the sound and investigate the resulting sound produced by the loudspeaker.

5.2.1.6.

Expected Result

The expected result of this test is that the sound produced by the MP4 player will be amplified by power amplifier. The resulting sound is supposed to be the same as produced by the MP4 player.

5.2.1.7.

Test Result

The author observed that the power amplifier can amplify the incoming signal and works well.

5.2.2. Microphone Preamplifier and Post (Passive Lowpass) Filter 5.2.2.1.

An Overview

The microphone preamplifier and post filter is basically an amplifier cascaded to a passive first-order lowpass filter. This device will amplify and limit the bandwidth of the incoming signal. The hardware test can be done qualitatively by passing an audible signal to the input and connecting the resulting signal to the power amplifier. The amplification can be detected by comparing the resulting signal to its original. In addition, the effect of the low pass filter can be detected from the

104

reduction of high pitched tones (i.e. treble) and the degradation of sound clarity. In this test, the sound source is an MP4 player.

Test Objective

5.2.2.2.

The objective of this test is to verify the microphone amplifier and its post low pass amplifier.

Test Assumption

5.2.2.3.

This test assumes that the following requirements are met.

5.2.2.4.



The MP4 player is working well



The sound produced by sound MP4 player is audible and clear.



The power amplifier is working well

Test Configuration

The configuration used in this test is given by the picture below.

Figure 5-2 : The Configuration of Microphone Preamplifier Test

5.2.2.5.

Test Guide

The following step is used to perform this test. a. Connect the MP4 player output to the microphone preamplifier input. b. Connect the output of the microphone preamplifier to the power amplifier input. c. Connect the power amplifier output to the loudspeaker.

105

d. Switch on the MP4 player and the power supply e. Play the music and set the volume to low. f. Evaluate the resulting sound produced by the loudspeaker

5.2.2.6.

Expected Result

The resulting music should be similar as the one produced by the MP4 player with lower quality and some amplification that is adjustable by potentiometer available at the circuit.

5.2.2.7.

Test result

The author observed that the resulting signal produced by the loudspeaker has the characteristics given by the expected result. Hence, the author concluded that the microphone preamplifier and its post passive lowpass filter are working well.

5.2.3. PWM Lowpass Filter This test has the same method as the microphone preamplifier test done previousky. Every point that applicable to the previous test can be applied to this test except that the tested circuit is changed to the PWM lowpass filter instead of the microphone preamplifier.

5.2.4. RS-232 / TTL Converter

5.2.4.1.

An Overview

The TTL/RS-232 converter can be verified by testing the TTL to RS-232 conversion and vice versa. A successful TTL to RS-232 conversion can be determined by comparing the data sent from the microcontroller through the incoming TTL signal

106

and the data received by the PC through RS-232 outgoing signal. In addition, the successful RS-232 to TTL conversation can be determined by comparing the data sent from the PC through the incoming RS-232 and the data received by the microcontroller through TTL outgoing signal. To maintain the simplicity, the test application only uses the USART module of ATMega32 at speed 115200, double speed, single stop bit and no parity.

The Test Objective

5.2.4.2.

The objective of this test is to verify the TTL/RS-232 converter circuit.

The Test Assumption

5.2.4.3.

The test assumed that the following conditions are met.



The PC serial port is working well



The microcontroller USART is working well



The test code is coded well



The Hercules software is working well

The Test Configuration

5.2.4.4.

Configurations used in this test are listed below.



The microcontroller is configured as DCE at 115200bps 8n 1.



The connection is described by the figure 5-3 below.

107

Figure 5-3 : The Test Configuration of the RS-232/TTL Level Converter

5.2.4.5.

The Test Guide

The sequence performed on this test is shown below. a. Compile and test the code into microcontroller b. Open “Hercules Software” and initialize corresponding serial port by 115200 baudrate, 8 bit data size, no parity, no handshake and “LF” terminating character. c. Open corresponding port, reset microcontroller and wait for messages sent from microcontroller. The given message by microcontroller is “Test RS232/TTL Converter” on the first line and “Please type, then press enter” on the second line.

d. Type “Hello World” then press enter. e. A “Hello World” message is supposed to be displayed just after the previous message.

5.2.4.6.

The Test Code

The test code used in this test is given by the snippet 5-1.

5.2.4.7.

The Expected Result

The expected result of this test is that a “Hello World” message is printed below the message prompted by the microcontroller. 108

5.2.4.8.

The Test Result

The test showed that the RS-232/TTL converter circuit was working properly. The screenshot is shown below.

Figure 5-4 : The Screenshot of RS-232/TTL Level Convertor Test

5.2.5. Keypad Matrix and Driver 5.2.5.1.

An Overview

The functionality of the 4x4 matrix keypad can be determined by the resulting code produced by the matrix keypad driver which continuously monitors the hardware. In addition, it is also important to determine the detection accuracy and the bouncing effect of the keypad to ensure that what the user pressed is the same as what the microcontroller read.

109

In this test, the microcontroller board is configured as a DCE that continuously monitors the matrix keypad and sends the pressed key to PC over an asynchronous communication at 115200 bps, single stop bit and no parity.

The Test Objective

5.2.5.2.

The objective of this test is to ensure the functionality of the 4x4 matrix keypad and its driver.

The Test Assumption

5.2.5.3.

The test assumed that the following conditions are met.



The Keypad driver is algorithmically correct.



The RS-232/TTL converter is working well.



The microcontroller USART is working well.



The PC serial port is working well.



The Hercules software is working well.

The Test Configuration

5.2.5.4.

The following configurations are used while performing this test.



The microcontroller board is configured as DCE at 115200 bps 8n1.



The Hercules software is configured at the same configuration.



The keypad module is connected to microcontroller at PORTC.

The overall connection is shown below.

110

Figure 5-5 : The Configuration of the Matrix Keypad Test

The Test Guide

5.2.5.5.

Sequences performed on this test are shown below.



Connect the 4x4 matrix keyboard to PORTC, make sure that the column selector is connected to the high nibble of PORTC



Connect the RS232-TTL converter to PC and microcontroller board.



Open and configure corresponding port on Hercules at 115200 bps, 8bit and no parity



Switch on the power supply and wait until the microcontroller prompts a ready message.



Press the keypad button one by one from 0 to 9, A to D, ended by * to #.



The resulting pressed string is supposed to be displayed. The expected string is “0123456789ABCD*#”.

5.2.5.6.

The Test Code

The test code of the 4x4 matrix keypad module is given by the snippet 5-2.

5.2.5.7.

The Expected Result

The displayed string is supposed to be “0123456789ABCD*#”.

111

5.2.5.8.

Test Result

The result showed that the 4x4 matrix keypad module and its hardware are working well. The screenshot of the test result is shown below.

Figure 5-6 : The Screenshot of the Matrix Keypad Test

5.2.6. LCD 16x2

5.2.6.1.

An Overview

The hardware which interfaces the LCD 16x2 to the microcontroller PORTB is based on Codevision standard LCD interface. The hardware can be tested by displaying simple string to the LCD. The successfully buillt hardware interface will print the same text as expected.

112

The Test Objective

5.2.6.2.

The objective of this test is to test the hardware that interfaces a 16x2 LCD module to PORTB of microcontroller, organized in Codevision standard LCD interface, by printing a simple “Hello World” message.

The Test Assumption

5.2.6.3.

In order to run this test successfully, the following conditions are assumed.



The LCD 16x2 is working well



The PORTB of ATMega32 is working well, free, and connected to the LCD interface in line with the standard given by Codevision.

The Test Configuration

5.2.6.4.

The microcontroller is configured as a standalone controller that controls a 16x2 LCD in PORTB. The illustration is given by the figure 5-7 below.

Figure 5-7 : The Configuration of LCD Test

The Test Guide

5.2.6.5.

The steps used in this test are described below.



Connect the LCD module to PORTB of ATMega32 microcontroller.



Switch on the power supply



Wait until a “Hello World” message is printed in the first line of LCD 113

5.2.6.6.

The Test Code

The following test code is used to test the LCD interface. The test code is given by the snippet 5-3.

5.2.6.7.

The Expected Result

The successful LCD interfacing is determined by the existence of a “Hello World” message sent by the microcontroller.

5.2.6.8.

The Test Result

The author observed that a “Hello World” message is displayed on the LCD’s first line. Hence, it is concluded that the LCD interface is working well.

5.2.7. ADC and PWM 5.2.7.1.

An Overview

Since ADC and PWM works reciprocally, they can be tested simultaneously. The test will be completed by periodically sampling the signals sampled by the ADC. The resulting data is then sent to the PWM for conversion back to analog. The signal source is taken from the MP4 player. If sound is produced from the PWM then the ADC and the PWM are working well. The test will be performed qualitatively by listening to the resulting signal produced by the PWM.

114

The Test Objective

5.2.7.2.

The objective of this test is to verify the ADC and PWM hardware by a performing loopback test that redirects the sampled signal directly to the PWM instead of USART.

The Test Assumption

5.2.7.3.

In order to successfully perform this test, the following conditions are assumed.



The microphone, MP4 player, preamplifier, PWM lowpass filter, ADC and PWM hardware are working well.



5.2.7.4.

The ADC and PWM are initialized properly

The Test Configuration

The microcontroller is configured as a standalone controller that periodically reads the sampled signal from the ADC, sequentially followed by setting the PWM value. The illustration is given by the figure 5-8.

Figure 5-8 : The Configuration of ADC PWM Test

115

The Test Guide

5.2.7.5.

The steps used in this test are described below:

5.2.7.6.



Connect all sub-circuit properly



Switch on the MP4 player and play



Switch on power supply of analog circuit and microcontroller board



Adjust volume

The Test Code

The code used in this test is given by the snippet 5-4

5.2.7.7.

The Expected Result

The result expected from this test is that the loudspeaker produces sound which is the same as produced by the MP4 play, with less clarity.

5.2.7.8.

The Test Result

The author observed that a low clarity sound is produced by the loudspeaker, the sound is the same as the one that produced by the MP4 player.

5.3. Software Test

5.3.1. The RC4 Stream Cipher 5.3.1.1.

An Overview

The implementation of RC4 stream cipher can be evaluated by comparing the inner state buffer and the generated byte stream. A correct implementation of inner state buffer initialization will result in a correct inner buffer state. In addition, a

116

correct implementation of PRGA will generate exactly the same pseudo-random byte stream. In order to be able to display a raw data, both the inner state condition and the generated byte sequence have to be formatted as hexadecimal string. The formatting is done by a software that continuously displays the content of the inner state buffer as well as the generated byte sequence. The verification will be completed by comparing the result of a standardized RC4 implementation and the result of the RC4 stream cipher used in this thesis. The result of the RC4 processing from the microcontroller will be transmitted through a serial connection. The verification of the RC4 pseudo-random byte sequence will be applied to the first 512 generated byte sequences. The 512 bytes pseudo-random byte sequence will be divided into two 256 bytes to simplify verification.

The Test Objective

5.3.1.2.

The objective of this test is to verify the implementation of RC4 used in this thesis.

The Test Assumption

5.3.1.3.

In order to run the test successfully, the following conditions are assumed



The serial connection is tested and working properly



The Hercules software is working properly



The RS-232/TTL level converter is working properly

117

The Test Configuration

5.3.1.4.

In this test, the microcontroller board will be configured as a DCE that will print the result of the RC4 initialization and generated the RC4 byte sequence. The illustration is given by the figure 5-9.

Figure 5-9 : The Configuration of RC4 Test

The Test Guide

5.3.1.5.

The steps required on this test are summarized as follow.



Connect all sub-circuit and configure the Hercules software



Switch on the microcontroller board.



After the inner state buffer initialization result is displayed, evaluate the inner state buffer and clear Hercules’s display.

5.3.1.6.



Press any key to proceed to the next step.



Evaluate the displayed data.

The Test Code

The code used in this test is given by the snippet 5-5.

5.3.1.7.

The Expected Result

The result of this test is that the displayed inner state content and the generated byte stream exhibit the same result. The stream cipher set to {0x00, 0x11, 0x22, 0x33,

118

0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}. The expected results are shown below. The Content of Inner State Buffer 00 46 9b 3e 7f 58 bd 4c 72 3f 09 51 1d cb fa f7

f5 c9 95 80 9a 37 a0 b8 5d 13 86 43 25 b6 ca 54

91 38 55 d4 8e 4e 81 d0 7a 63 5b f9 c5 88 99 02

6c 24 ab 3a 0c d9 35 76 4d b3 fb 22 c7 94 50 96

30 5a 62 b2 a5 6d eb 1e 32 2f 89 dd be 84 bb 39

0e 6a 8d 4b 97 e6 fd 5f 57 b0 d8 b9 93 9f c2 69

82 40 8a 56 4f 1c 5e a7 11 04 3b f4 01 5c ed 36

f8 ce b7 e3 17 b1 67 60 79 83 75 a9 ef da 21 4a

3d 6e 0f cf 9e 41 ff 10 49 a3 b4 7d df e1 64 a6

cd 26 29 1a bf ee 12 44 f2 48 d1 af 65 05 f0 e8

aa e4 dc c1 a1 18 73 3c 20 16 03 8b f3 db de 0b

a4 ba b5 6b 06 2b fc 27 8c 14 f1 c3 68 ae 70 61

7c ec 1b 71 92 ea 0d 45 2d 7e c8 23 47 42 a2 7b

66 9c 15 d2 33 f6 6f 9d 1f 2c 34 19 c0 53 98 fe

d3 a8 78 e9 07 85 ac 2a 2e 74 d5 d6 c4 0a d7 e7

28 c6 59 e0 77 cc ad 87 08 52 e5 31 bc 90 8f e2

59 a1 77 7f f5 ab f6 9b 90 ac 02 fd bc ed 25 31

b9 0b 98 50 70 98 77 78 88 49 8d b2 ed 03 3e 80

3b 7e 42 a1 a0 d9 83 9b ea 7c 0f 2b 7c f5 14 dd

95 51 2d b1 37 54 12 b4 76 61 58 53 46 79 6f 68

45 fd 67 87 df df d6 48 35 a9 d8 de c0 a0 fc 03

7d e7 7c 1e c5 e3 80 d8 35 9c 7f b5 b3 44 6e 1d

94 1d fe c0 0d 15 51 85 5a 3b f7 3e 6c 15 9a 02

7a bc 1d 9b e6 92 b0 e7 f3 bd 4a 82 36 03 fb 7a

27 09 59 03 7e aa d8 92 0d f9 e5 93 4d 79 54 fc

ad e6 8d 90 0a a2 2d 96 ce a7 78 e7 65 56 3a c5

f6 ac e1 1e 95 3a 9c 86 97 24 0b 00 cb 86 26 19

86 b5 f4 c4 b1 6c ea dc e7 99 de 47 89 04 84 a3

67 78 54 fc 19 0e 3b b8 d2 da d6 64 cf 2c e4 52

9d 71 3c 6f 18 6c 59 2e 97 dc 07 f7 83 ad ce 96

Generated Byte Stream (Part 1) 85 09 43 54 12 31 4e 90 84 f5 b2 42 5b a9 0d 72

5b c5 9b 21 f3 03 2f 7e 8f 84 12 22 27 53 22 42

ac 93 b5 60 a2 cf 1c 7c 0c 85 b3 0f c7 9e ab 3d

57 50 a9 0b 53 f7 08 f3 08 8b db 8a ed 52 9f 31

92 a1 06 43 56 4d 1e 27 13 33 1b 98 bb bf 9c 0d

27 17 20 b8 52 e2 11 0c 9b 72 a0 f4 5e 4f a4 92

61 8b 92 a8 89 76 c7 17 4e 12 73 c3 ab 8a 56 9f

85 2e 2a b8 c6 62 74 5d 31 20 e4 b4 83 cf c0 b3

f8 60 b1 a1 07 60 cf f2 f3 3a 90 ac 2d d4 17 bc

Generated Byte Stream (Part 2) 47 05 fb 19 4b 72 98 e3 4e e7 d1 b6 f9 ca 05 68

ff 87 5a 0a d3 bc c6 72 4a 51 22 ce a5 fa 78 66

0f 75 74 c1 6e e8 33 80 59 68 1c fc 68 70 4f 4b

c5 c1 32 10 dd c2 18 2e f1 fb 8b 7e 55 29 55 c1

a3 b2 33 32 c8 63 a3 bb 74 71 31 a6 d2 e8 e2 ef

2a 69 be dc a0 b0 4e 9f 7d fd 44 fd c5 7d 4b 90

9d e5 ef b6 2f 81 05 e6 3b 7c 8d 99 41 96 1b 0c

db 24 17 28 5c 05 65 82 47 41 11 bb db 06 1a e2

21 c1 57 ae 8d 10 6a b2 4a d6 c7 1a 4c 47 b4 36

Figure 5-10 : The RC4 Known Value Test

119

5.3.1.8.

The Test Result

Based on the test result, it is concluded that the RC4 stream cipher module is working properly. Screenshots are shown below.

Figure 5-11 : The Screenshot of Inner State Buffer Content

Figure 5-12 : The Screenshot of RC4 Generated Byte Stream

120

Figure 5-13 : The Screenshot of RC4 Generated Byte Stream

5.3.2. The Diffie-Hellman Key-Exchange Algorithm

5.3.2.1.

An Overview

The Diffie-Hellman module can be verified by comparing the resulting calculation and the known result. The resulting calculation is propagated through a serial connection. The known values are outlined below. Parameter Hexadecimal Decimal g

0x03

3

e

0x 9a2e

39470

m

0x10001

65537

y

0xc366

50022

Table 5-1 : The Diffie-Hellman Known Test Reference

121

Test Objective

5.3.2.2.

The objective of this test is to verify the accuracy of the Diffie-Hellman implementation.

Test Assumption

5.3.2.3.

In order to successfully perform this test, the following conditions are assumed.



The serial communication is working properly



The Hercules software is working properly

Test Configuration

5.3.2.4.

In this test, the microcontroller board is configured as a DCE that performs the Diffie-Hellman calculation and propagates the result through a serial communication. The illustration is given by the figure 5-14.

Figure 5-14 : The Configuration of Diffie-Hellman Test

Test Guide

5.3.2.5.

The followings are the steps required in this test.



Connect all sub-circuit and configure Hercules software



Switch on microcontroller board and evaluate the printed message

122

5.3.2.6.

Test Code

The code used in this test is given by the snippet 5-6.

5.3.2.7.

Expected Result

The expected result of this test is the appearance of calculation result which is the same as known values defined above

5.3.2.8.

Test Result

The result of the Diffie-Hellman calculation performed by the microcontroller is exactly the same as the known reference value. The screenshot is shown below.

Figure 5-15 : The Screenshot of Diffie-Hellman Test

123

CHAPTER VI CONCLUSION

The designing of an ATMega32-based secure communication device over

Public Switched Telephone Network (PSTN) using the RC4 stream cipher has been completed successfully. The experiment showed that the cryptophone secure communication device could reach the expected functional requirement including a secure communication that uses dynamic key management shared through a particular key-exchange algorithm. The encrypted speech sample is satisfactorily randomized into noise which is unintelligible enough for a secure communication. The device response is also fast, although some heavy calculation in keyexchange process may requires a minute to complete. In addition, the encryption algorithm also runs very fast. The environment driven pseudo-random number generator showed an unpredictable fashion of generating number. Although the device only supports the basic functionality of a cryptophone secure communication device, it can be developed further to support complex event handling or complex user interface.

6.1. Further Development Direction

The author suggested the following list of topics that can be covered as the continuation effort of the secure communication device development.



The usage of hybrid coding between assembly and C to increase the device performance.



The cryptographic verification of the stream cipher used in this thesis.

124



The usage of another stream / block cipher and key-exchange algorithm, may provide more security.



The further analysis on the differential power analysis to enhance device security against hardware attack.



The implementation of a complex cryptophone using a larger and faster microcontroller which can handle multiprocessing.



The investigation of another practical approach of secure communication device with high security and low cost.

125

BIBLIOGRAPHY

[1]

Alexander, Charles K., and Matthew N.O. Sadiku. Fundamentals of Electric Circuit. 3rd Edition. New York: Mc Graw Hill Science, 2001.

[2]

Axelsen, Jan. Serial Port Complete : Programming and Circuits for RS-232 and RS-485 Links and Networks. Madison: Lakeview Research, 2000.

[3]

Chu, Wai C. Speech Coding Algorithms : Foundation and Evolution of Standardized Coders. New Jersey: Wiley Interscience, 2003.

[4]

George, Jim, Gautham Krishnamurthy, and Venkatesh. H.B. Digital Voice Recorder. April 07, 2002. http://wiredworld.tripod.com/tronics.html (accessed February Sunday, 2009).

[5]

Grosul, Alexander L., and Wallasch Dan S. A Related Key Cryptanalysis of RC4. Rice University, 2000.

[6]

Haykin, Simon. Communication Systems. New York: John Wiley and Sons, 2001.

[7]

Jung, Walter G. Op Amp Applications. Massachusetts: Analog Devices, 2002.

[8]

Mancini, Ron. Op Amps for Everyone, A Design Reference. Texas: Texas Instruments, 2002.

[9]

Menezes, Alfred J., Paul C. van Oorschot, and Scott A. Vanstone. Handbook of Applied Cryptography. Florida: CRC Press, 1996.

[10]

Oppenheim, Alan V., Alan S. Willsky, and S. Hamid Nawab. Signals and System. 2nd Edition. New Jersey: Prentice Hall, 1996.

[11]

Oppenheim, Alan V., Ronald W. Schafer, and John R. Buck. Discrete Time Signal Processing. New Jersey: Prentice Hall, 1998.

126

[12]

Oppliger, Rolf. Contemporary Cryptography. Massachuset: Artech House, Inc., 2005.

[13]

Scheneier, Bruce. Applied Cryptography. New York: Jown Wiley and Sons, 1996.

[14]

Vaudenay, Serge. A Classical Introduction to Cryptography. New York: Springer Science, 2006.

[15]

Wikipedia,

The

Free

Encyclopedia.

May

8,

2009.

http://en.wikipedia.org/wiki/Sallen_Key_filter (accessed May Monday, 2009). [16]

Zhang, Tony. Sams Teach Yourself C in 24 Hours. Indiana: Macmillan Computer Publishing, 1997.

127

APPENDICES A. SNIPPETS unsigned char RC4_s[256];

// RC4 inner state buffer

/************************************************************************************* Function Name : RC4_init(unsigned char *key, unsigned char len) Description : this function initializes the inner state buffer of RC4 stream cipher Number of Argument : 2 Type of Argument : unsigned char (pointer to cipher key) unsigned char (length of given cipher key) Type of Return Value : void *************************************************************************************/ void RC4_init(unsigned char *key, unsigned char len){ int i; unsigned char j, t; /* Initialize s[] with incrementing value from 0x00 to 0xff */ for(i=0; i<256; i++){ RC4_s[i]=i; }

/* Randomize s[i]*/ for(i=0, j=0; i<256; i++){ j = ( j + RC4_s[i] + key[i % len]) & 0xff; t = RC4_s[i]; // swap s[i] and s[j] RC4_s[i] = RC4_s[j]; RC4_s[j] = t; } }

Snippet 4-1 : The RC4 Inner State Initialization

/************************************************************************************* Function Name : unsigned char RC4_out(void) Description : this function generates RC4 pseudo-random byte stream Number of Argument : none Type of Argument : void Type of Return Value : unsigned char *************************************************************************************/ unsigned char RC4_out(void){ static unsigned char i=0; // 1st S[] pointer static unsigned char j=0; // 2nd S[] pointer unsigned char t; // temporary buffer i++; j = (j + RC4_s[i]) & 0xff;

// point next i index // update j pointer

t = RC4_s[i]; RC4_s[i] = RC4_s[j]; RC4_s[j] = t;

// swap s[i] and s[j]

t = (RC4_s[i] + RC4_s[j]) & 0xff; return RC4_s[t]; // return s[s[i] + s[j]] }

Snippet 4-2 : The RC4 Pseudo-Random Generation Algorithm (PRGA) Routine 128

/************************************************************************************* Function Name : void get_random(unsigned char *prng_out) Description : Generate Pseudo-random Sequence as a hex string to given buffer Number of Argument : 1 Type of Argument : unsigned char (pointer to output string buffer) Type of Return Value : unsigned char *************************************************************************************/ void get_random(unsigned char *prng_out){ unsigned char i; // loop counter memset(prng_out,0,33); // Reset random zero terminated hex buffer #ifdef USE_ADC_PRNG /* Sample 16 bytes data from DAC */ adc_sync = FALSE; while(!adc_value); for(i=0;i<31;i+=2){ while(!adc_sync); adc_sync = FALSE; sprintf((prng_out + i),"%02x",adc_value); } #else /* generate pseudo-random sequence using rand() function */ for(i=0;i<31;i+=2){ sprintf((prng_out + i)),"%02x",rand() & 0xff); } #endif }

Snippet 4-3 : The Pseudo-Random Number Generator (PRNG) Routine

/************************************************************************************* Keypad Related Constants *************************************************************************************/ #define FCLK 16000000 #define FIRST_COLUMN 0x80 // 0b10000000 #define LAST_COLUMN 0x10 // 0b00010000 #define KEYIN PINC #define KEYOUT PORTC #define KEYPAD_PRESCALAR 256 #define KEYPAD_RATE 500 // 500 scan per second #define KEYPAD_TIMER_SET (0x100-(FCLK/KEYPAD_PRESCALAR/KEYPAD_RATE)) /* Lookup Table */ unsigned int keys = 0; flash unsigned char key_table[17]={ 0, ‘D’,’#’,’0’,’*’, ‘C’,’9’,’8’,’7’, ‘B’,’6’,’5’,’4’, ‘A’,’3’,’2’,’1’ };

/************************************************************************************* Function Name : interrupt [TIM2_OVF] void timer2_int(void) Description : Scheduled keypad scanning process based on timer2 overflow interrupt which is occurred every 2ms; Number of Argument : none Type of Argument : void Type of Return Value : void *************************************************************************************/ interrupt [TIM2_OVF] void timer2_int(void){ static unsigned char key_pressed_counter=20; static unsigned char key_released_counter,column=FIRST_COLUMN; static unsigned int row_data,crt_key; TCNT2 = KEYPAD_TIMER_SET;

// initialize timer2

129

row_data <<= 4; row_data |= (~KEYIN & 0x0f); column >>= 1; if (column == (LAST_COLUMN>>1)){ column = FIRST_COLUMN; if (!row_data) goto new_key; if (key_released_counter){ --key_released_counter; }else{ if (--key_pressed_counter == 9){ crt_key=row_data; }else{ if (row_data != crt_key){ new_key: key_pressed_counter = 10; key_released_counter = 0; goto end_key; }; if (!key_pressed_counter){ keys = row_data; key_released_counter = 20; }; }; }; end_key:; row_data = 0; }; KEYOUT = ~column; }

/************************************************************************************* Function Name : unsigned char inkey(void) Description : Convert scanned data provided by scanning routine. The scanning routine provides scanned key as a 16 bit string, while the pressed key is simply represented by the location of non zero bit. Number of Argument : none Type of Argument : void Type of Return Value : ASCII character [0123456789*#ABCD] *************************************************************************************/ unsigned char keypad_read(void){ unsigned char i=0; // declare bit counter while(keys){ // detect non zero bit location and save it to i keys >>= 1; i++; } return key_table[i]; }

/************************************************************************************* Function Name : void init_keypad(void) Description : Initialize Keypad Number of Argument : 0 Type of Argument : void Type of Return Value : void *************************************************************************************/ void keypad_init(void){ TCNT2 = KEYPAD_TIMER_SET; // set to overflow every 2ms TCCR2 = ( TIMER_COUNTER_2_NORMAL_PORT_OPERATION | // Use OC2 as normal TIMER_COUNTER_2_CLOCK_SELECT_CLK_IO_PRESCALING_256 | // prescalar 256 TIMER_COUNTER_2_WAVEFORM_NORMAL ); // Use timer2 in normal mode TIMSK = TIMER_COUNTER_2_OVERFLOW_INTERRUPT_ENABLE; // enable timer2 overflow }

Snippet 4-4 : The Implementation of Keypad Driver

130

#define DIFFIE_NUM_BITS 128 #define DIFFIE_NUM_BYTES (DIFFIE_NUM_BITS/8) unsigned unsigned unsigned unsigned

char char char char

m[DIFFIE_NUM_BYTES+1]; g[DIFFIE_NUM_BYTES+1]; e[DIFFIE_NUM_BYTES+1]; b[DIFFIE_NUM_BYTES+1];

int n, v, d, z; /************************************************************************************* Function Name : void dh_add(unsigned char *x, unsigned char *y, int o) Description : Add y times o to x x = (x + y * o) Number of Argument : 3 Type of Argument : unsigned char *x (pointer to x buffer) unsigned char *y (pointer to y buffer) int o (factor) Type of Return Value : void *************************************************************************************/ void dh_add(unsigned char *x, unsigned char *y, int o){ d = 0; /* initialize temporary to zero */ v = DIFFIE_NUM_BYTES; while(v){ d += x[v]+y[v]*o; x[v] = d; d = d>>8; v--; }

/* /* /* /* /* /*

set cell pointer to the rightmost side */ process while pointer does not reach the boundary */ add x and (y*o) to d */ copy lower byte to destination */ copy higher byte to temporary */ point the next cell */

}

/************************************************************************************* Function Name : void dh_sub(unsigned char *x) Description : subtract x by modulo m, if x was greater than m Number of Argument : 1 Type of Argument : unsigned char *x (pointer to x) Type of Return Value : void *************************************************************************************/ void dh_sub(unsigned char *x){ v=0; /* start scanning from the leftmost cell */ /* find the leftmost cell which is different with modulo */ while((v < DIFFIE_NUM_BYTES) && (x[v] == m[v])){ v++; } /* subtract m from x, if it was greater or equal */ if(x[v] >= m[v]){ dh_add(x,m,-1); } }

/************************************************************************************* Function Name : void dh_shr(unsigned char *x) Description : shift right number buffer by one bit Number of Argument : 1 Type of Argument : unsigned char *x (pointer to x) Type of Return Value : void *************************************************************************************/ void dh_shr(unsigned char *x){ d=0; /* clear temporary */ v=0; /* set pointer to the leftmost cell */ /* scan cells from right to left */ while(v < (DIFFIE_NUM_BYTES+1)){ d |= x[v]; /* set the lower byte */ x[v++] = (d>>1); /* shift right d and store on x[v] */ d = (d & 0x01) << 8; /* copy ignored bit to higher byte */ }

131

}

/************************************************************************************* Function Name : void dh_mult(unsigned char *x,unsigned char *y) Description : multiply y into x x = (x * y) Number of Argument : 2 Type of Argument : unsigned char *x (pointer to x buffer) unsigned char *y (pointer to y buffer) Type of Return Value : void *************************************************************************************/ void dh_mult(unsigned char *x,unsigned char *y){ unsigned char X[DIFFIE_NUM_BYTES+1]; unsigned char Y[DIFFIE_NUM_BYTES+1]; /* Copy x->X and y->Y and reset x */ memcpy(X,x,DIFFIE_NUM_BYTES + 1); memcpy(Y,y,DIFFIE_NUM_BYTES + 1); memset(x,0,DIFFIE_NUM_BYTES + 1); /* loop as much as the number of bits */ z=((DIFFIE_NUM_BYTES + 1)*8); while(z){ z--; /* if the rightmost bit was set */ if(X[DIFFIE_NUM_BYTES]&1){ dh_add(x,Y,1); /* x = (x + y)*/ dh_sub(x); /* subtract if x is greater than modulo */ } dh_shr(X); /* shift right and point the rightmost bit */ dh_add(Y,Y,1); /* multiply y by two */ dh_sub(Y); /* subtract if y is greater than modulo */ } } /************************************************************************************* Function Name : void dh_htoi(char *x,unsigned char *y) Description : Convert Hexadecimal string to integer Number of Argument : 2 Type of Argument : unsigned char *x (pointer to x) unsigned char *y (pointer to y) Type of Return Value : void *************************************************************************************/ void dh_htoi(unsigned char *x,unsigned char *y){ /* clear y buffer */ memset(y,0,DIFFIE_NUM_BYTES + 1); for(n=0;x[n]>0;n++){ z=4; while(z){ z--; dh_add(y,y,1); }

/* shift left y */

/* translate hex to decimal and save on the rightmost cell */ y[DIFFIE_NUM_BYTES] |= toint(x[n]); } } /************************************************************************************* Function Name : void dh_print(unsigned char *prn_out, unsigned char *x) Description : print Diffie-Hellman calculation result as a hexadecimal string Number of Argument : 2 Type of Argument : unsigned char *prn_out (pointer to printing buffer) unsigned char *x (pointer to Diffie-Hellman res buffer) Type of Return Value : void *************************************************************************************/ void dh_print(unsigned char *prn_out, unsigned char *x){ /* clear printing buffer */ memset(prn_out,0,33); /* convert to hexadecimal string */ for(n=0;n<(DIFFIE_NUM_BYTES + 1);n++){

132

sprintf((prn_out + (n << 1)),"%02x",x[n]); } } /************************************************************************************* Function Name : void dh_init(unsigned char *arg_g, unsigned char *arg_e, unsigned char *arg_m) Description : Initialize Diffie-Hellman Module Number of Argument : 0 Type of Argument : void Type of Return Value : void *************************************************************************************/ void dh_init(unsigned char *arg_g, unsigned char *arg_e, unsigned char *arg_m){ dh_htoi(arg_g,g); /* convert hexadecimal string at arg_g into integer at g */ dh_htoi(arg_e,e); /* convert hexadecimal string at arg_e into integer at e */ dh_htoi(arg_m,m); /* convert hexadecimal string at arg_m into integer at m */ /* clear b buffer */ memset(b,0,DIFFIE_NUM_BYTES + 1); /* set rightmost byte to 1 */ b[DIFFIE_NUM_BYTES]=1; }

/************************************************************************************* Function Name : void dh_run(unsigned char *key_buff) Description : Run Diffie-Hellman Module Number of Argument : 1 Type of Argument : unsigned char (pointer to key result buffer) Type of Return Value : void *************************************************************************************/ void dh_run(unsigned char *key_buff){ /* set to number bits */ n=((DIFFIE_NUM_BYTES + 1)*8); /* while not in the leftmost cell */ while(n){ n--; /* if the rightmost bit of e is set then b = (b x g) */ if(e[DIFFIE_NUM_BYTES]&1){ dh_mult(b,g); } dh_mult(g,g); dh_shr(e);

/* square out g */ /* shift right exponent and point the next bit */

} /* display calculation result */ dh_print(key_buff, b); }

Snippet 4-5 : The Implementation of DHKEA

unsigned char adc_value; /************************************************************************************* Function Name : interrupt [TIM0_OVF] void timer0_int(void) Description : ADC Sampling Scheduler at rate 8KHz Number of Argument : none Type of Argument : void Type of Return Value : void *************************************************************************************/ interrupt [TIM0_OVF] void timer0_int(void){ TCNT0 = ADC_TIMER_SET; // Set the counter reg to get a sampling rate of 8000Hz sch_sync = TRUE;

133

}

/************************************************************************************* Function Name : interrupt [ADC_INT] void adc_int(void) Description : Sample from ADC Channel 0, copy result to adc_value Number of Argument : none Type of Argument : void Type of Return Value : void *************************************************************************************/ interrupt [ADC_INT] void adc_int(void){ adc_value = ADCH; adc_sync = TRUE; // prompt other routine that sampled data is available }

/************************************************************************************* Function Name : void adc_init(void) Description : Initialize ADC Number of Argument : none Type of Argument : void Type of Return Value : void *************************************************************************************/ void adc_init(){ ADCSRA = 0x00; // Disable adc ADMUX

= ( ADC_REFERENCE_AVCC ADC_LEFT_ADJUST_RESULT

| |

// // // // // // // //

Use AVCC As Reference Use ADC Channel 0 as sampling line from microphone Left Justified Enable ADC Start Conversion Enable Interrupt ADC Clock = FCLK/128

ADC_SINGLE_INPUT_ADC0 ); ADCSRA = ( ADC_ENABLE | ADC_START_CONVERSION | ADC_INTERRUPT_ENABLE | ADC_PRESCALAR_128 | ADC_AUTO_TRIGGER_ENABLE ); SFIOR |= ADC_AUTO_TRIGGER_SOURCE_TIMER_COUNTER0_OVERLOW;

// ADC Triggered by // Timer0 Overflow

} /************************************************************************************* Function Name : void adc_timer_enable(void) Description : Enable ADC Timer Scheduler Number of Argument : none Type of Argument : void Type of Return Value : void *************************************************************************************/ void adc_timer_enable(void){ TCCR0 = ( TIMER_COUNTER_0_NORMAL_PORT_OPERATION | // Use Timer0 as normal // timer TIMER_COUNTER_0_CLOCK_SELECT_CLK_IO_PRESCALING_8 | // prescalar 8 TIMER_COUNTER_0_WAVEFORM_NORMAL ); TIMSK |= TIMER_COUNTER_0_OVERFLOW_INTERRUPT_ENABLE; //Enable Timer0 overflow // interrupt } /************************************************************************************* Function Name : void adc_timer_disable(void) Description : Disable ADC Timer Scheduler Number of Argument : none Type of Argument : void Type of Return Value : void *************************************************************************************/ void adc_timer_disable(void){ TCCR0 = 0x00; // use no clock source to stop timer0 } /************************************************************************************* Function Name : void adc_shutdown(void) Description : Disable ADC Number of Argument : none Type of Argument : void Type of Return Value : void *************************************************************************************/

134

void adc_shutdown(void){ ADCSRA = 0x00; // Disable adc } /************************************************************************************* Function Name : unsigned char get_adc(void) Description : Return ADC value Number of Argument : 0 Type of Argument : void Type of Return Value : void *************************************************************************************/ unsigned char get_adc(void){ return adc_value; }

Snippet 4-6 : The ADC Driver Implementation

/************************************************************************************* Function Name : void pwm_enable(void) Description : Initialize PWM Number of Argument : none Type of Argument : void Type of Return Value : void *************************************************************************************/ void pwm_enable(void){ TCCR1A = 0x21; // Connect output to OC1B, Non Inverting 8bit PWM TCCR1B = 0x09; // Fast PWM with prescalar 1 TCNT1 = 0x00; // Initialize counter to 0; TIFR = 0x04; // Clear all Timer Interrupts OCR1B = 0x00; // Initial PWM value } /************************************************************************************* Function Name : void pwm_disable(void) Description : disable PWM Number of Argument : none Type of Argument : void Type of Return Value : void *************************************************************************************/ void pwm_disable(void){ TCCR1B = 0x00; // disable timer1 clock source to make it off }

Snippet 4-7 : The PWM-Based DAC Driver

/* ADPCM Stuff */ signed int predict; signed int temp2; signed int accum; signed int step_size_in; signed int step_size_out;

// predicted value of the current sample // 16 bit accumulator // step size for decoding // step size for encoding

signed char current_index_in; signed char current_index_out;

//index into the "index" array //index into the "index" array

unsigned unsigned unsigned unsigned

// cycle in counter // cycle out counter

char char char char

temp; cycle_in; cycle_out; upper, lower;

135

unsigned char p1,p2; bit neg_flag; flash signed char flash signed char { 7, 14, 29, 58, 116,

// Negative Flag index[8] = {-1, -1, table4[NUMSTEPS] = 8, 8, 9, 10, 11, 15, 17, 18, 20, 22, 31, 34, 37, 41, 44, 63, 69, 75, 82, 89, 127};

-1, -1, 2, 4, 6, 8}; 12, 24, 48, 98,

13, 26, 53, 107,

/************************************************************************************* Function Name : unsigned char adpcm_encode(unsigned char byte_stream) Description : encode given sample as adpcm code Number of Argument : 1 Type of Argument : unsigned char (RC4 cipher stream) Type of Return Value : void *************************************************************************************/ void adpcm_encode(unsigned char byte_stream){ signed

int

delta;

unsigned char adpcm_code = 0; /* measure difference */ delta = int2fix(adc_value) - predict; if (delta < 0){ neg_flag adpcm_code delta }else{ neg_flag }

//difference between real value // and predicted value // ADPCM code

= TRUE; = SIGN_BIT; = -delta; = FALSE;

temp2 = step_size_out; if (delta >= temp2){ adpcm_code += 4; delta -= temp2; } temp2 >>= 1; if (delta >= temp2){ adpcm_code += 2; delta -= temp2; } temp2 >>= 1; if (delta >= temp2){ adpcm_code += 1; } temp = adpcm_code & 0x07; temp2 = (step_size_out >> 3); if (temp & 1){ temp2 += (step_size_out >> 2); } if (temp & 2){ temp2 += (step_size_out >> 1); } if (temp & 4){ temp2 += (step_size_out >> 0); } if (neg_flag){ temp2 = -temp2; } predict += temp2; if (predict > MAX){ predict = MAX; } if (predict < MIN){ predict = MIN;

136

} current_index_out += index[temp];

/* set current index between 0 to NUMSTEPS-1 */ if (current_index_out < 0){ current_index_out = 0; } if (current_index_out > NUMSTEPS-1){ current_index_out = NUMSTEPS-1; } step_size_out = int2fix( table4[current_index_out] ); if(cycle_out & 0x01){ lower = adpcm_code; /* send encoded data to USART */ putchar ((unsigned char)((upper << 4) | (lower & 0x0f)) ^ byte_stream); }else{ upper = adpcm_code; } cycle_out++; } /************************************************************************************* Function Name : void adpcm_decode(unsigned char byte_stream) Description : decode given sample as adpcm code Number of Argument : 1 Type of Argument : unsigned char (RC4 cipher stream) Type of Return Value : void *************************************************************************************/ void adpcm_decode(unsigned char byte_stream){ unsigned char adpcm_d_tmp; //compute next sample if (!(cycle_in & 0x01)){ //do we need to unpack more data? adpcm_d_tmp = rx_data ^ byte_stream; p1 = (adpcm_d_tmp >> 4) & 0x0f; // high nibble p2 = (adpcm_d_tmp & 0x0f); // low nibble adpcm_d_tmp = p1; }else{ adpcm_d_tmp = p2; } temp = (adpcm_d_tmp & 0x07); temp2 = (step_size_in >> 3); if (temp & 1){ temp2 += (step_size_in >> 2); } if (temp & 2){ temp2 += (step_size_in >> 1); } if (temp & 4){ temp2 += step_size_in; } if (adpcm_d_tmp & SIGN_BIT){ temp2 = -temp2; } accum += temp2; if (accum > MAX){ accum = MAX; } if (accum < MIN){ accum = MIN;

137

} //compute the new stepsize current_index_in += index[temp]; if (current_index_in < 0){ current_index_in = 0; } if (current_index_in > NUMSTEPS-1){ current_index_in = NUMSTEPS-1; } step_size_in = int2fix( table4[current_index_in] ); OCR1B = (accum) >> 8; cycle_in++; } /************************************************************************************* Function Name : void adpcm_init(void) Description : initialize ADPCM related settings Number of Argument : 0 Type of Argument : void Type of Return Value : void *************************************************************************************/ void adpcm_init(void){ /* encoder init */ OCR1B = 0x00; upper = 0x00; lower = 0x00; cycle_out = 0x00; // cycle out counter predict = 0x00; step_size_out = int2fix( table4[0] ); current_index_out = 0x00; //index into the "index" array temp2 = 0; temp = 0; step_size_in = int2fix( table4[0] ); accum = 0; // 16 bit accumulator cycle_in = 0; // cycle in counter p1 = 0; p2 = 0; current_index_in = 0; //index into the "index" array }

Snippet 4-8 : The ADPCM Voice Codec Module

#include <mega32.h> #include <stdio.h> #include <string.h> /* Environment Setting */ #define FCLK 16000000 #define UBRR_115200 ((long) (FCLK/(8*115200 ))-1) /* USART Bit Definition */ #define UCSRA_U2X 1 #define UCSRB_RXEN 4 #define UCSRB_TXEN 3 #define UCSRC_URSEL 7 #define UCSRC_UCSZ0 1 /* Main Entrance */ void main(void){ /* Declare Buffer */ unsigned char tmp[101];

138

/* Initialize Port Related to TX and RX pin */ DDRD = 0b00000010; PORTD = 0b00000000; /* Initialize USART */ UBRRH = UBRR_115200 >> 8; UBRRL = UBRR_115200; UCSRA = ( 1 << UCSRA_U2X ); /* Use Double Speed */ UCSRB = ( (1 << UCSRB_RXEN ) | (1 << UCSRB_TXEN )); /* Enable TX and RX */ UCSRC = ( (1 << UCSRC_URSEL) | (3 << UCSRC_UCSZ0)); /* Asynchronous 8 Bit */ /* Prompt message */ putsf("Test RS232/TTL Converter\r"); putsf("Please type, then press enter"); /* wait and print typed characters*/ while(1){ memset(tmp,0,sizeof(tmp)); gets(tmp,sizeof(tmp)); puts(tmp); putchar('\r'); } }

Snippet 5-1: The RS-232/TTL Test Code

#include <mega32.h> #include <stdio.h> #include <string.h>

/* Environmental Setting */ #define FCLK 16000000 /* USART Related Constant */ #define UBRR_115200 ((long) (FCLK/(8*115200 ))-1) /* USART Bit Definition */ #define UCSRA_U2X 1 #define UCSRB_RXEN 4 #define UCSRB_TXEN 3 #define UCSRC_URSEL 7 #define UCSRC_UCSZ0 1 /* Keypad Related Bit Definition */ #define TCCR2_CS20 0 #define TIMSK_TOIE2 6 /* Keypad related Constants */ #define FIRST_COLUMN 0x80 // 0b10000000 #define LAST_COLUMN 0x10 // 0b00010000 #define KEYIN PINC #define KEYOUT PORTC #define KEYPAD_PRESCALAR 256 #define KEYPAD_RATE 500 // 500 scan per second #define KEYPAD_TIMER_SET (0x100-(FCLK/KEYPAD_PRESCALAR/KEYPAD_RATE))

/* Function Prototypes */ interrupt [TIM2_OVF] void timer2_int(void); unsigned char keypad_read(void); void keypad_init(void); void usart_init(void);

/* Global Variables */ unsigned int keys = 0; flash unsigned char key_table[17]={ 0,

139

'D','#','0','*', 'C','9','8','7', 'B','6','5','4', 'A','3','2','1' };

/* Main Entrance */ void main(void){ unsigned char k; usart_init(); keypad_init(); #asm("sei");

/* Key Buffer */

/* Initialize USART */ /* Initialize Keypad */ /* Activate interrupt */

/* Prompt A Ready Message */ putsf("Keypad Test Ready\r"); while(1){ if(k = keypad_read()){ putchar(k); } } }

/* Keypad Scheduling Interupt */ interrupt [TIM2_OVF] void timer2_int(void){ static unsigned char key_pressed_counter=20; static unsigned char key_released_counter,column=FIRST_COLUMN; static unsigned int row_data,crt_key; TCNT2 = KEYPAD_TIMER_SET; // initialize timer2 row_data <<= 4; row_data |= (~KEYIN & 0x0f); column >>= 1; if (column == (LAST_COLUMN>>1)){ column = FIRST_COLUMN; if (!row_data) goto new_key; if (key_released_counter){ --key_released_counter; }else{ if (--key_pressed_counter == 9){ crt_key=row_data; }else{ if (row_data != crt_key){ new_key: key_pressed_counter = 10; key_released_counter = 0; goto end_key; }; if (!key_pressed_counter){ keys = row_data; key_released_counter = 20; }; }; }; end_key:; row_data = 0; }; KEYOUT = ~column; } /* Decode positional symbol into character */ unsigned char keypad_read(void){ unsigned char i=0; // declare bit counter while(keys){ // detect non zero bit location and save it to i keys >>= 1; i++; } return key_table[i]; } /* Initialize Keypad */ void keypad_init(void){ DDRC = 0b11110000; PORTC = 0b11111111; TCNT2 = KEYPAD_TIMER_SET;

// Keypad Port // set to overflow

140

every 2ms TCCR2 = (4 << TCCR2_CS20 ); // prescalar 256 TIMSK = (1 << TIMSK_TOIE2); // enable timer2 overflow }

/* Initialize USART */ void usart_init(void){ DDRD = 0b00000010; PORTD = 0b00000000; UBRRH = UBRR_115200 >> 8; UBRRL = UBRR_115200; UCSRA = ( 1 << UCSRA_U2X ); /* Use Double Speed */ UCSRB = ( (1 << UCSRB_RXEN ) | (1 << UCSRB_TXEN )); /* Enable TX and RX */ UCSRC = ( (1 << UCSRC_URSEL) | (3 << UCSRC_UCSZ0)); /* Asynchronous 8 Bit */ }

Snippet 5-2 : The Matrix Keypad Test Code

#asm (".equ __lcd_port=0x18") #include <mega32.h> #include

/* Main Entrance */ void main(void){ lcd_init(16); lcd_putsf("Hello World"); while(1); }

// use PORTB as LCD port

/* initialize LCD */ /* Print Message */ /* Freeze Microcontroller */

Snippet 5-3 : The LCD Test Code

#include <mega32.h> /* Environment Setting */ #define FCLK 16000000

/* ADC Related Constant */ #define ADC_PRESCALAR 8 #define ADC_RATE 8000 /* 8000 sample per second */ #define ADC_TIMER_SET (0x100-(FCLK/ADC_PRESCALAR/ADC_RATE))

/* Bit Definition */ #define TCCR0_CS00 #define TIMSK_TOIE0 #define ADMUX_REFS0 #define ADMUX_ADLAR #define ADCSRA_ADEN #define ADCSRA_ADSC #define ADCSRA_ADATE #define ADCSRA_ADIE #define ADCSRA_ADPS0 #define SFIOR_ADTS0

0 0 6 5 7 6 5 3 0 5

/* function prototype */ interrupt [TIM0_OVF] void timer0_int(void);

141

interrupt [ADC_INT] void adc_int(void);

/* main entrance */ void main(void){ DDRA = 0x00; /* Set PORTA as input */ /* setup scheduling timer */ TCCR0 = (2 << TCCR0_CS00); TIMSK |= (1 << TIMSK_TOIE0); /* setup TCCR1A = TCCR1B = TCNT1 = TIFR = OCR1B =

pwm */ 0x21; 0x09; 0x00; 0x04; 0x00;

/* setup adc */ ADCSRA = 0x00; ADMUX

= ( (1 (1

/* prescalar 8 */ /* Enable Timer0 overflow interrupt */

/* Connect output to OC1B, Non Inverting 8bit PWM */ /* Fast PWM with prescalar 1 */ /* Initialize counter to 0 */ /* Clear all Timer Interrupts */ /* Initial PWM value */

/* Disable adc */ << ADMUX_REFS0 ) | << ADMUX_ADLAR ) );

/* Use AVCC As Reference */ /* Use ADC Channel 0 as sampling line from microphone */

ADCSRA = ( (1 (1 (1 (7 (1

<< << << << <<

/* /* /* /*

SFIOR

<< SFIOR_ADTS0 );

|=

(4

#asm("sei"); while(1);

ADCSRA_ADEN ) ADCSRA_ADSC ) ADCSRA_ADIE ) ADCSRA_ADPS0) ADCSRA_ADATE)

| | | | );

Enable ADC */ Start Conversion */ Enable ADC Interrupt */ ADC Clock = FCLK/128 */

/* ADC Triggered by Timer0 Overflow */

/* Enable interrupt */ /* freeze microcontroller */

}

/* ADC scheduling based on timer0 interrupt */ interrupt [TIM0_OVF] void timer0_int(void){ TCNT0 = ADC_TIMER_SET; /* Set the counter to get a 8000Hz sampling rate */ } /* Interrupt of a completed sampling */ interrupt [ADC_INT] void adc_int(void){ OCR1B = ADCH; }

Snippet 5-4 : The ADC-PWM Test Code

#include <mega32.h> #include <stdio.h> /* Environment Setting */ #define FCLK 16000000 #define UBRR_115200 ((long) (FCLK/(8*115200 ))-1) /* USART Bit Definition */ #define UCSRA_U2X 1 #define UCSRB_RXEN 4 #define UCSRB_TXEN 3 #define UCSRC_URSEL 7 #define UCSRC_UCSZ0 1 /* Global Variable */ unsigned char RC4_s[256];

// RC4 inner state buffer

142

/* Function Prototypes */ void RC4_init(unsigned char *key, unsigned char len); unsigned char RC4_out(void); void test_stream(void); /* Main Entrance */ void main(void){ /* Declare Buffer */ unsigned char RC4_key[16]={ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}; int i; /* Initialize Port Related to TX and RX pin */ DDRD = 0b00000010; PORTD = 0b00000000; /* Initialize USART */ UBRRH = UBRR_115200 >> 8; UBRRL = UBRR_115200; UCSRA = ( 1 << UCSRA_U2X ); /* Use Double Speed */ UCSRB = ( (1 << UCSRB_RXEN ) | (1 << UCSRB_TXEN )); /* Enable TX and RX */ UCSRC = ( (1 << UCSRC_URSEL) | (3 << UCSRC_UCSZ0)); /* Asynchronous 8 Bit */ /* Initialize the RC4 buffer */ RC4_init(RC4_key,sizeof(RC4_key)); putsf("The Content of Inner State Buffer"); /* Display the Inner State Initialization Result */ for(i=0;i<256;i++){ printf("%02x",RC4_s[i]); if((i+1)%16){ putchar(' '); }else{ putchar('\n'); } } putchar('\r'); /* wait for user respone */ getchar(); /* Display Geerated Byte Stream */ putsf("The RC4 Pseudo-random Byte Sequence [1/2]"); test_stream(); getchar(); putsf("The RC4 Pseudo-random Byte Sequence [2/2]"); test_stream(); /* freeze microcontroller */ while(1); } /* RC4 Initialization */ void RC4_init(unsigned char *key, unsigned char len){ unsigned char j, t; int i; /* Initialize s[] with incrementing value from 0x00 to 0xff */ for(i=0; i<256; i++){ RC4_s[i]=i; } /* Randomize s[i]*/ for(i=0, j=0; i<256; i++){ j = ( j + RC4_s[i] + key[i % len]) & 0xff; t = RC4_s[i]; // swap s[i] and s[j] RC4_s[i] = RC4_s[j]; RC4_s[j] = t;

143

} }

/* The RC4 PRGA */ unsigned char RC4_out(void){ static unsigned char i=0; static unsigned char j=0; unsigned char t;

// 1st S[] pointer // 2nd S[] pointer // temporary buffer

i++; j = (j + RC4_s[i]) & 0xff;

// point next i index // update j pointer

t = RC4_s[i]; RC4_s[i] = RC4_s[j]; RC4_s[j] = t;

// swap s[i] and s[j]

t = (RC4_s[i] + RC4_s[j]) & 0xff; return RC4_s[t]; // return s[s[i] + s[j]] } /* test generated byte stream */ void test_stream(void){ int i; for(i=0;i<256;i++){ printf("%02x", RC4_out()); if((i+1)%16){ putchar(' '); }else{ putchar('\n'); } } }

Snippet 5-5 : The RC4 Test Code

#include #include #include #include

<mega32.h> <stdio.h> <string.h>

/* Environment Setting */ #define FCLK 16000000 #define UBRR_115200 ((long) (FCLK/(8*115200 ))-1) /* USART Bit Definition */ #define UCSRA_U2X 1 #define UCSRB_RXEN 4 #define UCSRB_TXEN 3 #define UCSRC_URSEL 7 #define UCSRC_UCSZ0 1 /* Diffie-Hellman Related Constants */ #define DIFFIE_NUM_BYTES 16 /* Global Variables */ unsigned char m[DIFFIE_NUM_BYTES+1]; unsigned char g[DIFFIE_NUM_BYTES+1]; unsigned char e[DIFFIE_NUM_BYTES+1]; unsigned char b[DIFFIE_NUM_BYTES+1]; int n, v, d, z; /* function Prototypes */ void dh_add(unsigned char *x, unsigned char *y, int o); void dh_adj(unsigned char *x); void dh_shr(unsigned char *x); void dh_mult(unsigned char *x,unsigned char *y); void dh_htoi(char *x,unsigned char *y);

144

void dh_print(unsigned char *prn_out, unsigned char *x); void dh_init(unsigned char *arg_g, unsigned char *arg_e, unsigned char *arg_m); void dh_run(unsigned char *key_buff); /* Main Entrance */ void main(void){ /* Declare Buffer */ unsigned char dh_g[2*DIFFIE_NUM_BYTES+1]="03"; unsigned char dh_m[2*DIFFIE_NUM_BYTES+1]="10001"; unsigned char dh_e[2*DIFFIE_NUM_BYTES+1]="9a2e"; unsigned char dh_y[2*DIFFIE_NUM_BYTES+1]; /* Initialize ADC Related port*/ DDRA = 0b00000000; // ADC Port, set all input PORTA = 0b00000000; // set all Hi Impedance no Pullup /* Initialize USART */ UBRRH = UBRR_115200 >> 8; UBRRL = UBRR_115200; UCSRA = ( 1 << UCSRA_U2X ); /* Use Double Speed */ UCSRB = ( (1 << UCSRB_RXEN ) | (1 << UCSRB_TXEN )); /* Enable TX and RX */ UCSRC = ( (1 << UCSRC_URSEL) | (3 << UCSRC_UCSZ0)); /* Asynchronouis 8 Bit */

/* Prompt message */ putsf("Diffie-Hellman Test"); dh_init(dh_g,dh_e,dh_m); dh_run(dh_y); printf("Calculate y = (g^e) mod m \n"); printf("g = %s\n", dh_g); printf("e = %s\n", dh_e); printf("m = %s\n", dh_m); printf("y = %s\n", dh_y); while(1); } void dh_add(unsigned char *x, unsigned char *y, int o){ d = 0; v=(DIFFIE_NUM_BYTES+1); while(v){ d += x[v]+y[v]*o; x[v] = d; d = d>>8; v--; } } void dh_adj(unsigned char *x){ v=0; while((v < DIFFIE_NUM_BYTES) && (x[v] == m[v])){ v++; } if(x[v] >= m[v]){ dh_add(x,m,-1); } } void dh_shr(unsigned char *x){ d=0; v=0; while(v < (DIFFIE_NUM_BYTES+1)){ d |= x[v]; x[v++] = d>>1; d = (d & 0x01) << 8; } } void dh_mult(unsigned char *x,unsigned char *y){ unsigned char X[DIFFIE_NUM_BYTES+1]; unsigned char Y[DIFFIE_NUM_BYTES+1];

145

/* Copy x->X and y->Y and reset x */ memcpy(X,x,DIFFIE_NUM_BYTES + 1); memcpy(Y,y,DIFFIE_NUM_BYTES + 1); memset(x,0,DIFFIE_NUM_BYTES + 1); z=((DIFFIE_NUM_BYTES + 1)*8); while(z){ if(X[DIFFIE_NUM_BYTES]&1){ dh_add(x,Y,1); dh_adj(x); } dh_shr(X); dh_add(Y,Y,1); dh_adj(Y); z--; } } void dh_htoi(unsigned char *x,unsigned char *y){ /* clear y buffer */ memset(y,0,DIFFIE_NUM_BYTES + 1); for(n=0;x[n]>0;n++){ z=4; while(z){ dh_add(y,y,1); z--; } y[DIFFIE_NUM_BYTES] |= toint(x[n]); } } void dh_print(unsigned char *prn_out, unsigned char *x){ unsigned char tmp[3]; // hex buffer temporary /* clear printing buffer */ memset(prn_out,0,33); for(n=0;n<(DIFFIE_NUM_BYTES + 1);n++){ if(x[n]){ sprintf(tmp,"%02x",x[n]); strcat(prn_out,tmp); } } } void dh_init(unsigned char *arg_g, unsigned char *arg_e, dh_htoi(arg_g,g); /* convert hexadecimal string at dh_htoi(arg_e,e); /* convert hexadecimal string at dh_htoi(arg_m,m); /* convert hexadecimal string at

unsigned char *arg_m){ arg_g into integer at g */ arg_e into integer at e */ arg_m into integer at m */

/* clear b buffer */ memset(b,0,DIFFIE_NUM_BYTES + 1); /* set rightmost byte to 1 */ b[DIFFIE_NUM_BYTES]=1; } void dh_run(unsigned char *key_buff){ n=((DIFFIE_NUM_BYTES + 1)*8); while(n){ if(e[DIFFIE_NUM_BYTES]&1){ dh_mult(b,g); } dh_mult(g,g); dh_shr(e); /* e >>= 1*/ n--; } dh_print(key_buff, b); }

Snippet 5-6 : The Diffie-Hellman Test Code

146

Related Documents

Edipermadi Thesis
June 2020 8
Thesis
April 2020 31
Thesis
October 2019 45
Thesis
July 2020 22
Thesis
November 2019 35
Thesis
June 2020 19

More Documents from ""