[ / / / / / / / / / / / / / ] [ dir / cafechan / caos / htg / leftpol / rel / stol / thestorm / ztg ][Options][ watchlist ]

/tech/ - Technology

You can now write text to your AI-generated image at https://aiproto.com It is currently free to use for Proto members.
Name
Email
Subject
Comment *
File
Select/drop/paste files here
* = required field[▶ Show post options & limits]
Confused? See the FAQ.
Expand all images

File (hide): fac4d4ef199f967⋯.png (59.44 KB, 680x680, 1:1, 9d5.png) (h) (u)

[–]

 No.849357>>849377 >>851784 [Watch Thread][Show All Posts]


//XOR Encryption

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
// Print usage and exit if args != 5
if (argc != 5)
{
printf("Usage: <input> <output> <key> <offset>\n");
return -1;
}

// Check to make sure offset is a char that can be converted to an int
int offset;
if (offset = atoi(argv[4]) == 0)
{
printf("Invalid offset argument.\n");
return -1;
}

// Attempt to open input file. Exit if not found
FILE* input;
input = fopen(argv[1], "r");
if (input == NULL)
{
printf("Input file %s was not found.\n", argv[1]);
return -1;
}

// Attempt to open output file. Exit if NULL
FILE* output;
output = fopen(argv[2], "w");
if (output == NULL)
{
printf("Error creating output file\n");
return -1;
}

printf("XOR Encrypting %s to %s\n", argv[1], argv[2]);

char* key = argv[3];
int encrypt_byte;
int key_count = 0;

// XOR
while ((encrypt_byte = fgetc(input)) != EOF)
{
fputc(encrypt_byte ^ key[offset+key_count], output);
key_count++;
if (key_count + offset == strlen(key))
{
offset = 0;
key_count = 0;
}
}

// Close input and output files and exit.
fclose(output);
fclose(input);
printf("Done.\n");
return 0;

}

 No.849360

what's the point ?


 No.849362>>849364 >>849366 >>850806

easily broken

encrypted[key_length] ^ encrypted[key_length*2] = key

https://github.com/ThomasHabets/xor-analyze


 No.849364

>>849362

>encrypted[key_length] ^ encrypted[key_length*2] = key

this is wrong but you get the idea if you read into it


 No.849366>>849368

>>849362

you still need to know the keys length to use that though.


 No.849368>>849372

>>849366

you can figure it out statistically analyzing the file. you would need a key length that's the size of the file or larger.


 No.849372

>>849368

that seems easy enough. if it's just a text file i guess read it into memory and use sizeof() or something?


 No.849375>>849387 >>849408 >>849411 >>849415

XOR encryption is perfectly secure as long as the key is randomly generated and at least as long as the message, assuming you have a secure way of sharing the key.

If the key is shorter than the message it's garbage.


 No.849377>>849379

>>849357 (OP)

t. 1st year CS student who just learned about C and encryption


 No.849379

>>849377

as a self taught guy with only a 7th grade education i'll take that as a compliment.


 No.849387>>849401 >>849408

>>849375

So it's OTP


 No.849401>>849408

>>849387

Yes. OTP is perfectly secure, and no perfectly secure encryption can be more convenient than OTP. The key space needs to be as large as the message space.


 No.849408>>849410

>>849375

>>849387

>>849401

What do you mean by this? OTP as in one-time-pad but how does it work in practice? How do you share the very long key? Why can't it be broken?


 No.849409>>850817

wow a really shitty stream cipher

look into salsa20/chacha20 for a good one

https://en.wikipedia.org/wiki/Salsa20

saged because shit thread


 No.849410>>849468

>>849408

You XOR the message with the key.

You and the recipient both need to have the key, there's no special way to share the key, which is why it's almost never used. Sharing the key securely is typically just as hard as sharing the message securely in the first place.

It can't be broken because for every ciphertext/message pair there is exactly one key which decrypts that ciphertext to that message, which means that knowing the ciphertext gives you no information about the message, other than the length.


 No.849411>>849414

>>849375

>as long as the key is randomly generated and at least as long as the message, assuming you have a secure way of sharing the key

This is why OTP isn't practical. If you have a way to secretly share a key the same length as the message you could just share the message itself.


 No.849414

>>849411

That's not always true. Sometimes you can share the key ahead of time, before there's a message to encrypt, but don't have a secure channel by the time there's a message to send. And there might be cases in which a message can be intercepted, but you'll always know if it's intercepted, in which case you can keep trying to share keys until you know one wasn't intercepted, and then use that key to encrypt the message.

