//作者:西安电子科技大学 通信工程学院 王余刚
//2009.8.25
#include <reg51.h>
sbit P01=P0^1;
unsigned int keystreamTime=0 ;
unsigned char key[1] ;
void init_serialcom( void ) ;
void send_char_com ( unsigned char ch) ;
void delay_ms(unsigned char t) ;
void swap ( unsigned char *x, unsigned char *y ) ;
main()
{
unsigned int i, j, q;
unsigned int key_Counter, iCounter, key_len ;
unsigned char s[256], k[256], key_stream[32] ;
key_len=1;
init_serialcom() ; //初始化串口
for ( key_Counter=0; key_Counter<256 ; key_Counter++ )
{
RI = 0 ;
key[0]= key_Counter ; //主密钥赋值
while ( RI==0 )
{
P01 = 0 ;
//算法开始执行
for( i=0 ; i<256 ; i++ )
s[i] = i ; //S盒赋值
for( i=0 ; i<256 ; i++ )
k[i] = key[i%key_len] ;
for( i=j=0 ; i<256 ; i++ ) //打乱S盒
{
j= (j+s[i]+k[i])%256 ;
swap( &s[i] , &s[j] ) ;
}
i=j=0 ;
for( q=0 ; q<32 ; q++ ) //产生密钥流
{
i = ( i+1 )%256 ;
j = (j+s[i])%256 ;
swap( &s[i], &s[j]) ;
key_stream[q] = s[(s[i]+s[j])%256] ;
}
//算法结束 加密完成 产生密钥流
P01 = 1 ;
delay_ms( 2000 ) ;
if( keystreamTime < 1 ) //密钥流只返回一次 本次总返回64字节数据 前32字节数据为上次密钥流 后32字节数据为本次密钥流
{
for ( iCounter=0 ; iCounter<32 ; iCounter++ ) //返回密钥流
{
send_char_com( key_stream[iCounter] ) ;
}
keystreamTime++ ;
}
}
}
}
void init_serialcom( void ) //串口通信初始设定
{
TMOD |= 0x20 ; //定时器1为模式2,8位自动重装
TH1 = 0xFD ; //Baud:19200 fosc="11".0592MHz
SCON = 0x50 ; //UART为模式1,8位数据,允许接收
PCON |= 0x00 ; //SMOD=0;
IE |= 0x90 ; //开串口中断
TR1 = 1 ; // 定时器启动
RI=0; //准备接收数据
}
void send_char_com ( unsigned char ch) //向串口发送一个字符
{
SBUF = ch ;
while (TI == 0);
TI = 0 ;
}
void delay_ms(unsigned char t) //延时函数
{
unsigned char i;
while(t-->0)for(i=120;i>0;i--);
}
void swap ( unsigned char *x, unsigned char *y ) //交换两个数
{
unsigned char temp;
temp = *x ;
*x = *y ;
*y = temp ;
}
void serial () interrupt 4 using 3 //串口中断函数
{
if( RI==0 )
keystreamTime=0 ;
}