-
-
Notifications
You must be signed in to change notification settings - Fork 30
Cryptography
TheoremJS includes very basic but powerful cryptographic functions. Most of these functions were originally created and developed at CrypTools, an organization that I created with some friends.
t.sha256("TheoremJS") // => "506a3473100061c0f1237f17949e1b65b47eb8ed2ce22d1685dc3354acb700a9"
t.md5("TheoremJS") // => "80139a691767b8ba6c43873c40fc9fe1"
t.str2bin("TheoremJS") // => "01010100 01101000 01100101 01101111 01110010 01100101 01101101 01001010 01010011 "
t.bin2str("01010100 01101000 01100101 01101111 01110010 01100101 01101101 01001010 01010011 ") // => "TheoremJS"
If there were ever a data compression method to take the world by storm, it would be Huffman encoding.
Here is how it works: We have a string that we want to encode into bits. Huffman encoding ensures that our encoded bitstring is as small as possible without losing any information. Because it is both lossless and guarantees the smallest possible bit length, it outright replaces both Shannon and Shannon-Fano encoding in most cases, which is a little weird because the method was devised while Huffman was taking a course from Fano, himself!
By creating a binary tree of the input alphabet, every branch can be provided a unique bit representation simply by assigning a binary value to each child and reading to a character in a leaf node if starting from the root node.
Here's an image of what this might look like for the phrase bibbity_bobbity
:
This will create a codebook that looks like this:
Character | Bit Representation |
---|---|
b | 0 |
i | 100 |
t | 101 |
y | 110 |
o | 1110 |
___ | 1111 |
and bibbity_bobbity
becomes 01000010010111011110111000100101110
.
As mentioned this uses the minimum number of bits possible for encoding.
The fact that this algorithm is both conceptually simple and provably useful is rather extraordinary to me and is why Huffman encoding will always hold a special place in my heart.
Here is an example of how to use it with TheoremJS:
const encoded = t.huffmanEncode("bibbity bobbity");
const decoded = t.huffmanDecode(encoded.string, encoded.tree);
console.log(encoded.string);
console.log(decoded);
Any questions? Don't hesitate to create an issue and tell me about your problem 😊.
Copyright © 2017-2018 Arthur Guiot