Perfect secrecy isn't really better than imperfect computational secrecy, though, so even in those cases you're better off using more modern encryption. The only realistic use case for OTP I can think of is if you have to encrypt a message using pen and paper, without any sort of computer, because it's simple enough to do by hand.


 No.849415>>849416 >>849417 >>850423

>>849375

What about if the randomly generated key is 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000?


 No.849416

>>849415

highly unlikely. it is more likely that your randomly generated key xored with your message produces non-random looking output


 No.849417>>849424

>>849415

The chance of that happening is equal to the chance that they'd get the correct message by guessing it by flipping coins. There's a way larger chance that you and the recipient both die of a heart attack.

There's a far larger chance that the ciphertext appears to be a coherent message that isn't the actual message than that it is the actual message.

If the message is "Hello", then there's just as large a chance that the ciphertext is "Hello" as that it is "Vines". They still don't get any information, it's just that if they unwisely decide to interpret the ciphertext as if it's the message they would succeed in that particular astronomically unlikely case.

Excluding 0000... as the key actually gives the attacker a minimal amount of information about the message. It tells them that the ciphertext doesn't equal the message. So trying to guard against that scenario makes the encryption less secure.


 No.849424>>849426

>>849417

>he thinks the frequency with which things happen in the real world is directly proportional to their chances of happening


 No.849426>>849435

>>849424

Yes, by definition


 No.849435>>849472

>>849426

>(((definition)))

LOL. hilarious dude


 No.849468>>849490

>>849410

>Sharing the key securely is typically just as hard as sharing the message securely in the first place.

Not if the key sharing happens before you know what message you'll want to send.

For example if you know that you won't have a chance of secure communication after you decide what message you want to send.

So there may be some contrived cases where it's not completely useless.


 No.849472


 No.849490>>849494

>>849468


#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#define BUFFER 400

int main(void)
{
char s[] = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*?><";
char key[BUFFER];
int i, u;
time_t t;
srand((unsigned)time(&t));
for (i=0; i < BUFFER; i++) {
u = (double)rand() / RAND_MAX * strlen(s);
key[i] = s[u];
}
printf("%s\n", key);
return 0;
}

this generates a random key. well almost. it leaves some junk at the end. not sure why.


 No.849492>>849691 >>849939

A C program is like a fast dance on a newly waxed dance floor by people carrying razors.


 No.849494>>849496

>>849490

You need to terminate the string


key[BUFFER] = '\0';


 No.849496>>849497

>>849494

oh. should i make s and key const char instead?


 No.849497>>849501

>>849496

key changes so it can't be const.


 No.849501>>849508

>>849497

getting invalid initializer on that. might want to use strcat and stick it on the end of the key after the for loop is complete.


 No.849508>>849511

>>849501

Yeah it's used after you initialize. There's also a buffer overflow so you need to either initialize it to


char key[BUFFER+1];
// do stuff here
key[BUFFER] = '\0';

or


char key[BUFFER];
// for(etc; i < BUFFER - 1; etc ) but key size will be one less than buffer
key[BUFFER-1] = '\0';


 No.849511>>850820

>>849508

nice. seems to be working good now. just need to maybe use sizeof to get the size of the file to use as the buffer then the xor program should be able to generate it's own random key that should be the same size of the file thus making it secure.... in theory...


 No.849513>>849595 >>849945

While on the topic of 1st year CS crypto, what are some books that anons recommend on cryptography (ideally accessible to below-average undergrads)?


 No.849539>>849546

well... it compiled... heh. not sure if it actually will work though.


//XOR Encryption

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main(int argc, char* argv[])
{
// Print usage and exit if args != 5
if (argc != 4)
{
printf("Usage: <input> <output> <offset>\n");
return -1;
}

// Check to make sure offset is a char that can be converted to an int
int offset;
if (offset = atoi(argv[3]) == 0)
{
printf("Invalid offset argument.\n");
return -1;
}

// Attempt to open input file. Exit if not found
FILE* input;
input = fopen(argv[1], "r");
if (input == NULL)
{
printf("Input file %s was not found.\n", argv[1]);
return -1;
}

// Attempt to open output file. Exit if NULL
FILE* output;
output = fopen(argv[2], "w");
if (output == NULL)
{
printf("Error creating output file\n");
return -1;
}

// Generate a random key
char s[] = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*?><";
int BUFFER = sizeof(input) +1;
char key[BUFFER];
int i, u;
time_t t;
srand((unsigned)time(&t));
for (i=0; i < BUFFER; i++) {
u = (double)rand() / RAND_MAX * strlen(s);
key[i] = s[u];
}
key[BUFFER] = '\0';

// Write key to a text file
FILE* keyFile;
keyFile = fopen("key.txt", "w");
if (keyFile == NULL)
{
printf("Error writing key to file\n");
return -1;
}
fclose(keyFile);

// XOR
printf("XOR Encrypting %s to %s\n", argv[1], argv[2]);
int encrypt_byte;
int key_count = 0;
while ((encrypt_byte = fgetc(input)) != EOF)
{
fputc(encrypt_byte ^ key[offset+key_count], output);
key_count++;
if (key_count + offset == strlen(key))
{
offset = 0;
key_count = 0;
}
}

// Close input and output files and exit.
fclose(output);
fclose(input);
printf("Done.\n");
return 0;

}


 No.849546

