Unix Programming - Re: Right way of using setkey(3) and encrypt(3)

This is Interesting: Free IT Magazines  
Home > Archive > Unix Programming > December 2004 > Re: Right way of using setkey(3) and encrypt(3)





You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

Author Re: Right way of using setkey(3) and encrypt(3)
cnystrom@gmail.com

2004-12-17, 2:49 am


Wayne C. Morris wrote:

> For a more practical program, you'd want to add functions to convert

an
> 8-byte string into a 64-byte array of 1's and 0's, and vice versa.


Here is my solution. Comments welcome.

I suppose the next step is to come up with some code that packs strings
into 8 byte chuncks and back for encryption processing.

Chris

--

/*
* des.c
*
* Example code to use the unix encypt() function.
*
* 2004 Chris Nystrom (cnystrom@gmail.com)
*
* Public Domain
*
* Thank you to Wayne C. Morris for assistance.
*
* $ gcc -lcrypt des.c
* $ ./a.out
*
*/

#include <stdio.h>
#include <crypt.h>

#define ENCODE (0)
#define DECODE (1)

int
power(int base, int n)
{
int p;

for (p = 1; n > 0; --n)
p = p * base;

return p;
}

void
byte2bin(char *s, unsigned char b)
{
int i;
unsigned char mask = 0x80;

for (i = 0; i < 8; ++i) {
if (b & mask)
*(s + i) = '\1';
else
*(s + i) = '\0';

mask >>= 1;
}
}

int
bin2byte(char *s)
{
int i, j, ret = 0;

for (i = 0; i < 8; i++) {
if (*(s + i) == '\1') {
j = 7 - i;
ret += power(2, j);
}
}

return(ret);
}

void
encode(char *s_out, char *s_in)
{
int i, j = 0;
char tmp[9];

for (i = 0; i < 8; i++) {
j = (i * 8);

byte2bin(s_out + j, *(s_in + i));
}
}

void
decode(char *s_out, char *s_in)
{
int i, j = 0;

for (i = 0; i < 8; i++) {
j = (i * 8);
*(s_out + i) = bin2byte(s_in + j);
}
}

void display_bitmap(char *msg)
{
int i;

for (i = 0; i < 64; i++) {
printf( "%1d", (msg[i] ? 1 : 0) );
}

printf("\n");
}

int main()
{
int i, j = 0;

char key_in[9] = "12345678";
char txt_in[9] = "abcdefgh";
char txt_out[9];
char key[64]; // bit pattern for key
char txt[64]; // bit pattern for message

printf("txt_in = |%s|\n", txt_in);

encode(key, key_in);
encode(txt, txt_in);

setkey(key);

// display_bitmap(txt);

encrypt(txt, ENCODE);

// display_bitmap(txt);

decode(txt_out, txt);
txt_out[8] = '\0';
printf("txt_out (encoded) = |%s|\n", txt_out);

encrypt(txt, DECODE);

// display_bitmap(txt);

decode(txt_out, txt);
txt_out[8] = '\0';
printf("txt_out (decoded) = |%s|\n", txt_out);
}

--
cnystrom@gmail.com
Chris Nystrom

Sponsored Links






Free braindumps | Software forum | Database administration forum

Copyright 2003 - 2008 webservertalk.com