The way to see if you are close is to try it out. I used this short program to test out your encoder:
Code:
#include <stdlib.h>
#include <stdio.h>
void decrypt (unsigned char buf[37])
{
unsigned int nBitNr;
unsigned int nIndex = 4;
unsigned int nKey = (unsigned int)buf[3] << 24;
nKey |= (unsigned int)buf[2] << 16;
nKey |= (unsigned int)buf[1] << 8;
nKey |= (unsigned int)buf[0];
for(nBitNr = 0; nBitNr < 32; ++nBitNr, nIndex++)
{
int nDecryptBit = (nKey & (1 << nBitNr)) >> nBitNr;
int chEncryptedByte = buf[nIndex];
int chDecryptedByte = chEncryptedByte;
chDecryptedByte = chDecryptedByte ^ nDecryptBit;
chDecryptedByte = chDecryptedByte & 1;
chDecryptedByte = chDecryptedByte ^ chEncryptedByte;
buf[nIndex] = chDecryptedByte;
if(nBitNr == 31)
break;
}
buf[36] = '\0'; /* added to make sure the string is properly terminated */
printf("File Decrypted is %s\n",buf);
}
void cruxisEncrypt (char buf[37])
{
unsigned int nBitNr;
unsigned int nIndex = 4;
for(nBitNr = 0; nBitNr < 32; ++nBitNr, nIndex++)
{
// make key ???
unsigned int nKey = buf[nIndex] << 1 | (buf[nIndex] & 1);
int nEncryptBit = (nKey >> nBitNr) & 1;
int chEncryptedByte = nEncryptBit ^ buf[4+nIndex];
buf[4+nIndex] = chEncryptedByte;
if(nBitNr == 31)
break;
}
printf("File Encrypted is %s\n",buf);
}
void davtEncrypt (char buf[37])
{
unsigned int i;
for (i = 35; i > 3; i--) {
buf[(i-4)/8] = (buf[(i-4)/8] << 1) | (buf[i] & 1);
buf[i] ^= rand() % 2;
}
buf[36] = '\0'; /* shouldn't need this line - but just in case... */
printf("File Encrypted is %s\n", buf);
}
int main (void)
{
char buf[37] = "key*This is my plaintext. How dull!!";
// davtEncrypt(buf);
cruxisEncrypt(buf);
decrypt(buf);
return 0;
}
Notice that I have had to make some changes to the code to get it to compile - some because my compiler is pre-C99 and some because it just won't work. Here is what I get as output:
Code:
File Encrypted is key*This is my!plaintext. How dull!!
File Decrypted is key*Uihs is mx!plainudxu/!Inv!dulm
Which is clearly not right. Using my function gives:
Code:
File Encrypted is lce¬Tihs hs ly ql`ioudyu/!How dtll
File Decrypted is lce¬This is my plaintext. How dull!!
Which shows that it works. (note that the first 4 symbols above are not right - I couldn't type the actual values produced by the program). All my code does is store the least significant bit of each character in the key and randomly mess up the least significant bit of each character in the message. The decrypt algorithm can be simplified to:
Code:
void decrypt (char buf[37])
{
unsigned int i;
for (i = 0; i < 32; i++) {
unsigned int keyBit = ((buf[i/8] >> (i%8)) & 1);
buf[i+4] &= (~1); /* clear lsb */
buf[i+4] |= keyBit; /* set lsb = keyBit */
}
buf[36] = '\0';
printf("File Decrypted is %s\n", buf);
}