>>849539

yea it's fucked. can't use sizeof for that. lol.


 No.849595

>>849513

Anything written by David Bentley Hart because that shit is INDECIPHERABLE.


 No.849597>>850046

looks like we might have a winner here. it seems to work. im honestly no crypto wizard so feel free to try it and tell me how shit it is or how it can be improved.


//XOR Encryption

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main(int argc, char* argv[])
{
// Print usage and exit if args != 4
if (argc != 4)
{
printf("Usage: <input> <output> <offset>\n");
return -1;
}

// Check to make sure offset is a char that can be converted to an int
int offset;
if (offset = atoi(argv[3]) == 0)
{
printf("Invalid offset argument.\n");
return -1;
}

// Attempt to open input file. Exit if not found
FILE* input;
input = fopen(argv[1], "r");
if (input == NULL)
{
printf("Input file %s was not found.\n", argv[1]);
return -1;
}

// Attempt to open output file. Exit if NULL
FILE* output;
output = fopen(argv[2], "w");
if (output == NULL)
{
printf("Error creating output file\n");
return -1;
}

// Generate a random key
char s[] = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*?><";
fseek(input, 0L, SEEK_END);
int BUFFER = ftell(input)+1;
rewind(input);
char key[BUFFER];
int i, u;
time_t t;
srand((unsigned)time(&t));
for (i=0; i < BUFFER; i++) {
u = (double)rand() / RAND_MAX * strlen(s);
key[i] = s[u];
}
key[BUFFER] = '\0';

// Write key to a text file
FILE* keyFile;
keyFile = fopen("key.txt", "w");
if (keyFile == NULL)
{
printf("Error writing key to file\n");
return -1;
}
fprintf(keyFile, "%s", key);
fclose(keyFile);
printf("Saved key to key.txt\n");

// XOR
printf("XOR %s to %s\n", argv[1], argv[2]);
int encrypt_byte;
int key_count = 0;
while ((encrypt_byte = fgetc(input)) != EOF)
{
fputc(encrypt_byte ^ key[offset+key_count], output);
key_count++;
if (key_count + offset == strlen(key))
{
offset = 0;
key_count = 0;
}
}

// Close input and output files and exit.
fclose(output);
fclose(input);
printf("Done.\n");
return 0;

}


 No.849691>>850106 >>850128 >>850830

>>849492

A C program is like a white man writing code while fast dancing on a newly waxed dance floor while the shitskins are outside taking a shit on the street.


 No.849939>>850060 >>850106 >>850830

>>849492

White people can do that safely after some training, pajeet.


 No.849945

>>849513

Handbook of Applied Cryptography by Menezes, van Oorschot and Vanstone.

http://cacr.uwaterloo.ca/hac/

There's lots of higher math in there, but it's mostly optional to read and understand. You can just skip to ready recipies and algorithms if you don't care about or understand the math behind them.


 No.850046

>>849597

using special characters in s[ ] causes problems when running this program in bash. bash can't process text input if it's got "<>!" chars in it. I removed them and it works fine. The key is still going to be secure alpha numeric with upper and lower case anyway.


 No.850060>>850106

>>849939

And he won't get anything done without a humongous expense. All the training in the world doesn't change the fact that there is a real burden placed upon the brain.


 No.850101

Been tinkering with it some more. The last one i posted works but needs a separate program to decrypt it. This one does encryption and decryption but it's no decrypting correctly at the moment.


//XOR Encryption

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

// Max amount of chars that can be read from an input file
#define MAX_CHARS 100000

FILE* input;
FILE* output;

int openFiles(const char* inputFileName, const char* outputFileName)
{
// Attempt to open input file. Exit if not found
input = fopen(inputFileName, "r");
if (input == NULL)
{
printf("Input file %s was not found.\n", inputFileName);
return -1;
}

// Attempt to open output file. Exit if NULL
output = fopen(outputFileName, "w");
if (output == NULL)
{
printf("Error creating output file\n");
return -1;
}
return 0;
}

