// DES.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
//////////////////////////////////////////////////////////////////////////
// DES加密、解密算法
// 作者:liujichao
// DES算法:64位明文(不足需补位) + 56位密钥(8个校验位) --> 64位密文
// 定义32位无符号类型
typedef unsigned long DWORD;
// DES 64位块
typedef struct tagBLOCK
{
DWORD dwLeft32; // 高32位
DWORD dwRight32; // 低32位
}BLOCK, *LPBLOCK;
namespace
{
// 正向置换表
int DES_IP[] =
{
58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7
};
// 逆向置换表
int DES_NIP[] =
{
40, 8, 48, 16, 56, 24, 64, 32,
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25
};
}
// DES IP置换算法
void DesIpTransform(LPBLOCK lpBlock, bool bDirection = true)
{
// 缓冲临时置换数据
BLOCK buffer;
memset(&buffer, 0, sizeof(BLOCK));
// 指定置换表
int* ip = bDirection ? DES_IP : DES_NIP;
// 比特位置换过程
for(int i = 0; i < 64; ++i)
{
// 防止边界外非法读、写操作
//assert((table[i] >= 0) && (table[i] < 64));
// 低32位置换
if(i <= 31)
{
if(ip[i] > 32)
{
buffer.dwLeft32 |= ( (lpBlock->dwRight32 >> (64 - ip[i]) ) & 0x01) << (31 - i);
}
else
{
buffer.dwLeft32 |= ( (lpBlock->dwLeft32 >> (32 - ip[i]) ) & 1) << (31 - i);
}
}
// 高32位置换
else
{
if (ip[i] < 32)
{
buffer.dwRight32 |= ( (lpBlock->dwLeft32 >> (32 - ip[i]) ) & 1) << (31 - i);
}
else
{
buffer.dwRight32 |= ( (lpBlock->dwRight32 >> (64 - ip[i]) ) & 1) << (31 - i);
}
}
}
lpBlock->dwLeft32 = buffer.dwLeft32;
lpBlock->dwRight32 = buffer.dwRight32;
}
int main(int argc, char* argv[])
{
BLOCK block = {0x01, 0x02};
DesIpTransform(&block, true);
DesIpTransform(&block, false);
return 0;
}