#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <memory.h>
#include <malloc.h>
typedef int INT32;
typedef char INT8;
typedef unsigned char ULONG8;
typedef unsigned short ULONG16;
typedef unsigned long ULONG32;
#ifndef BIN_TO_STR
#define BIN_TO_STR 0
#define STR_TO_BIN 1
#endif
#define SUCCESS 0
#define FAIL -1
/*函数申明*/
/*加密接口函数*/
INT32 gost_enc(ULONG32 *data , ULONG32 *key);
/*解密接口函数*/
INT32 gost_dec(ULONG32 *data, ULONG32 *key);
INT32 encry_data( ULONG32 *Ldata,ULONG32 *Rdata,ULONG32 *key);
INT32 dencry_data( ULONG32 *Ldata,ULONG32 *Rdata,ULONG32 *key);
INT32 f(ULONG32 x);/*s-盒替换、循环左移11位操作*/
/*左右值交换*/
INT32 gost_swap( ULONG32 *Ldata,ULONG32 *Rdata);
/*Gost的s-盒*/
ULONG8 wz_sp[8][16] ={
{ 0x4,0xa,0x9,0x2,0xd,0x8,0x0,0xe,0x6,0xb,0x1,0xc,0x7,0xf,0x5,0x3},
{ 0xe,0xb,0x4,0xc,0x6,0xd,0xf,0xa,0x2,0x3,0x8,0x1,0x0,0x7,0x5,0x9},
{ 0x5,0x8,0x1,0xd,0xa,0x3,0x4,0x2,0xe,0xf,0xc,0x7,0x6,0x0,0x9,0xb},
{ 0x7,0xd,0xa,0x1,0x0,0x8,0x9,0xf,0xe,0x4,0x6,0xc,0xb,0x2,0x5,0x3},
{ 0x6,0xc,0x7,0x1,0x5,0xf,0xd,0x8,0x4,0xa,0x9,0xe,0x0,0x3,0xb,0x2},
{ 0x4,0xb,0xa,0x0,0x7,0x2,0x1,0xd,0x3,0x6,0x8,0x5,0x9,0xc,0xf,0xe},
{ 0xd,0xb,0x4,0x1,0x3,0xf,0x5,0x9,0x0,0xa,0xe,0x7,0x6,0x8,0x2,0xc},
{ 0x1,0xf,0xd,0x0,0x5,0x7,0xa,0x4,0x9,0x2,0x3,0xe,0x6,0xb,0x8,0xc}
};
/*加密密钥使用顺序表*/
ULONG32 wz_spkey[32] = {
0,1,2,3,4,5,6,7,
0,1,2,3,4,5,6,7,
0,1,2,3,4,5,6,7,
7,6,5,4,3,2,1,0
};
/*s-盒替换、循环左移11位操作*/
INT32 f (ULONG32 x) {
x = wz_sp[7][(x>>28)&0xf]<<28 | wz_sp[6][(x>>24)&0xf]<<24
| wz_sp[5][(x>>20)&0xf]<<20 | wz_sp[4][(x>>16)&0xf]<<16
| wz_sp[3][(x>>12)&0xf]<<12 | wz_sp[2][(x>>8)&0xf]<<8
| wz_sp[1][(x>>4)&0xf]<< 4 | wz_sp[0][x&0xf];
return x <<11 | x>>21;
}
/*左右值交换*/
INT32 gost_swap( ULONG32 *Ldata,ULONG32 *Rdata)
{
ULONG32 tempbuf;
tempbuf = *Rdata;
*Rdata = *Ldata ;
*Ldata = tempbuf;
return SUCCESS;
}
/*32轮解密操作*/
INT32 dencry_data( ULONG32 *Ldata,ULONG32 *Rdata,ULONG32 *key)
{
ULONG32 i = 0 ;
ULONG32 tempbuf = 0 ;
for (i = 0 ; i < 32;i++)
{
*Rdata ^=f(*Ldata + key[wz_spkey[31-i]]);
gost_swap(Ldata,Rdata); /*左右值交换*/
}
gost_swap(Ldata,Rdata); /*左右值交换*/
return SUCCESS;
}
/*解密接口函数*/
INT32 gost_dec(ULONG32 *data ,/*待解密数据首地址,内容需保证是64位长*/
ULONG32 *key/*用户输入密钥首地址,内容需保证是256位长*/
)
{
ULONG32 *Ldata ;
ULONG32 *Rdata ;
Ldata = data ;
Rdata = &Ldata[1];/*分成左右两个部分,每部分32字节*/
dencry_data( Ldata, Rdata,key ) ;
/*明文可用data读出*/
return SUCCESS;
}
INT32 gost_enc(ULONG32 *data , /*待加密数据首地址,内容需保证是64位长*/
ULONG32 *key/*用户输入密钥首地址,内容需保证是256位长*/
)
{
ULONG32 *Ldata ;
ULONG32 *Rdata ;
Ldata = data ;
Rdata = &Ldata[1];/*分成左右两个部分,每部分32字节*/
encry_data( Ldata, Rdata,key ) ;
/*密文可用data读出*/
return SUCCESS;
}
/*32轮加密操作*/
INT32 encry_data( ULONG32 *Ldata,ULONG32 *Rdata,ULONG32 *key)
{
ULONG32 i = 0 ;
ULONG32 tempbuf = 0;
for (i = 0 ; i < 32;i++)
{
*Rdata ^=f(*Ldata + key[wz_spkey[i]]);
gost_swap(Ldata,Rdata); /*左右值交换*/
}
gost_swap(Ldata,Rdata); /*左右值交换*/
return SUCCESS;
}
/*算法实现代码结束*/