void xor(char* key, int offset)
{
// XOR
int encrypt_byte;
int key_count = 0;
while ((encrypt_byte = fgetc(input)) != EOF)
{
fputc(encrypt_byte ^ key[offset+key_count], output);
key_count++;
if (key_count + offset == strlen(key))
{
offset = 0;
key_count = 0;
}
}
}

int genKey(int offset)
{
// Generate a random key
char s[] = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
fseek(input, 0L, SEEK_END);
int BUFFER = ftell(input)+1;
rewind(input);
char key[BUFFER];
int i, u;
time_t t;
srand((unsigned)time(&t));
for (i=0; i < BUFFER; i++) {
u = (double)rand() / RAND_MAX * strlen(s);
key[i] = s[u];
}
key[BUFFER] = '\0';

// Write key to a text file
FILE* keyFile;
keyFile = fopen("key.txt", "w");
if (keyFile == NULL)
{
printf("Error writing key to file\n");
fclose(input);
fclose(output);
return -1;
}
fprintf(keyFile, "%s", key);
fclose(keyFile);
printf("Saved key to key.txt\n");

// Send key to xor function
xor(key, offset);
return 0;
}

int main(int argc, char* argv[])
{
// Print usage and exit if args < 4
if (argc < 4)
{
printf("Usage: <input> <output> <offset> <decrypt mode=1> <keyfile>\n");
printf("Encryption example: unencrypted.txt encrypted.txt 4\n");
printf("Decryption example: encrypted.txt decrypted.txt 4 1 key.txt\n");
return -1;
}

// Handle null args
if (argv[4] == NULL || argv[5] == NULL)
{
argv[4] = "2";
argv[5] = "nothing";
}

// Check to make sure offset is a char that can be converted to an int
int offset;
if (offset = atoi(argv[3]) == 0)
{
printf("Invalid offset argument.\n");
return -1;
}

// Decryption
// Check to make sure mode is char that can be converted to an int
int mode;
if (mode = atoi(argv[4]) == 0)
{
printf("Invalid mode number\n");
return -1;
} else if (mode == 1){
// Attempt to open key file. Exit if not found
FILE* keyFile;
keyFile = fopen(argv[5], "r");
if (keyFile == NULL)
{
printf("Keyfile %s was not found.\n", argv[5]);
return -1;
}
// Read in the key from the key file
char* keybuf;
keybuf = (char*) malloc(MAX_CHARS+1);
if (keybuf == NULL)
{
printf("Couldn't allocate memory. Aborting...\n");
fclose(keyFile);
return -1;
}
printf("Attempting to read from input file.\n");
while (fgets(keybuf, MAX_CHARS, keyFile)!=NULL);
keybuf[MAX_CHARS+1] = '\0';

// Open input and output files
if (openFiles(argv[1], argv[2]) == -1)
{
free(keybuf);
return -1;
}

// call xor function
printf("XOR %s to %s\n", argv[1], argv[2]);
xor(keybuf, offset);
free(keybuf);
}

// Encryption
if (openFiles(argv[1], argv[2]) == -1)
{
return -1;
}

// Call genKey to generate a key and start the xor operation
printf("XOR %s to %s\n", argv[1], argv[2]);
genKey(offset);

// Close input and output files and exit.
fclose(output);
fclose(input);
printf("Done.\n");
return 0;

}


 No.850106>>850110 >>850830

>>850060

>do something impressive and daring that defies normal human limitations

<s..stop it! it's dangerous! it's too expensive! i..it's a burden on your brain!

I think >>849691 and >>849939 are onto something here. That is a very non-white way to think. I guess any thought more complex than planning in which designated street to poo risks giving the average Pajeet a mental cramp.


 No.850110>>850112

>>850106

Shell shock

Heart bleed


 No.850112>>850127

>>850110

<some people wrote very poor code a long time ago, so let's all program in straight jackets! it's for your safety bro

OpenSSL is just kind of a fucking mess, by the way.


 No.850127

>>850112

You're willfully missing the point. The point is that you can't just say "I'm a white man, I do things perfectly". There is a cost to everything. For the vast majority of application software, we don't need to invest the effort to achieve the work in C. There's thinking about application logic and then there's C memory booking that's applied on top of that work. It is this fetishistic approach that "all our work must be done in C and we will do it perfectly" that inherently implies two things: doing it correctly will take forever to achieve thus nobody will get any work done: doing it quickly means . It doesn't have to be this way, all it takes is to let go of the C fetish for anything that doesn't demand such a big rigor. 10/10


 No.850128

