r/dailyprogrammer • u/jnazario 2 0 • Jul 08 '15
[2015-07-08] Challenge #222 [Intermediate] Simple Stream Cipher
Description
Stream ciphers like RC4 operate very simply: they have a strong psuedo-random number generator that takes a key and produces a sequence of psuedo-random bytes as long as the message to be encoded, which is then XORed against the plaintext to provide the cipher text. The strength of the cipher then depends on the strength of the generated stream of bytes - its randomness (or lack thereof) can lead to the text being recoverable.
Challenge Inputs and Outputs
Your program should have the following components:
- A psuedo-random number generator which takes a key and produces a consistent stream of psuedo-random bytes. A very simple one to implement is the linear congruential generator (LCG).
- An "encrypt" function (or method) that takes a key and a plaintext and returns a ciphertext.
- A "decrypt" function (or method) that takes a key and the ciphertext and returns the plaintext.
An example use of this API might look like this (in Python):
key = 31337
msg = "Attack at dawn"
ciphertext = enc(msg, key)
# send to a recipient
# this is on a recipient's side
plaintext = dec(ciphertext, key)At this point, plaintext should equal the original msg value.
2
u/brainiac1530 Jul 08 '15 edited Jul 09 '15
It seems like too many people are taking the specification too literally. Basically every language has some sort of pseudo-RNG built in, and it will generally outperform whatever you hack together yourself. Even Python's RNG is based on a mersenne twister, which is better in basically every way. In particular, the most common LCG's are known to have poor randomness in the lowest bits, which is terrible for this. Here's my take on it in C++11. Edit: Added a Blum-Blum-Shub pseudo-RNG for novelty's sake. Even though it doesn't have quite the full interface the standard library generators have, it really ballooned the length. Also, I leave the implementation of modular exponentiation and LCM functions as an exercise to the (interested) reader.
10
u/skeeto -9 8 Jul 08 '15 edited Jul 08 '15
If you find RC4 interesting, be sure to check out the new Spritz cipher, also by Ron Rivest. It's an updated version on the same concept. It doesn't have the same flaws as RC4 and, one of the neatest parts, is that it was designed by a computer. They ran many different combinations of operators through a gauntlet of statistical tests and picked the combination with the best results.
The paper is very approachable so I highly recommend reading it!
7
u/wizao 1 0 Jul 08 '15 edited Jul 08 '15
Haskell:
And using
lcginstead ofmkStdGen:1
u/jnazario 2 0 Jul 08 '15
Python
1
u/jnazario 2 0 Jul 08 '15
a simple scala solution
and its usage:
4
u/Hells_Bell10 Jul 08 '15 edited Jul 08 '15
C++
3
u/dp_account Jul 08 '15
Python3.4
Usage:
Output:
3
u/kirsybuu 0 1 Jul 08 '15
D Language, using ANSIC LCG because I can:
3
u/psygate Jul 08 '15
Python 3. Implementation of an rc4 cipher. Pretty simple. and has all the problems that come with rc4.
2
u/HereBehindMyWall Jul 08 '15 edited Jul 08 '15
Python 3 solution. Note that enc takes a 'str', encodes it with UTF-8 and then applies the cipher and returns a 'bytes'.
2
u/bdforbes Jul 08 '15
Mathematica
2
u/[deleted] Jul 08 '15
Solution in Haskell, using the Xorshift* generator. This was actually easier than I first thought it would be. My implementation supports unicode, but there is a problem with it: Most of the wrong keys, if not all, can be eliminated by only checking the first character, since a wrong decryption usually leads to characters that are outside the range of a Char.
2
u/Hyperspot Jul 08 '15
My Java solution
2
u/Backerupper Jul 08 '15
First submission here, C. I used the xorshift* pseudorandom generator because it is so pretty and simple.
When run it provides:
2
u/carlfish Jul 08 '15 edited Jul 08 '15
scalaz-stream. Overkill, but I thought it came out quite elegantly, and the core crypt() function can handle infinite streams. Wrapper functions assume UTF-8 for brevity. Like all home-built RNGs, assume it's catastrophically broken. :)
2
u/kikibobo Jul 08 '15 edited Jul 09 '15
Rewritten to use scala Streams, inspired by the /u/carlfish's cool scalaz example:
Output:
2
u/superfunny Jul 09 '15 edited Jul 09 '15
My first attempt in C#:
Console Results:
2
u/zod77 Jul 09 '15
Python 3
2
u/AdmissibleHeuristic 0 1 Jul 09 '15
Python 3 An opaque RC4 implementation, as well as a completely arbitrary stream cipher designed with no considerations in mind whatsoever.
2
u/JakDrako Jul 09 '15
VB.Net
I made two versions: A simple one that implements the requirements as described and a "salted" version.
The salted version runs the LCG to "burn" some numbers then gets a few of them to create the salt. The salt is added to the key and then that modified key is used to encrypt the plaintext. The result is that encrypting the same plaintext with the same key will give different bytes each time.
Results
1
u/cpp_daily Jul 08 '15
C++
1
u/ehcubed Jul 08 '15
Python 3.
Code:
Output:
1
u/linkazoid Jul 08 '15
Did some research, but still had some trouble grasping Stream Ciphers. I'm not sure if I did this right, but I tried implementing the LCG for my psuedo-random number generator. It encrypts the message, and decrypts it, but I don't know if it is implemented correctly. Written in Ruby.
Output
1
u/Godspiral 3 3 Jul 08 '15 edited Jul 08 '15
in J,
uses a string key. Meant to be localized (inside class) ,but stripping it out for simplicity.
lcgFree generates a lcg function that can be saved, but also updates a roll function and seed value within the caller's locale. Its not my favorite lcg, but its the one with fewest dependencies.
with key 'asdf', I'm using just the first 32 bytes (parameter) of sha512 of the key to create a 256bit (32*8) extended integer. The initial seed is set to half this value.
2 multipliers are created:
1 is 4/3 the hash value (and made even), the other is a crc32 of the hash value (signed crc32 version). These are multiplied with the seed and summed before reduced by modulus. The modulus is double the hash value -1 (so odd)
The parameter to the lcg is a list of maximum ranges to return
164 146 241 43 72 192 35 149 66 230
applying function twice
Attack at dawn
also works on structured/boxed input
1
u/[deleted] Jul 08 '15 edited Jul 08 '15
Elixir:
Output:
I think that is correct? Any feedback appreciated
1
u/Stan-It Jul 08 '15
Scala:
1
u/Yulfy Jul 08 '15
C# Solution
Haven't written C# in a while so I was rusty on some syntax. It just uses a basic LCG to generate the sequences.
The code, as it always is for me, is in this gist to save space. :)
It can be used fully from CMD, most of code is actually making sure the user doesn't enter something silly. the only thing not checked is the message from the user.
Feedback is welcome! :)
1
u/glenbolake 2 0 Jul 08 '15
Python 2.7. I elected to use this as a chance to practice with sockets, so my encoder and decoder are in separate scripts, although it breaks the DRY rule as a result.
sender.py:
receiver.py:
1
u/marchelzo Jul 08 '15 edited Jul 08 '15
Haskell:
EDIT: I scrapped my previous submission, as this challenge is much more suited towards
ByteStrings. With myStringsolution, certain inputs would cause the program to throw an exception because an invalid argument was given toData.Char.chr(presumably anIntthat was not a valid Unicode code point).1
u/G33kDude 1 1 Jul 08 '15
Solution in AutoHotkey.
Outputs the encrypted text in hex so I won't have to restrict the output to printable ASCII.
The PRNG is Mersenne Twister, as that's what's built into AutoHotkey
It makes use of the WinAPI for very quick binary to hex conversion. AutoHotkey can execute arbitrary machine code, so I intend to rewrite the encryption algorithm in C/C++ to speed it up tremendously.
1
u/Scroph 0 0 Jul 08 '15
My solution in Dlang using the values from the first row of the "Parameters in common use" table.
You'll notice that decrypt() and encrypt() do the same thing despite having different names. In reality, only one function is needed. I only did this because the API posted in the OP contains two separate functions.
1
u/blankFacez Jul 08 '15 edited Jul 08 '15
After failing repeatedly at debugging some encoding issues, here is my working C# effort.
1
u/Chariot Jul 09 '15 edited Jul 09 '15
C++11:
Still learning C++, would appreciate feedback
1
u/Oderzyl Jul 09 '15 edited Jul 09 '15
Here is my C solution. I used Xorshift* for the PRNG because I like this generator, it is so simple =D
C code :
Output :
Edit : corrected the PRNG.
1
u/Tom109p Jul 09 '15 edited Jul 09 '15
JavaScript
I recently started learning, so all feedback is appreciated.
1
u/Frichjaskla Jul 09 '15
C++, streams , lcg pretty vanilla but '\n' kept taunting me so it can only handle single lines
1
u/jeaton Jul 10 '15
Linear congruential generator in assembly (intel gcc):
1
u/FanaticalFighter Jul 10 '15
Here's my solution: https://gist.github.com/FanaticalFighter/0da3cfbc8668678eb84c Usage:
There's no output as there can be quite a few characters from the 0-31 range in ASCII, so printing isn't really useful. Does anyone know any way to solve this problem and make the cipher text out of characters as well?
1
u/kangaroo_king Jul 12 '15
Python 2.7
Input:
Output:
1
u/[deleted] Jul 12 '15
Solution in C.
1
u/super_pimms Jul 13 '15
C, straight forward:
1
u/Mooxmirror Jul 13 '15
Python 3:
1
u/BruceJillis Jul 13 '15
Python 3:
1
u/PapaJohnX Jul 14 '15
Python 3
Output
1
u/RustyRain Jul 14 '15
Emacs Elisp (in the *scratch* buffer):
1
u/unfeelingtable Jul 17 '15
C++. No need to re-write the wheel when a PRNG exists already.
1
u/codeman869 Jul 27 '15
Ruby: RC4 implementation, fairly late submission, but figured it was better than nothing. Also, my first gem! :)
On GitHub
1
u/milliDavids Aug 10 '15
Ruby (LCG encryption).
I seem to be getting the same value for the first letter no matter what I put in. For instance, the ciphertext for "Attack at dawn." also starts with an 'A', and the cipher text for "David" starts with a 'D'. Is that something with LCG encryption? Or is my method not running correctly. I get this output for "Attack at dawn":