Von C nach Java, Teil 4: Datenkompression und Verschlüsselung

Seite 5: Listing 1

Inhaltsverzeichnis
#include <stdio.h>
#include <malloc.h>
#include <errno.h>

#define BUFLEN 1024*1024

int main(int argc, char *argv[]) {
int argcnt=1;
char *passwd=NULL, *argstr, fileName[280];
unsigned char *buffer;

if (argc < 3) {
fprintf(stderr,"usage: %s password file ...\n", argv[0]);
exit(1);
}
if ((buffer=malloc(BUFLEN))==NULL) {
fprintf(stderr,"unable to allocate buffer: malloc()
failed with %d: %s\n", errno, strerror(errno));
exit(errno);
}
while (--argc) {
FILE *ifp, *ofp;
int i, rb;
long seed=0;

argstr=argv[argcnt++];
if (!passwd) {
passwd=argstr;
continue;
}
strcpy(fileName, argstr);
for (i=0;i<strlen(passwd);i++) {
seed <<=5; seed |= passwd[i];
}
srand(seed);
if ((ifp=fopen(fileName,"rb"))==NULL) {
fprintf(stderr,"cannot open \"%s\": fopen() returned %d:
%s\n", fileName, errno, strerror(errno));
exit(errno);
}
strcat(fileName,".crypt");
if ((ofp=fopen(fileName,"wb"))==NULL) {
fprintf(stderr,"cannot open \"%s\": fopen() returned %d:
%s\n", fileName, errno, strerror(errno));
exit(errno);
}
while ((rb=fread(buffer, 1, BUFLEN, ifp))>0) {
for (i=0;i<rb;i++) {
buffer[i] = buffer[i] ^ ~rand();
}
fwrite(buffer, 1, rb, ofp);
}
fclose(ifp);
fclose(ofp);
}
}