>>849691

A C program is like Dennis Ritchie taking a shit on a white man writing code while fast dancing on a newly waxed dance floor.


 No.850320>>850322 >>850651 >>851165

Well looks like it's working now. It successfully encrypted and decrypted a text file. Use it and abuse it. I'd like to know if it's any good or not so i can encrypt my passwords with it.


//XOR Encryption

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

// Max amount of chars that can be read from an input file
#define MAX_CHARS 100000

FILE* input;
FILE* output;

int openFiles(const char* inputFileName, const char* outputFileName)
{
// Attempt to open input file. Exit if not found
input = fopen(inputFileName, "r");
if (input == NULL)
{
printf("Input file %s was not found.\n", inputFileName);
return -1;
}

// Attempt to open output file. Exit if NULL
output = fopen(outputFileName, "w");
if (output == NULL)
{
printf("Error creating output file\n");
return -1;
}
return 0;
}

void xor(char* key, int offset)
{
// XOR
int encrypt_byte;
int key_count = 0;
while ((encrypt_byte = fgetc(input)) != EOF)
{
fputc(encrypt_byte ^ key[offset+key_count], output);
key_count++;
if (key_count + offset == strlen(key))
{
offset = 0;
key_count = 0;
}
}
}

int genKey(int offset)
{
// Generate a random key
char s[] = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
fseek(input, 0L, SEEK_END);
int BUFFER = ftell(input)+1;
rewind(input);
char key[BUFFER];
int i, u;
time_t t;
srand((unsigned)time(&t));
for (i=0; i < BUFFER; i++) {
u = (double)rand() / RAND_MAX * strlen(s);
key[i] = s[u];
}
key[BUFFER] = '\0';

// Write key to a text file
FILE* keyFile;
keyFile = fopen("key.txt", "w");
if (keyFile == NULL)
{
printf("Error writing key to file\n");
fclose(input);
fclose(output);
return -1;
}
fprintf(keyFile, "%s", key);
fclose(keyFile);
printf("Saved key to key.txt\n");

// Send key to xor function
xor(key, offset);
return 0;
}

int main(int argc, char* argv[])
{
// Print usage and exit if args < 4
if (argc < 4)
{
printf("Usage: <input> <output> <offset> <decrypt mode=1> <keyfile>\n");
printf("Encryption example: unencrypted.txt encrypted.txt 4\n");
printf("Decryption example: encrypted.txt decrypted.txt 4 1 key.txt\n");
return -1;
}

// Handle null args
if (argv[4] == NULL || argv[5] == NULL)
{
argv[4] = "2";
argv[5] = "nothing";
}

// Check to make sure offset is a char that can be converted to an int
int offset;
if (offset = atoi(argv[3]) == 0)
{
printf("Invalid offset argument.\n");
return -1;
}

// Decryption
// Check to make sure mode is char that can be converted to an int
int mode;
/*
THIS KEEPS THE USER FROM INPUTING AN INVALID CHAR BUT HAD TO BE REMOVED-
BECAUSE IT SCREWS UP EVERYTHING FOR SOME REASON IDK WHY.
if (mode = atoi(argv[4]) == 0)
{
printf("Invalid mode number\n");
return -1;
}*/
mode = atoi(argv[4]);
if (mode == 1)
{
// Attempt to open key file. Exit if not found
FILE* keyFile;
keyFile = fopen(argv[5], "r");
if (keyFile == NULL)
{
printf("Keyfile %s was not found.\n", argv[5]);
return -1;
}
// Read in the key from the key file
char* keybuf;
keybuf = (char*) malloc(MAX_CHARS+1);
if (keybuf == NULL)
{
printf("Couldn't allocate memory. Aborting...\n");
fclose(keyFile);
return -1;
}
printf("Reading key from %s\n", argv[5]);
//while (fgets(keybuf, MAX_CHARS, keyFile)!=NULL);
fscanf(keyFile, "%s", keybuf);
keybuf[MAX_CHARS] = '\0';

// Open input and output files
if (openFiles(argv[1], argv[2]) == -1)
{
free(keybuf);
return -1;
}

// call xor function
printf("XOR %s to %s\n", argv[1], argv[2]);
xor(keybuf, offset);
free(keybuf);
}

// Encryption
if (openFiles(argv[1], argv[2]) == -1)
{
return -1;
}

if (mode != 1)
{
// Call genKey to generate a key and start the xor operation
printf("XOR %s to %s\n", argv[1], argv[2]);
genKey(offset);
}

// Close input and output files and exit.
fclose(output);
fclose(input);
printf("Done.\n");
return 0;

}


 No.850322

