C语言实现CBC模式DES加密

#define SECTION_SIZE 8 //每段密文字节数,DES为8个字节64位
#define GET_BIT(x,y) (x |((BYTE)0xff <<9-y) | ((BYTE)0xff >>y)) //将X的第Y位保留,其余位置1
#define FORM_DWORD(p1,p2,p3,p4)  ((((DWORD)p1) <<24) | (((DWORD)p2) <<16) | (((DWORD)p3) <<8) | ((DWORD)p4)) //四个字节形成一个双字
#define FORM_BYTE(x,y) ((BYTE)((x & ((DWORD)0xffffffff << 8*(4-y)) & ((DWORD)0xffffffff >> (y-1)*8)) >>(4-y)*8))//将双字X的第Y个字节提取出来
#define GET_BIT_LOW(x,y) ((x & ( (BYTE)0xff<<(8-y)) & (BYTE)0xff >> (y-1)) >> (8-y)) //拿到字节X的第Y位
//#define ENCRPT  //如果定义则为加密,无定义为解密
#define CHANGE  //未用

//------------------------------------------------------------------------------------------
BYTE DisPlaceIPTable[] = { 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
};
BYTE DisPlaceRIPTable[] = { 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
};
BYTE DisPlaceKEYTable[] = { 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4, };
BYTE MoveCount[] = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 };
BYTE PC_2[] = { 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 };
BYTE E_Table[] = { 32, 1, 2, 3, 4, 5,
4, 5, 6, 7, 8, 9,
8, 9, 10, 11, 12, 13,
12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21,
20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29,
28, 29, 30, 31, 32, 1 };
BYTE S1[4][16] = { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13};
BYTE S2[4][16] = { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 };
BYTE S3[4][16] = { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 };
BYTE S4[4][16] = { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14 };
BYTE S5[4][16] = { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 };
BYTE S6[4][16] = { 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13 };
BYTE S7[4][16] = { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12 };
BYTE S8[4][16] = { 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11 };
BYTE result[] = { 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10,
2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25 };
//---------------------------------------------------------------------------------
typedef struct _BIT
{
    BYTE a : 1;
    BYTE b : 1;
    BYTE c : 1;
    BYTE d : 1;
    BYTE e : 1;
    BYTE f : 1;
}BIT,*PBIT;
typedef struct _8_BIT
{
    BYTE a : 1;
    BYTE b : 1;
    BYTE c : 1;
    BYTE d : 1;
    BYTE e : 1;
    BYTE f : 1;
    BYTE g : 1;
    BYTE h : 1;
}E_BIT,*P4_BIT;

LPVOID  getTable(int index);
DWORD data_rl(DWORD x, BYTE y, BYTE z);
PBYTE SHL_Connect(PBYTE p1, PBYTE p2, int index);
void ExchangeDword(PVOID p1, PVOID p2);
void DisPlaceItem(PVOID fileVa, PBYTE KEY, int length);
// DESEncryption.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "windows.h"
#include "myEncpy.h"

