DataChunk DESECBEncrypt(DataChunk messageChunk, Block key) { DataChunk cipherChunk = initDataChunk(messageChunk.iLength - messageChunk.iLength % 8 + 16); Block message = initBlock(64), cipher; KeySchedule k; int i; cipher = initBlock(64); k = DESKeySchedule(key); for (i = 0; i < messageChunk.iLength / 8; i++) { memcpy(message, messageChunk.block + 8 * i, 8); cipher = DESEncrypt(message, k); memcpy(cipherChunk.block + 8 * i, cipher, 8); } free(message); // If the length is not an integral multiple of 8. if (messageChunk.iLength % 8) { memcpy((message = initBlock(64)), messageChunk.block + 8 * i, messageChunk.iLength % 8); cipher = DESEncrypt(message, k); memcpy(cipherChunk.block + 8 * i, cipher, 8); } return (cipherChunk); }
//======================================== // test_fun1 功能是计算DES加密 // RxComm[1]: // RxComm[2..9]: 8字节密钥 // RxComm[10] : 待加密数据的长度 // RxComm[11....N]: 待加密数据 //======================================== void test_fun1(unsigned char xdata *RxComm,unsigned char xdata *TxComm) { unsigned char i; unsigned char xdata in[129]; //待加密的数据长度 不超过128字节 unsigned char xdata out[128]; unsigned char xdata key[9]; key[0] = 8; for(i=0;i<8;i++) { key[i+1] = RxComm[i+2]; } in[0] = RxComm[10]; // 待加密数据的长度 for(i=0;i<in[0] ;i++) { in[i+1] = RxComm[i+11]; } DESEncrypt(in,key,out);// in,key 两个输入参数都是LV格式,输出参数out也是LV格式. for(i=0;i<out[0];i++) { TxComm[i+1] = out[i+1]; //输出8字节DES加密的结果 } TxComm[0]=out[0]; //输出长度为 out[0] }
void testDES() { Block message = initBlock(64); KeySchedule k1; Block key = (unsigned char*)"12345678"; Block cifer; memset(message, 0x01, 8); k1 = DESKeySchedule(key); cifer = DESEncrypt(message, k1); //17 c1 2b 68 ab 3a a1 4c }