File (hide): 9e2b8a1ac39c4d9⋯.png (80.72 KB, 788x382, 394:191, working.png) (h) (u)


 No.850423>>850590

>>849415

all crypto is only probablistically secure, and they're much weaker than getting 9000 0's as a key.


 No.850590

>>850423

>all crypto is only probablistically secure

what?

The reason why get an all 0 key is not an issue is that the all 0 key is not the only key that gives a valid message. Imagine if you intercepted an encrypted message and it said god. There is no way to prove if the original message was god (all 0 key) or if it could have been any other three letter word like red, dog, or Ben for example. If you have a very long input, there are tons of false messages which look correct.


 No.850651>>850793

>>850320

>rand

rand is not a CSPRNG. This is just as bad as your first version.

Just stop, my dude.


 No.850793>>850796

>>850651

works on my machine.


 No.850796>>850804

>>850793

Yeah. It will work on NSA's machines too.


 No.850804>>850806

>>850796

why do not trust /dev/urandom? i know it's no a true RNG but why do you not think it's good enough to generate a key? the only problem i see in my implementation is that if you run the genkey function say in a for loop it will generate the same key because it uses time to seed it. so if it happens to fast the seed doesn't change and it makes the same key again. but that's unlikely to happen in the program i posted above.

but your argument all comes down to not trusting /dev/urandom.


 No.850806>>850807

>>850804

I do trust /dev/urandom but you are using rand.

Also no matter how you generate the key, if the message is longer than the key you can trivially compute the key. See >>849362

Kill yourself, my dude.


 No.850807>>850808

>>850806

the key should always be longer than the message in my code.


 No.850808>>850810

>>850807

Doesn't matter as you are using rand to generate it.


 No.850810>>850813


 No.850813>>850816

>>850810

Doesn't matter because rand isn't a CSPRNG.


 No.850816>>850817


 No.850817>>850818 >>850824

>>850816

Yes. But your gen_key function is still shit because you are fucking about withou floating point numbers and ASCII characters. Just xor the raw bytes together.

Even if you fix this your program is still unpractical because the keyfile is as long as your plain/ciphertext.

See >>849409


 No.850818

>>850817

>withou

with


 No.850820>>850822

File (hide): 625da88ebbc04b1⋯.png (396.08 KB, 600x850, 12:17, topnep.png) (h) (u)

>>849511

>just need to maybe use sizeof to get the size of the file


 No.850822

>>850820

don't laugh at me. i've only been learning C for 2 weeks.


 No.850824>>850825

>>850817

> because the keyfile is as long as your plain/ciphertext.

that is true but that wouldn't matter if i never planned to share the key. that sort of attack would depend on the attacker having access to the key file.


 No.850825>>850826

>>850824

I said it is unpractical. I wasn't speaking of an attack.


 No.850826

>>850825

i just ASCII would be easier to use because in my first version it took the key as an argument to decrpyt it. but this version just reads it in from a file so the user never really needs to interact with it.


 No.850830

>>849691

>>849939

>>850106

I love this board and all of you faggots. Never change.


 No.850894>>850895 >>850907 >>850916 >>851022

I wrote an actually secure file encryption program in Rust:

use std::cmp::min;
use std::fmt::Display;
use std::io::{self, Read, Write};
use std::ops::{Deref, DerefMut};

const RATE: usize = 16;
const CHUNK_LEN: usize = RATE * 256;
const USAGE: &str = "Usage: decrypt|encrypt <password>";

struct Wrapper(State);
#[derive(Default)] struct State([u32; 32]);

impl Wrapper {
fn new(mut key: &[u8]) -> Self {
let mut state = State::default();
loop {
let len = min(RATE, key.len()); xor(&mut state[..len], &key[..len]);
if len < RATE { state[len] ^= 1; }
state[RATE] ^= 0x80; state.permute();
key = &key[len..]; if key.is_empty() { break; }
} Wrapper(state)
}

fn wrap(&mut self, data: &mut [u8]) -> &[u8] { self.wrap_impl(data, <[u8]>::copy_from_slice) }

fn unwrap(&mut self, data: &mut [u8], tag: &[u8]) -> Result<(), ()> { assert!(tag.len() == RATE);
if tag == self.wrap_impl(data, xor) { Ok(()) } else { Err(()) }
}

fn wrap_impl(&mut self, data: &mut [u8], f: fn(&mut [u8], &[u8])) -> &[u8] {
let index = if !data.is_empty() {
let mut chunks = data.chunks_mut(RATE); let last_chunk = chunks.next_back().unwrap();
for chunk in chunks {
xor(chunk, &self.0[..RATE]); f(&mut self.0[..RATE], chunk);
self.0[RATE] ^= 0x80; self.0.permute();
}

let len = last_chunk.len();
xor(last_chunk, &self.0[..len]); f(&mut self.0[..len], last_chunk); len
} else { 0 };

self.0[index] ^= 1; self.0[RATE] ^= 0x80; self.0.permute(); &self.0[..RATE]
}
}