int _tmain(int argc, _TCHAR* argv[])
{

    //get plaintext
    HANDLE hFile = CreateFile(L"d:\\a.txt", GENERIC_ALL, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL);
    if (hFile == INVALID_HANDLE_VALUE)
    {
        printf_s("can not create file...  d:a.txt");
        system("pause");
        return 0;
    }
    HANDLE hFileMapping = CreateFileMapping(hFile, 0, PAGE_READWRITE, 0, 0, L"myshare");
    if (hFileMapping == INVALID_HANDLE_VALUE)
    {
        printf_s("can not create filemapping");
        system("pause");
        return 0;
    }
    LPVOID fileVa = MapViewOfFile(hFileMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0);
    if (fileVa == NULL)
    {
        printf_s("can not get mapview");
        system("pause");
        return 0;
    }
    //printf_s("%s\n", fileVa);
    //使用内存映射打开大文件
    //---------------------------------------------------------------
    //get parameter,key,subkey
    BYTE KEY[8] = { ‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘, ‘h‘ }; //定义密钥
    DisPlaceItem(KEY, DisPlaceKEYTable,7);
    PBYTE SubKey[16];
    BYTE C0[4] = { KEY[0], KEY[1], KEY[2], KEY[3]&0xf0 };
    BYTE D0[4] = { KEY[3] & 0x0f, KEY[4], KEY[5], KEY[6] };
    for (int i = 0; i < 16; i++)
    {
        PBYTE p = SHL_Connect(C0, D0, i);
        DisPlaceItem(p, PC_2, 6);
        SubKey[i] = p;  //生成16个子密钥
    }

    //-----------------
    // begain encryp
    BYTE CBC_IV[] = { 0x11, 0x32, 0x43, 0x54, 0x65, 0x76, 0x87, 0xa8 };//初始化向量 未向
    PBYTE fileOffset =(PBYTE)fileVa;  //明文起始位置
    DWORD fileSize = GetFileSize(hFile, 0); //得到明文大小

    for (DWORD index = 0; index < fileSize / SECTION_SIZE ; index ++) //目前只针对凑满8个字节的部分进行加密
    {
        fileOffset = fileOffset + index *SECTION_SIZE;

        //for (int i = 0; i < SECTION_SIZE; i++)
        //{
        //    *(fileOffset + i) ^= CBC_IV[i];
        //}

#ifdef CHANGE
        DisPlaceItem(fileOffset, DisPlaceIPTable, 8); //IP置换
#endif

#ifdef ENCRPT
        for (int j =0; j <16; j++)
        {
#else
        for (int j = 15; j >= 0; j--)
        {
#endif
            BYTE L0[4], R0[6];
            memcpy(L0, fileOffset, 4);
            memcpy(R0, fileOffset + 4, 4); //分别拿到左边右边4个字节
#ifdef ENCRPT
            if (j !=15)
#else
            if (j != 0)
#endif
                memcpy(fileOffset, R0, 4); //如果不是最后一次加密或者解密,则右边直接写回左边
            else
                memcpy(fileOffset + 4, R0, 4);
            DisPlaceItem(R0, E_Table, 6); //扩展置换
            PBYTE pbyte1 = SubKey[j];
            for (int i = 0; i < 6; i++)
            {
                R0[i] ^= pbyte1[i];  //与右边进行异或
            }
            //partion----------------------------------------
            BIT mybit[8] = {0};
            ///////////////////////
            BYTE t[48]; //把6字节分为6位一组共8组
            int tIndex = 1;
            int rIdex = 0;
            for (int i = 0; i < 48; i++)
            {
                BYTE a = R0[rIdex];
                t[i] = GET_BIT_LOW(R0[rIdex], tIndex);
                if (tIndex % 8 == 0)
                {
                    rIdex++;
                    tIndex = 1;
                }
                else
                {
                    tIndex++;
                }
            }
            tIndex = 0;
            for (int i = 0; i < 48; i+=6)
            {
                mybit[tIndex].a = t[i];
                mybit[tIndex].b = t[i+1];
                mybit[tIndex].c = t[i+2];
                mybit[tIndex].d = t[i+3];
                mybit[tIndex].e = t[i+4];
                mybit[tIndex].f = t[i+5];
                tIndex++;
            }
            //此时mybit里面放着分组之后的每一位
            ////////////////////////
            BYTE  Str[4];
            int EIndex = 0;
            BYTE(*tempTable)[16] = 0;
            for (char i = 0; i < 8; i += 2) //根据mybit拿到表中的数并 组合成str
            {
                tempTable = (BYTE(*)[16])getTable(i + 1);
                BYTE sum1 = tempTable[mybit[i].a*2 + mybit[i].f][mybit[i].b*8 + mybit[i].c*4 + mybit[i].d*2 + mybit[i].e];
                tempTable = (BYTE(*)[16])getTable(i + 2);
                BYTE sum2 = tempTable[mybit[i + 1].a*2 + mybit[i + 1].f][mybit[i + 1].b*8 + mybit[i + 1].c*4 + mybit[i + 1].d*2 + mybit[i + 1].e];
                BYTE sum = sum1 << 4 | sum2;
                memcpy(Str + EIndex, &sum, 1);
                EIndex++;
            }
#ifdef CHANGE
            DisPlaceItem(Str, result, 4); //结果与左边置换
#endif
            for (int i = 0; i < 4; i++)
            {
                L0[i] ^= Str[i];
            }
#ifdef ENCRPT
            if (j != 15)
#else
            if (j != 0)  //将左边写到右边
#endif
                memcpy(fileOffset + 4, L0, 4);
            else
                memcpy(fileOffset, L0, 4);
        }

#ifdef CHANGE
        DisPlaceItem(fileOffset, DisPlaceRIPTable, 8);//IP逆置换
#endif
        //memcpy(CBC_IV, fileOffset, 8);
        //-----------------------------------------------

    }

    printf_s("got it");
    for (int i = 0; i < 16; i++)
    {
        free(SubKey[i]);
    }
    CloseHandle(hFile);
    CloseHandle(hFileMapping);
    UnmapViewOfFile(fileVa);

    system("pause");
    return 0;
}

void DisPlaceItem(PVOID fileVa,PBYTE KEY,int length) //fileva为需要置换的内容首地址 key为置换表,length为输出字节数
{
    PBYTE File = (PBYTE)fileVa;
    BYTE Result[8] ;
    memset(Result, 0xff, 8);
    int DisIndex = 1;
    for (int i = 0; i < length; i++)
    {
        int bitofEach = 1;
        while (true)
        {
            BYTE temp1 = KEY[DisIndex-1];
            BYTE ByteIndex = temp1 / 8;
            ByteIndex = temp1 % 8 == 0 ? ByteIndex -1 : ByteIndex;
            BYTE BitIndex = temp1- ByteIndex*8;
            BYTE temptemp = *(File + ByteIndex);
            if (bitofEach < BitIndex)
            {
                temptemp = *(File + ByteIndex) << (BitIndex - bitofEach);
            }
            else if (bitofEach>BitIndex)
            {
                temptemp = *(File + ByteIndex) >> (bitofEach - BitIndex);
            }
            BYTE t = GET_BIT(temptemp, bitofEach);
            Result[i] = Result[i] & GET_BIT(temptemp, bitofEach);
            if (DisIndex % 8 == 0)
                break;
            DisIndex++;
            bitofEach++;
        }
        DisIndex++;
    }
    memcpy(fileVa, Result, length);
}
PBYTE SHL_Connect(PBYTE p1, PBYTE p2, int index) //循环移位并连接
{
    PBYTE pbyte = (PBYTE)malloc(7);
    DWORD d1 = FORM_DWORD(p1[0], p1[1], p1[2], p1[3]);
    DWORD d2 = FORM_DWORD(p2[0], p2[1], p2[2], p2[3]) <<4;
    d1 = data_rl(d1, MoveCount[index], 32);
    d2 = data_rl(d2, MoveCount[index], 32) >>4;
    for (int i = 0; i < 4; i++)
    {
        *(p1 + i) = FORM_BYTE(d1, i + 1);
        *(p2 + i) = FORM_BYTE(d2, i + 1);
    }
    memcpy(pbyte, p1, 3);
    BYTE temp = p1[3] | p2[0];
    *(pbyte + 3) = temp;
    memcpy(pbyte + 4, p2, 3);
    return pbyte;
}
DWORD data_rl(DWORD x, BYTE y, BYTE z)  //移位的实现
{
    DWORD temp;
    temp = x >> (y - z );
    temp = temp << 4;
    x = x << z;
    x = x | temp;
    return x;
}
LPVOID  getTable(int index)
{
    switch (index)
    {
    case 1:
        return S1;
        break;
    case 2:
        return S2;
        break;
    case 3:
        return S3;
        break;
    case 4:
        return S4;
        break;
    case 5:
        return S5;
        break;
    case 6:
        return S6;
        break;
    case 7:
        return S7;
        break;
    case 8:
        return S8;
        break;
    default:
        break;
    }
}
时间: 2024-10-11 22:47:31

C语言实现CBC模式DES加密的相关文章

使用Crypto++库的CBC模式实现加密

1 //***************************************************************************** 2 //@File Name : scsaes.h: the interface of crypto++ library 3 //@Version : V1.0.0 4 //@Author : xiaoc 5 //@Date : 2014/11/11 6 //**************************************

使用Crypto++库的CBC模式实现加密(二)

前面已经有一篇介绍使用Crypto++库实现的加密的文章了,但是代码中考虑的不完全,所以就重新发了个二 C++封装: #include "zyaes.h" #include <string.h> #include <stdio.h> using namespace CryptoPP; CZYAes::CZYAes() { byte byteKey[] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08, 0x01,0x02, 0

DES加密模式详解

DES加密模式详解 http://www.cnblogs.com/Lawson/archive/2012/05/20/2510781.html http://www.blogjava.net/wayne/archive/2011/05/23/350879.html 加密算法常见的有ECB模式和CBC模式: ECB模式:电子密本方式,这是JAVA封装的DES算法的默认模式,就是将数据按照8个字节一段进行DES加密或解密得到一段8个字节的密文或者明文,最后一段不足8个字节,则补足8个字节(注意:这里

分组密码模式: CBC模式(密码分组链接模式)

CBC模式是将前一个密文分组与当前明文分组的内容混合起来进行加密的,这样就可以避免ECB模式的弱点. 在CBC模式中,首先将明文分组与前一个密文分组进行XOR运算,然后再进行加密,如下图所示: 如果将一个分组的加密过程分离出来,我们就可以很容易地比较出ECB模式和CBC模式的区别,ECB模式只进行了加密,而CBC模式则在加密之前进行了一次XOR,如下图所示: 当加密第一个明文分组时,由于不存在“前一个密文分组”,因此需要事先准备一个长度为一个分组的比特序列来代替“前一个密文分组”,这个比特序列称

C++调用openssl实现DES加密解密cbc模式 zeropadding填充方式 pkcs5padding填充方式 pkcs7padding填充方式

============================================== des   cbc  加密 zeropadding填充方式 ============================================== //加密 cbc zeropadding 自己实现 std::string des_cbc_zero_encrypt(const std::string &clearText, const std::string &key) { static u

【转】 iOS DES ECB模式对称加密解密

最近忙于android和iOS的项目,写完了android的DES 的ECB模式加密解密(相关连接:http://blog.csdn.net/vipa1888/article/details/8086037),又 回到了Ios上面,因为本人也是最近今年开始研究ios的,所以Ios上面好多东西都不懂,进过了半年的研究,终于吧ios的DES 的ECB模式对称加密解密搞定了,本人遇到的问题很严重的问题,网上写的好多16进制数转化位字节都有问题的,经过本人研究发现他们有一个地方写错了,导 致解密后的NS

OC的DES加密,使与java的Cipher类用DES/CBC/PKCS5Padding方式的加密结果相同

问题说明: 最近用到DES加密,并且要与java的Cipher类加密的结果保持一致.没研究过java的Cliper,但工作中Cipher根据DES/CBC/PKCS5Padding加密方式生成了一个字符串.比较后发现,此字符串与将OC加密生成的NSData直接用字符串格式化([NSString stringWithFormat:@"%@",data])相同.所以就先这么用了. 代码如下: #import "CommonCrypto/CommonCryptor.h"

【转】 java DES ECB模式对称加密解密

最近需要又要使用DES加密数据,要求DES加密出来的数据为对称加密,经过研究,发现了一些问题: 1.DES对称ECB模式加密的数据,长度必须为8的倍数 2.加密的数据,加密后先转码(因为加密后的数据我是转码了),否则解密是乱码格式 一下是源代码: 这个是加密的工具类: package com.palmfu.sql; import java.security.Key; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpe

AES加密CBC模式 IOS - Java 互通共用

AES加密模式和填充方式 算法/模式/填充                16字节加密后数据长度        不满16字节加密后长度AES/CBC/NoPadding             16                          不支持AES/CBC/PKCS5Padding          32                          16AES/CBC/ISO10126Padding       32                          16AE