impl State {
fn permute(&mut self) {
macro_rules! i { ($a:expr, $b:expr, $c:expr, $d:expr, $e:expr) => { ($a << 4) | ($b << 3) | ($c << 2) | ($d << 1) | $e } }
macro_rules! s { ($a:expr, $b:expr, $c:expr, $d:expr, $e:expr) => { self.0[i!($a, $b, $c, $d, $e)] } }

for _ in 0..32 { for j in 0..1 { for k in 0..1 { for l in 0..1 { for m in 0..1 {
s!(1, j, k, l, m) = s!(1, j, k, l, m).wrapping_add(s!(0, j, k, l, m));
s!(0, j, k, l, m) = s!(0, j, k, l, m).rotate_left(7);
self.0.swap(i!(0, 0, k, l, m), i!(0, 1, k, l, m));
s!(0, j, k, l, m) ^= s!(1, j, k, l, m);
self.0.swap(i!(1, j, k, 0, m), i!(1, j, k, 1, m));
s!(1, j, k, l, m) = s!(1, j, k, l, m).wrapping_add(s!(0, j, k, l, m));
s!(0, j, k, l, m) = s!(0, j, k, l, m).rotate_left(11);
self.0.swap(i!(0, j, 0, l, m), i!(0, j, 1, l, m));
s!(0, j, k, l, m) ^= s!(1, j, k, l, m);
self.0.swap(i!(1, j, k, l, 0), i!(1, j, k, l, 1));
}}}}}
}
}

impl Deref for State { type Target = [u8];
fn deref(&self) -> &Self::Target { unsafe { &*(self.0.as_ptr() as *const [u32; 32] as *const [u8; 128]) } }
}

impl DerefMut for State {
fn deref_mut(&mut self) -> &mut Self::Target { unsafe { &mut *(self.0.as_mut_ptr() as *mut [u32; 32] as *mut [u8; 128]) } }
}

fn main() {
let args = std::env::args().skip(1); if args.len() != 2 { eprintln!("{}", USAGE); return; }
if let Err(e) = run(args) { eprintln!("{}", e); }
}

fn run<I: Iterator<Item = String>>(mut args: I) -> Result<(), Box<Display>> {
let f = match &*args.next().unwrap() { "decrypt" => { decrypt } "encrypt" => { encrypt } _ => { return Err(Box::new(USAGE)); } };
if let Err(e) = f(&mut Wrapper::new(args.next().unwrap().as_bytes()), &mut io::stdin(), &mut io::stdout()) { return Err(Box::new(e)); }
Ok(())
}

fn decrypt<R: Read, W: Write>(wrapper: &mut Wrapper, reader: &mut R, writer: &mut W) -> io::Result<()> {
let mut buf = [0; CHUNK_LEN];
loop {
let len = fill_buf(reader, &mut buf)?; if len < RATE { return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "")); }
{
let (data, tag) = buf.split_at_mut(len - RATE);
wrapper.unwrap(data, &tag[..RATE]).map_err(|()| io::Error::new(io::ErrorKind::InvalidData, "tag mismatch"))?;
}
writer.write_all(&buf[..len - RATE])?; if len < CHUNK_LEN { return Ok(()); }
}
}

fn encrypt<R: Read, W: Write>(wrapper: &mut Wrapper, reader: &mut R, writer: &mut W) -> io::Result<()> {
let mut buf = [0; CHUNK_LEN];
loop {
let len = fill_buf(reader, &mut buf[..CHUNK_LEN - RATE])?;
let tag = wrapper.wrap(&mut buf[..len]); buf[len..][..RATE].copy_from_slice(tag);
writer.write_all(&buf[..len + RATE])?; if len < CHUNK_LEN - RATE { return Ok(()); }
}
}

fn fill_buf<R: Read>(reader: &mut R, mut buf: &mut [u8]) -> io::Result<usize> {
let len = buf.len();
while !buf.is_empty() {
match reader.read(buf) {
Ok(0) => { break; } Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {} Err(e) => { return Err(e); }
}
}
Ok(len - buf.len())
}

fn xor(dst: &mut [u8], src: &[u8]) {
assert!(dst.len() == src.len());
unsafe { for i in 0..dst.len() { *dst.get_unchecked_mut(i) ^= *src.get_unchecked(i); } }
}


 No.850895>>851043

>>850894

>muuuuuuuh syntax

I had to agressively compress it vertically.


 No.850907>>851043


 No.850916>>851043

>>850894

this makes me love C even more.


 No.851022>>851043

>>850894

looks disgusting. i might would use it if you port it to C. I ain't touching that rust sjw shit language.


 No.851043

>>850907

>>850895

>>850916

>>851022

>whining about superficial shit like ugly syntax

top LARP.


 No.851156>>851171 >>851188 >>851195


//Double XOR Encryption

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
// Print usage and exit if args != 5
if (argc != 5)
{
printf("Usage: <input> <output> <key> <offset>\n");
return -1;
}

// Check to make sure offset is a char that can be converted to an int
int offset;
if (offset = atoi(argv[4]) == 0)
{
printf("Invalid offset argument.\n");
return -1;
}

// Attempt to open input file. Exit if not found
FILE* input;
input = fopen(argv[1], "r");
if (input == NULL)
{
printf("Input file %s was not found.\n", argv[1]);
return -1;
}

// Attempt to open output file. Exit if NULL
FILE* output;
output = fopen(argv[2], "w");
if (output == NULL)
{
printf("Error creating output file\n");
return -1;
}

printf("Double XOR Encrypting %s to %s\n", argv[1], argv[2]);

char* key = argv[3];
int encrypt_byte;
int key_count = 0;

// XOR
while ((encrypt_byte = fgetc(input)) != EOF)
{
fputc(encrypt_byte ^ key[offset+key_count] ^ key[offset+key_count], output);
key_count++;
if (key_count + offset == strlen(key))
{
offset = 0;
key_count = 0;
}
}

// Close input and output files and exit.
fclose(output);
fclose(input);
printf("Done.\n");
return 0;
}


 No.851165>>851171

>>850320

maybe try this


#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char **argv){
int rng;
int urnd = open("/dev/random", O_RDONLY);
read(urnd, &rng, sizeof(int));
close(urnd);
printf("%d\n", rng);
return 0;
}


 No.851171


 No.851188>>851190

>>851156

seems like overkill but ok. one xor should be sufficient.


 No.851190>>851192

>>851188

Modern CPUs have no problem doing two xor ops in one cycle.


 No.851192>>851195

>>851190

just adds needless complication. if one xor will do why use two? now you need two keys. and more lines of code to make it all work.


 No.851195>>851198

>>851192

>needless complication

It is just an additional xor.

>if one xor will do why use two?

To keep the CIA niggers out of my stuff????

>now you need two keys

and more lines of code to make it all work

look again >>851156


 No.851198>>851337

>>851195

ok. lets make a quadruple xor program that uses /dev/urandom to generate the keys and automatically encrypt the loli folders.


 No.851337>>851339

>>851198

why not xor the file N times against the file length key on rotating increment N times.


 No.851339>>851443

>>851337

or rotating offset is a better way to word it.


 No.851443>>851553

>>851339

i guess you could make it do that but then you would also need to use a json to store the key and offset value it used and then another function to read that json in. parse it. and use the data to decrypt. not worth the effort imho.


 No.851553>>851558

>>851443

no, just rotate through every possible offset in the key. if the key and file are 1000 bytes long.

put an if somewhere if i+offset > key length, loop around to 0 and start there.

offset=0

key[0+offset]^file[0]=result[0]

...

key[999+offset]^file[999]=result[999]

offset=1

key[0+offset]^result[0]=result[0]

...

key[999+offset]^result[999]=result[999]

offset=2

key[0+offset]^result[0]=result[0]

key[999+offset]^result[999]=result[999]

...

etc


 No.851558>>851848

>>851553

Brilliant. But do double xor. Like this: key[i+offset]^file[i]^key[i+offset]=result[i]

That way it is also protected from the right side.


 No.851784

>>849357 (OP)

>if (key_count + offset == strlen(key)) { ... }

Should be

> { printf("Key too short"); return -1; }


 No.851848

>>851558

if you xor the key twice then it neutralizes itself. but you could do and rotate the offset on the second key too.

key[i+offset]^file[i]^key[i+offset+j ]=result[i]




[Return][Go to top][Catalog][Screencap][Nerve Center][Cancer][Update] ( Scroll to new posts) ( Auto) 5
91 replies | 3 images | Page ?
[Post a Reply]
[ / / / / / / / / / / / / / ] [ dir / cafechan / caos / htg / leftpol / rel / stol / thestorm / ztg ][ watchlist ]