├── .gitignore ├── LICENSE ├── README.md ├── blog.md ├── images ├── confusables.png ├── stego_images.jpg └── unicode_url.png ├── setup.py └── steganos ├── __init__.py ├── src ├── __init__.py ├── branchpoints.py ├── steganos_decode.py └── steganos_encode.py └── test ├── __init__.py ├── branchpoints_test.py ├── integration_test.py ├── sample_text.txt.gz ├── steganos_decode_test.py └── steganos_encode_test.py /.gitignore: -------------------------------------------------------------------------------- 1 | .cache 2 | venv 3 | **__pycache__ 4 | *.pyc 5 | *.swp 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # steganos 2 | 3 | This is a library to encode bits into text. 4 | 5 | ## Installation 6 | 7 | You can install from source by doing, 8 | 9 | ```bash 10 | $ git clone git@github.com:fastforwardlabs/steganos.git 11 | $ cd steganos 12 | $ python setup.py install 13 | ``` 14 | 15 | or simply, 16 | 17 | ```bash 18 | $ pip install git+https://github.com/fastforwardlabs/steganos.git 19 | ``` 20 | 21 | ## Encoding 22 | 23 | To find out how many bits can be encoded into a string: 24 | 25 | ```.py 26 | import steganos 27 | 28 | original_text = '"Hello," he said.\n\t"I am 9 years old"' 29 | capacity = steganos.bit_capacity(original_text) 30 | ``` 31 | 32 | To encode bits into a string: 33 | 34 | ```.py 35 | import steganos 36 | 37 | bits = '101' 38 | original_text = '"Hello," he said.\n\t"I am 9 years old"' 39 | encoded_text = steganos.encode(bits, original_text) 40 | ``` 41 | 42 | ## Decoding 43 | 44 | Retrieving the bits from a string requires the original text into which the bits were encoded. 45 | 46 | If you have the complete encoded text, use the decode_full_text function: 47 | 48 | ```.py 49 | import steganos 50 | 51 | bits = '101' 52 | original_text = '"Hello," he said.\n\t"I am 9 years old"' 53 | encoded_text = steganos.encode(bits, original_text) 54 | recovered_bits = steganos.decode_full_text(encoded_text, original_text) 55 | # recovered_bits.startswith('101') == True 56 | ``` 57 | 58 | If you have on part of the encoded text, you can use the decode_partial_text function. If you know the indices of the _original text_ that the partial encoded text corresponds to, you can pass those in as a tuple (start_index, end_index) as the final parameter. Otherwise, they will be inferred. 59 | 60 | ```.py 61 | import steganos 62 | 63 | bits = '101' 64 | original_text = '"Hello," he said.\n\t"I am 9 years old"' 65 | encoded_text = steganos.encode(bits, original_text) 66 | partial_text = encoded_text[:8] 67 | recovered_bits = steganos.decode_partial_text(partial_text, original_text) 68 | # recovered_bits.startswith('1?1') == True 69 | ``` 70 | 71 | ## Sending messages 72 | 73 | In order to help send encoded messages as opposed to just storing bytes, we 74 | provide `bytes_to_binary` and `binary_to_bytes` in order to encode/decode a 75 | message to and from steganos' binary format. 76 | 77 | ```.py 78 | import steganos 79 | 80 | message = b'Hello World!' 81 | original_text = open('text.txt').read() 82 | 83 | bits = steganos.bytes_to_binary(message) 84 | encoded_text = steganos.encode(bits, original_text) 85 | 86 | recovered_bits = steganos.decode_full_text(encoded_text, original_text) 87 | recovered_msg = steganos.binary_to_bytes(recovered_bits) 88 | 89 | # recovered_msg.startswith(b'Hello World!') == True 90 | ``` 91 | 92 | ## A note on message length 93 | 94 | By default, and decoded message will be the maximum length encodable within the 95 | source document. That is to say, if you have a document that can store 8 bits 96 | and your message is just two bits, the decoded result will be your two bits 97 | repeated four times. This can be solved by providing the `message_bits` 98 | parameter to the decode function. In addition to returning with the proper 99 | number of bits, this also will give possible increased accuracy for partial 100 | decodings. 101 | 102 | 103 | ```py 104 | bits = '101' 105 | original_text = '"Hello," he said.\n\t"I am 9 years old"' 106 | encoded_text = steganos.encode(bits, original_text) 107 | partial_text = encoded_text[14:26] 108 | recovered_bits = steganos.decode_partial_text(partial_text, original_text) 109 | recovered_bits_limit = steganos.decode_partial_text(partial_text, original_text, message_bits=3) 110 | # recovered_bits == '1??101' 111 | # recovered_bits_limit = '101' 112 | ``` 113 | 114 | # Extending Steganos 115 | 116 | Steganos **encoding** works by generating 'branchpoints' for a given original 117 | text. Each branchpoint represents a change to the text that does not change the 118 | meaning of the text. Each branchpoint is 'executed', which means that the 119 | change it defines is made, according to the bits we are trying to encode. For 120 | example, if we want to encode '10' in a text for which we can generate two 121 | branchpoints, the first of those is executed and the second is not. Note that 122 | if there are more branchpoints available than there are bits to encode, the bits 123 | are repeated to make use of the spare capacity. For example, if we want to 124 | encode '10' in a text with 4 branchpoints, `steganos.encode` automatically 125 | encodes '1010', improving our ability to retrieve the encoded information from 126 | an incomplete encoded text. 127 | 128 | Steganos **decoding** works by figuring out which branchpoints were executed on a given text. It does this by comparing the encoded text to the original. 129 | 130 | ## The Data Model 131 | 132 | Each **branchpoint** is represented as a list of **changes**. Each **change** is a tuple of length three. The first two elements are the start and end indices of the chunk to be removed from the text, and the third element is the text with which it is to be replaced. The end index is non-inclusive. Branchpoints are represented in this way so that they can be easily interleaved. 133 | 134 | ## Adding Branchpoints 135 | 136 | Adding a new type of branchpoint should only entail changes to src/branchpoints.py and test/branchpoints_test.py. Simply add a function that accepts a string and returns a list of branchpoints represented in the manner described above. 137 | 138 | Note that there are functions called `unicode_branchpoints`, `ascii_branchpoints` and `global_branchpoints`in the branchpoints module. Functions that add branchpoints that take advantage of unicode codepoints should be called from the `unicode_branchpoints` function. Other local branchpoints should be called from the `ascii_branchpoints` function. 139 | 140 | Some changes to the text only make sense when applied universally (e.g. using oxford commas). These can be represented as a single branchopint with many changes. Functions that find global branchpoints should be called from the `global_branchpoints` function. 141 | 142 | The `get_all_branchpoints` function in that module will then integrate the new branchpoints appropriately, and no further changes will have to be made. 143 | 144 | Please note that adding new branchpoints will make it impossible to decode text that had been encoded before those branchpoints were added. As such, we should bump the version every time new branchpoints are added and keep track of which texts were encoded with which version. 145 | 146 | An arbitrary example to demonstrate a function that finds branchpoints with multiple changes each is below. This will generate branchoints that every time the letter 'a' appears will change it to 'x' and will change the letter two before to 'y'. This is of course not a legitimate branchpoint because it alters the semantics of the text. 147 | 148 | ```.py 149 | def example_branchpoints(text: str): 150 | a_indices = [index for index, char in enumerate(text) if char == 'a'] 151 | return [[(index - 2, index - 1, 'y'), (index, index + 1, 'x')] for index in a_indices] 152 | ``` 153 | 154 | ## Running Tests 155 | 156 | Get pytest with `pip install pytest`, then run `py.test test/`. There are no production dependencies. 157 | 158 | # TODO 159 | - The code contains only sample global, ascii, and unicode branchpoints. 160 | - Enable flag for 'ascii-only' branchpoints. 161 | -------------------------------------------------------------------------------- /blog.md: -------------------------------------------------------------------------------- 1 | # Fingerprinting documents with steganography 2 | 3 | Steganography is the practice of hiding messages anywhere they’re not expected. 4 | In a well-executed piece of steganography, anyone who is not the intended 5 | recipient can look at the message and not realize its there at all. In a recent 6 | headline-making 7 | [story](http://www.bbc.com/future/story/20170607-why-printers-add-secret-tracking-dots), 8 | The Intercept inadvertently outed their source by publishing a document with an 9 | embedded steganographic message that allowed the NSA to identify the person who 10 | printed it. 11 | 12 | ![](./images/stego_images.jpg) 13 | 14 | These days, information is often hidden in digital media like images and audio 15 | files, where flipping a few bits doesn’t change the file to the human eye (or 16 | ear). Before computers came along, though, there were plenty of messages 17 | creatively hidden in art, furniture, etc. There’s speculation that women in the 18 | U.S. used to hide messages in their quilt work as a way to help escaped slaves 19 | find friendly homes. Neal Stephenson riffs on this theme in his Quicksilver 20 | Trilogy by having Eliza embed a binary code in her cross-stitching to smuggle 21 | information out of the court of Louis XIV. 22 | 23 | Hiding messages in text has always been especially challenging. There’s not much 24 | room to make changes without fundamentally altering the meaning of the original 25 | document, which in turn makes it obvious that something is amiss. If someone 26 | other than the intended recipient of the information realizes that there’s a 27 | message present at all, the steganography has, in some sense, failed. 28 | 29 | ## What problem are we trying to solve? 30 | 31 | In this post, I’ll talk about fingerprinting documents using text-based 32 | steganography. The problem we’re trying to solve is as follows. We have a 33 | sensitive document that must be distributed to some number of readers. Let’s 34 | say, for example, that Grandpa has decided to share his famous cookie recipe 35 | with each of his grandchildren. But it’s super important to him that the recipe 36 | stays in the family! So they’re not allowed to share it with anyone else. If 37 | Grandpa finds pieces of his cookie recipe online later, he wants to know which 38 | grandchild broke the family trust. 39 | 40 | To address this problem, he assigns each of his grandchildren an ID, which is 41 | just a string of zeros and ones. Before he gives out the recipe, he identifies a 42 | number of ’branchpoints’ in the text. These are places where he can make a 43 | change without altering the grandchild’s experience of the recipe, or alerting 44 | them that something is amiss. One such branch point might be spelling out the 45 | numbers in the recipe - “ten ”instead of “10”. Another might be using imperial 46 | units instead of metric. This type of method is called a [canary 47 | trap](https://en.wikipedia.org/wiki/Canary_trap). 48 | 49 | For each grandchild, he goes through the branchpoints one at a time. If the 50 | grandchild’s ID has a zero at some position, he does not make a change at the 51 | corresponding branch point. If it is a one, he makes the change. 52 | 53 | Now, by looking at which changes had been made in the leaked cookie recipe, he 54 | should be able to identify which grandchild was the source of the leak. 55 | 56 | How does he find all the branchpoints he can use to effectively fingerprint 57 | the recipe? 58 | 59 | Before we can answer that question, we’ll have to take a slight detour into the 60 | world of character encoding. 61 | 62 | ## Digital Character encoding 63 | 64 | Computers think in binary, so when they save any symbol you might consider to be 65 | text, what they’re actually saving is some string of zeros and ones. The map 66 | that converts between binary and symbols is called a character encoding. 67 | 68 | For a long time, the dominant character encoding 69 | was [ASCII](http://www.asciitable.com/), which can only encode 256 characters. 70 | These include upper and lower case English letters, numbers, and some 71 | punctuation. 72 | 73 | A couple of decades ago, some folks got together and decided this wasn’t good 74 | enough, not least because people who don’t speak English should be able to use 75 | computers. They developed a specification called [unicode](http://unicode.org/) 76 | that now includes over 120,000 different characters and has the capacity to 77 | expand to over one million. 78 | 79 | Fortunately for us, there’s more room for hiding information these days than 80 | there used to be. We’ll see how we can take advantage of all those extra 81 | characters to find branchpoints in any document. 82 | 83 | ### Identifying branchpoints 84 | 85 | Some Unicode characters are more obviously useful than others. Take, for 86 | instance, the [zero width space](https://codepoints.net/U+200B). It has some 87 | semantic significance - it tells whatever is rendering the text that it’s okay 88 | to put a line break somewhere, even if there’s no other whitespace character. 89 | For example, it will sometimes be used after a slash - it’s okay to start a new 90 | line after a slash, but if you don’t, there shouldn’t be a visible space. 91 | 92 | So​ what​ happens​ if​ you​ put​ one​ 93 | of​ those​ zero​-​width​ spaces​ right​ 94 | in​ front​ of​ a​ normal,​ every​ day​ 95 | space?​ Absolutely​ nothing.​ It​ conveys​ no​ 96 | extra​ information,​ and​ doesn’t​ visibly​ 97 | change​ the​ text​ document​ at​ all.​ In​ 98 | fact,​ there’s​ a​ zero-width​ space​ in​ 99 | front​ of​ every​ space​ in​ this​ 100 | paragraph.​ Bet​ you​ couldn’t​ tell. 101 | 102 | This means we can already treat every normal single space as a branch point, 103 | where we can choose whether or not to place a zero width space in front of it. 104 | Depending on how much information you’re trying to encode, this may or may not 105 | be a good idea. 106 | 107 | There are a number of other non-displaying characters that we could use in a 108 | similar way, but let’s move on to characters we can actually see. 109 | 110 | When you have 120,000 characters, some of them are bound to look the same. 111 | Here’s an [English character](https://codepoints.net/U+0041) A, and here’s a 112 | [Greek character](https://codepoints.net/U+0391) Α. See the difference? 113 | 114 | ![](./images/confusables.png) 115 | 116 | Similar characters like these, called ’confusables’, are recognized as being 117 | dangerous enough that all modern browsers often some protection against letting 118 | you visit spoofed urls. Think you’re going to www.yahoo.com (all english 119 | characters)? Well, you may end up at ԝԝԝ.𝐲𝖺𝗵օօ.сօⅿ (no english characters) if 120 | you’re not careful. 121 | 122 | Here’s a great unicode 123 | [resource](http://unicode.org/cldr/utility/confusables.jsp?a=fast+forward+labs&r=None) 124 | for identifying confusables. 125 | 126 | ![](./images/unicode_url.png) 127 | 128 | Used judiciously, there are plenty of confusables that are, well, suitably 129 | confusing. Here are a few rules of thumb: simpler letters are more easily 130 | confused. For example, generally l-shaped things look more like each other than 131 | g-shaped things. Standalone, one letter words are harder to spot because they 132 | are separated by their neighbors by spaces, and so you don’t automatically 133 | visually juxtapose them with other characters. And, finally, how convincing your 134 | confusables are will depend to some degree on the font. Some typefaces may 135 | magnify the differences between confusables, while others will render 136 | confusables as more similar to each other. Ultimately, you don’t want to change 137 | your readers’ experience of the text in any way, so it’s good to be careful with 138 | these. 139 | 140 | But using funny characters in unicode is sometimes dangerous. In particular, if 141 | an unintended recipient of the message copies the text into an ASCII-only 142 | editor, it won’t know what to make of those crazy unicode characters and they’ll 143 | probably just show up as ????????, which is a pretty good hint to the interloper 144 | that something strange is going on. 145 | 146 | In the ASCII-only world, your options are much more limited. In general, though, 147 | any time you make a stylistic decision that could go either way, you can 148 | consider that to be a branch point. For example, do you use single quotes or 149 | double quotes? Do you spell out numbers, or do you use the numeric 150 | representations? If you want to be consistent throughout your document, each of 151 | these decisions will only get you one bit of hidden information. Because you 152 | have fewer options, you’ll have to get more creative. 153 | 154 | For example, we put five branchpoints in the following to produce a 5-bit message: 155 | 156 | - Ralphie set his secret decoder ring to “B ”and “twelve ”to decode the message. 157 | It said, “Be sure to drink your Ovaltine”. (00000) 158 | - Ralphie set his secret decoder ring to ’B’ and ’twelve’ to decode the message. 159 | It said, “Be sure to drink your Ovaltine”. (10000) 160 | - Ralphie set his secret decoder ring to “B ”and “12 ”to decode the message. It 161 | said, “Be sure to drink your Ovaltine”. (01000) 162 | - Ralphie set his secret decoder ring to “B ”and “twelve ”to decode the message. 163 | It said “Be sure to drink your Ovaltine”. (00100) 164 | - Ralphie set his secret decoder ring to “B ”and “twelve ”to decode the message. 165 | It said, ’Be sure to drink your Ovaltine’. (00010) 166 | - Ralphie set his secret decoder ring to “B ”and “twelve ”to decode the message. 167 | It said, “be sure to drink your Ovaltine”. (00001) 168 | - Ralphie set his secret decoder ring to ’B’ and ’12’ to decode the message. It 169 | said ’be sure to drink your Ovaltine’. (11111) 170 | 171 | ## Introducing: Steganos 172 | 173 | In order to play around with these concepts, we created a tool called 174 | [steganos](http://github.com/fastforwardlabs/steganos). Steganos is packaged 175 | with a small library of branchpoints (pull requests for new branchpoints are 176 | welcome!) and has the ability to: calculate the number of encodable bits, 177 | encode/decode bits into text and do a partial recovery of bits from text 178 | snippets. All this is possible by tracking the original unadulterated text as 179 | well as which branchpoints were available to steganos when the message was 180 | encoded. 181 | 182 | As an example, using the [current 183 | version](http://github.com/fastforwardlabs/steganos/tree/2378a]) of steganos, we 184 | can encode 1756 bits into this text. If we are using this for user-identification 185 | and expect to always see leaks of the full document, that means we can track 186 | 10^529 users (ie: vastly more than the number of people who have ever existed). 187 | 188 | 189 | ```.py 190 | import steganos 191 | 192 | message = '101' 193 | original_text = '”Wow! ”they said.\n\t”This tool is really #1”' 194 | 195 | capacity = steganos.bit_capacity(original_text) # == 10 196 | encoded_text = steganos.encode(message, original_text) 197 | 198 | recovered_bits = steganos.decode_full_text(encoded_text, original_text, 199 | message_bits=3) 200 | # recovered_bits == '101' 201 | 202 | partial_text = encoded_text[:8] # only use 18% of the text 203 | recovered_bits = steganos.decode_partial_text(partial_text, original_text, 204 | message_bits=3) 205 | # recovered_bits == '1?1' 206 | ``` 207 | 208 | As an example, below is the opening to Star Wars with and without a message 209 | hidden inside of it. Do you know which is the original? 210 | 211 | ``` 212 | It​ is a period of civil​ war. Rebel​ spaceships, striking​ from​ a hidden base, have​ won their first​ victory​ against the evil​ Galactic​ Empire‏‎. 213 | D⁠uring the battle, Rebel spies​ managed to​ steal​ secret plans​ to the​ E⁠mpire’s ultimate​ weapon, the D⁠EA⁠TH ST⁠A⁠R, an​ armored space station with enough​ power​ to destroy an​ entire planet‏‎. 214 | Pursued​ by the​ Empire’s sinister​ agents, P⁠rincess L⁠eia​ races​ home aboard​ her starship, custodian of the​ stolen​ plans that can save her​ people and​ restore​ freedom​ to the galaxy‏‎...‏‎. 215 | ``` 216 | 217 | ``` 218 | It is a period of civil war. Rebel spaceships, striking from a hidden base, have won their first victory against the evil Galactic Empire. 219 | During the battle, Rebel spies managed to steal secret plans to the Empire’s ultimate weapon, the DEATH STAR, an armored space station with enough power to destroy an entire planet. 220 | Pursued by the Empire’s sinister agents, Princess Leia races home aboard her starship, custodian of the stolen plans that can save her people and restore freedom to the galaxy.... 221 | ``` 222 | 223 | ## Conclusion 224 | 225 | Here we’ve seen a number of tricks we can use to fingerprint each individual 226 | copy of a document, without changing the reader’s experience or alerting them 227 | that they have a uniquely identifiable copy. There are a few practical 228 | considerations you’ll have to address if you go down this route - like how you 229 | identify the user from partial documents, or how you systematically mark pieces 230 | of text that cannot be changed without breaking the document (e.g. urls) - but 231 | these are mostly logistical issues. 232 | 233 | Fingerprinting documents in this way can be a powerful tool in finding out who 234 | breached a confidentiality agreement. On the flip side, it can also be used to 235 | track people’s behavior in ways they haven’t agreed to, which is something to be 236 | cautious of. There’s a little too much of that going on on the internet as it 237 | is. 238 | 239 | Do you have ideas for other cool branchpoints? Let us know! 240 | 241 | - [Noam](https://github.com/n-s-f) and [Micha](http://github.com/mynameisfiber/) 242 | 243 | Thanks to [Manny](https://twitter.com/MannyMoss) for his great edits! 244 | 245 | PS: If you want to make sure you _aren’t_ being tracked this way, simply make 246 | sure you only copy the ASCII transliterated version of text! In some systems, 247 | this is done by selecting the “Copy as Plain Text ”option. 248 | -------------------------------------------------------------------------------- /images/confusables.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fastforwardlabs/steganos/7733a0d8accc90c5509a7fa69281038119ec4be3/images/confusables.png -------------------------------------------------------------------------------- /images/stego_images.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fastforwardlabs/steganos/7733a0d8accc90c5509a7fa69281038119ec4be3/images/stego_images.jpg -------------------------------------------------------------------------------- /images/unicode_url.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fastforwardlabs/steganos/7733a0d8accc90c5509a7fa69281038119ec4be3/images/unicode_url.png -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from setuptools import setup 4 | from steganos import __version__ 5 | 6 | 7 | setup( 8 | name='steganos', 9 | version=__version__, 10 | description='Hide messages inside text', 11 | author='Noam Finkelstein, Micha Gorelick', 12 | url='http://github.com/fastforwardlabs/steganos', 13 | download_url='https://github.com/fastforwardlabs/steganos/tarball/master', 14 | license="GNU Lesser General Public License v3 or later (LGPLv3+)", 15 | 16 | packages=['steganos'], 17 | ) 18 | -------------------------------------------------------------------------------- /steganos/__init__.py: -------------------------------------------------------------------------------- 1 | from .src.steganos_encode import bit_capacity 2 | from .src.steganos_encode import encode 3 | from .src.steganos_decode import decode_full_text 4 | from .src.steganos_decode import decode_partial_text 5 | from .src.steganos_decode import binary_to_bytes, bytes_to_binary 6 | 7 | __version__ = '0.0.1' 8 | 9 | __all__ = ['bit_capacity', 'encode', 'decode_full_text', 'decode_partial_text'] 10 | -------------------------------------------------------------------------------- /steganos/src/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fastforwardlabs/steganos/7733a0d8accc90c5509a7fa69281038119ec4be3/steganos/src/__init__.py -------------------------------------------------------------------------------- /steganos/src/branchpoints.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def get_all_branchpoints(text): 5 | # local and unicode branchpoints are sorted to maximize the information 6 | # that can be retrieved from any contiguous piece of encoded text 7 | sorted_branchpoints = sort_branchpoints(ascii_branchpoints(text) + 8 | unicode_branchpoints(text)) 9 | branchpoints = global_branchpoints(text) + sorted_branchpoints 10 | 11 | unchangeable_areas = find_unchangeable_areas(text) 12 | changeable_branchpoints = [changeable_part(bp, unchangeable_areas) 13 | for bp in branchpoints] 14 | filtered_branchpoints = [bp for bp in changeable_branchpoints if bp] 15 | 16 | nored_branchpoints = remove_redundant_characters(text, 17 | filtered_branchpoints) 18 | return mutually_exclusive_branchpoints(nored_branchpoints) 19 | 20 | 21 | def changeable_part(branchpoint, unchangeable_areas): 22 | for start, end in unchangeable_areas: 23 | for change in branchpoint: 24 | if ((change[0] > start and change[0] < end) or 25 | (change[1] > start and change[1] < end) or 26 | (change[0] < start and change[1] > end)): 27 | branchpoint = [c for c in branchpoint if c != change] 28 | return branchpoint 29 | 30 | 31 | def find_unchangeable_areas(text): 32 | url_re = re.compile('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|' 33 | '(?:%[0-9a-fA-F][0-9a-fA-F]))+') 34 | code_re = re.compile('```.+?```', re.DOTALL) 35 | markdown_re = re.compile('[!]?\[[^\]]+?\]\([^)]+?\)', re.MULTILINE) 36 | 37 | url = [m.span() for m in url_re.finditer(text)] 38 | code_markdown = [m.span() for m in code_re.finditer(text)] 39 | markdown_links = [m.span() for m in markdown_re.finditer(text)] 40 | 41 | return code_markdown + url + markdown_links 42 | 43 | 44 | def ascii_branchpoints(text): 45 | return get_tab_branchpoints(text) + get_contraction_branchpoints(text) 46 | 47 | 48 | def unicode_branchpoints(text): 49 | return (get_directional_mark_branchpoints(text) + 50 | get_non_breaking_branchpoints(text) + 51 | get_zero_width_space_branchpoints(text)) 52 | 53 | 54 | def global_branchpoints(text): 55 | global_branchpoints = [get_single_quotes_branchpoint(text), 56 | get_single_digit_branchpoint(text)] 57 | return [bp for bp in global_branchpoints if bp] 58 | 59 | 60 | def get_tab_branchpoints(text): 61 | tab_indices = [m.start() for m in re.finditer('\t', text)] 62 | return [[(tab_index, tab_index + 1, ' ')] for tab_index in tab_indices] 63 | 64 | 65 | def get_contraction_branchpoints(text): 66 | contractions = [ 67 | ("won't", "will not"), 68 | ("can't", "cannot"), 69 | ("isn't", "is not"), 70 | ("doesn't", "does not"), 71 | ("would've", "would have"), 72 | ("how'll", "how will"), 73 | ("hadn't", "had not"), 74 | ] 75 | branchpoints = [] 76 | for contraction, long_form in contractions: 77 | for match in re.finditer(contraction, text): 78 | start, end = match.span() 79 | branchpoints.append([(start, end, long_form)]) 80 | for match in re.finditer(long_form, text): 81 | start, end = match.span() 82 | branchpoints.append([(start, end, contraction)]) 83 | return branchpoints 84 | 85 | 86 | def get_single_quotes_branchpoint(text): 87 | double_quote_indices = [m.start() for m in re.finditer('"', text)] 88 | return [(index, index + 1, "'") for index in double_quote_indices] 89 | 90 | 91 | def get_single_digit_branchpoint(text): 92 | digit_re = re.compile('(?= de[j][0]: 222 | this_area = de[i][3] 223 | next_area = de[j][3] 224 | # pick the item with the least "area" in terms of the higher 225 | # order list of intervals. This is a heuristic to remove long 226 | # lists of small intervals. We want those out because they have 227 | # a higher probability of intersecting with many other lists of 228 | # intervals. 229 | if this_area < next_area: 230 | to_remove.add(de[j][4]) 231 | else: 232 | to_remove.add(de[i][4]) 233 | i -= 1 234 | i += 1 235 | return [d for i, d in enumerate(data) if i not in to_remove] 236 | -------------------------------------------------------------------------------- /steganos/src/steganos_decode.py: -------------------------------------------------------------------------------- 1 | """ 2 | A 'change' represents instructions for making a change to the original text. 3 | It is represented as a tuple of length 3 where the first two elements 4 | are the first and last indices of the substring to be eliminated by 5 | the change, and the third element is the string that will replace it. 6 | 7 | A 'branchpoint' is a decision about the text that can be used to encode 8 | a single bit. Each branch point is represented by a list of 'changes'. 9 | """ 10 | from .branchpoints import get_all_branchpoints 11 | 12 | 13 | def decode_full_text(encoded_text, original_text, message_bits=None): 14 | """ 15 | Decodes bits from encoded text. Use this function if you have 16 | the full encoded text, otherwise use decode_partial_text function. 17 | 18 | :param encoded_text: A string that has been encoded with information. 19 | :param original_text: The text before encoding. 20 | :param message_bits: number of bits in message. If this isn't provided, the 21 | number decoded bits will be the full capacity of the 22 | text. 23 | :return: The bits decoded from the text. Unretrievable bits are 24 | returned as question marks. 25 | """ 26 | encoded_range = (0, len(original_text)) 27 | return decode_partial_text(encoded_text, original_text, encoded_range, 28 | message_bits) 29 | 30 | 31 | def decode_partial_text(encoded_text, original_text, encoded_range=None, 32 | message_bits=None): 33 | """ 34 | Decodes bits from encoded text. Use this function if you do not have 35 | the full partial text. 36 | 37 | :param encoded_text: A part of a text that has been encoded. 38 | :param original_text: The complete text before encoding. 39 | :param encoded_range (Optional): A tuple of length two. 40 | The elements represent the start and end indices 41 | of the piece of the original text that maps to 42 | the partial encoded text. If this parameter is 43 | not provided, it will be inferred. 44 | :param message_bits: number of bits in message. If this isn't provided, the 45 | number decoded bits will be the full capacity of the 46 | text. 47 | :return: The bits decoded from the text. Unretrievable bits are 48 | returned as question marks. 49 | """ 50 | branchpoints = get_all_branchpoints(original_text) 51 | message_bits = message_bits or len(branchpoints) 52 | start, end = encoded_range or get_indices(encoded_text, original_text, 53 | branchpoints) 54 | original_text = original_text[start:end] 55 | branchpoints = reindex_branchpoints(branchpoints, start) 56 | changes = get_relevant_changes(branchpoints, start, end) 57 | 58 | bits = ['?'] * message_bits 59 | for change in changes: 60 | if encoded_text[:change[0]] != original_text[:change[0]]: 61 | raise ValueError('Cannot extract bits from encoded text. ' 62 | 'It does not match the original text.') 63 | 64 | index = branchpoints.index(next(bp for bp in branchpoints 65 | if change in bp)) 66 | bindex = index % message_bits 67 | if bits[bindex] == '?': 68 | bits[bindex] = ('1' 69 | if change_was_made(encoded_text, original_text, 70 | change) 71 | else '0') 72 | if bits[bindex] == '1': 73 | encoded_text = undo_change(encoded_text, original_text, change) 74 | 75 | return ''.join(bits) 76 | 77 | 78 | def get_relevant_changes(branchpoints, start, end): 79 | index = end - start 80 | 81 | def change_is_relevant(change): 82 | return (change[0] >= 0 and change[0] < index and change[1] > 0 and 83 | change[1] <= index) 84 | changes = sum(branchpoints, []) 85 | changes = [change for change in changes if change_is_relevant(change)] 86 | changes.sort() 87 | return changes 88 | 89 | 90 | def reindex_branchpoints(branchpoints, start): 91 | return [reindex_changes(bp, start) for bp in branchpoints] 92 | 93 | 94 | def reindex_changes(changes, start): 95 | return [(change[0] - start, change[1] - start, change[2]) 96 | for change in changes] 97 | 98 | 99 | def get_indices(encoded_text, original_text, branchpoints): 100 | changes = sum(branchpoints, []) 101 | changes.sort() 102 | 103 | for start in range(len(original_text)): 104 | partial_text = original_text[start:] 105 | partial_changes = reindex_changes(changes, start) 106 | partial_changes = [change for change in partial_changes 107 | if change[0] >= 0] 108 | 109 | # in the case that there are no changes 110 | if encoded_text == partial_text[:len(encoded_text)]: 111 | return (start, start + len(encoded_text)) 112 | 113 | reverted_text = encoded_text 114 | for change in partial_changes: 115 | if reverted_text[:change[0]] != partial_text[:change[0]]: 116 | break 117 | 118 | if change_was_made(reverted_text, partial_text, change): 119 | reverted_text = undo_change(reverted_text, partial_text, 120 | change) 121 | 122 | if reverted_text == partial_text[:len(reverted_text)]: 123 | return (start, start + len(reverted_text)) 124 | 125 | raise ValueError('Cannot infer indices of encoded text. ' 126 | 'It does not match the original text.') 127 | 128 | 129 | def undo_change(encoded_text, original_text, change): 130 | start, end, change_string = change 131 | 132 | beginning = encoded_text[:start] 133 | original_string = original_text[start:end] 134 | 135 | remainder = '' 136 | 137 | # encoded text starts midway through a change 138 | if start == 0: 139 | for index in range(len(change_string)): 140 | if change_string[-1 * index:] == encoded_text[:index]: 141 | remainder = encoded_text[index:] 142 | break 143 | 144 | if not remainder: 145 | remainder = encoded_text[start + len(change_string):] 146 | 147 | return beginning + original_string + remainder 148 | 149 | 150 | def change_was_made(encoded_text, original_text, change): 151 | start, _, change_string = change 152 | end_change = start + len(change_string) 153 | 154 | # encoded text starts midway through a change 155 | if start == 0: 156 | for index in range(len(change_string)): 157 | if change_string[-1 * index:] == encoded_text[:index]: 158 | return True 159 | 160 | # change end_of_change if encoded text ends in the middle of the change 161 | if end_change > min(len(encoded_text), len(original_text)): 162 | end_change = min(len(encoded_text), len(original_text)) 163 | 164 | return encoded_text[start:end_change] == change_string[:end_change - start] 165 | 166 | 167 | def binary_to_bytes(binary): 168 | return bytes(chunk_binary_str_to_bytes(binary)) 169 | 170 | 171 | def bytes_to_binary(message): 172 | return ''.join(bin(i)[2:].rjust(8, '0') for i in message) 173 | 174 | 175 | def chunk_binary_str_to_bytes(binary): 176 | for i in range(0, len(binary), 8): 177 | try: 178 | yield int(binary[i:i+8], base=2) 179 | except ValueError: 180 | yield ord('?') 181 | -------------------------------------------------------------------------------- /steganos/src/steganos_encode.py: -------------------------------------------------------------------------------- 1 | from .branchpoints import get_all_branchpoints 2 | 3 | 4 | def bit_capacity(text): 5 | """ 6 | Returns the number of bits that can be encoded in a given string. 7 | """ 8 | return len(get_all_branchpoints(text)) 9 | 10 | 11 | def encode(bits, text): 12 | """ 13 | Encodes the provided bits into the given text. 14 | 15 | Sample usage: 16 | 17 | >> original_text = '"Some string" has 2 words.' 18 | >> encoded_text = steganos.encode('11', original_text) 19 | >> print(encoded_text) 20 | 'Some string' has two words. 21 | 22 | 23 | Encoded bits can be retrieved using one of the decode functions below. 24 | 25 | Sample usage: 26 | 27 | >> result = steganos.decode_full_text(encoded_text, original_text) 28 | >> print(result) 29 | 11 30 | 31 | :param bits: A string made up of '0' and '1' characters 32 | representing the bits to encode. 33 | :param text: The string within which to encode the bits. 34 | 35 | :return: A string based on input text into which the 36 | given bits are encoded. 37 | :raises: ValueError if given too many bits to encode into text. 38 | """ 39 | branchpoints = get_all_branchpoints(text) 40 | 41 | if len(branchpoints) < len(bits): 42 | raise ValueError( 43 | ('Attempting to encode {} bits into a text with a bit ' 44 | 'capacity of {}.').format(len(bits), len(branchpoints)) 45 | ) 46 | 47 | repeated_bits = repeat(bits, len(branchpoints)) 48 | active_branchpoints = filter_by_bits(branchpoints, repeated_bits) 49 | return execute_branchpoints(active_branchpoints, text) 50 | 51 | 52 | def repeat(xs, length): 53 | return xs * int(length / len(xs)) + xs[:length % len(xs)] 54 | 55 | 56 | def filter_by_bits(xs, bits): 57 | return [x for x, flag in zip(xs, bits) if flag == '1'] 58 | 59 | 60 | def execute_branchpoints(branchpoints, text): 61 | changes = sum(branchpoints, []) 62 | return make_changes(text, changes) 63 | 64 | 65 | def make_changes(text, changes): 66 | """ Assumes changes never overlap.""" 67 | # By executing the last changes first, we guarantee that 68 | # the indices of each change remain accurate. 69 | changes.sort(reverse=True) 70 | for change in changes: 71 | start, end, change_string = change 72 | text = text[:start] + change_string + text[end:] 73 | return text 74 | -------------------------------------------------------------------------------- /steganos/test/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fastforwardlabs/steganos/7733a0d8accc90c5509a7fa69281038119ec4be3/steganos/test/__init__.py -------------------------------------------------------------------------------- /steganos/test/branchpoints_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from ..src.steganos_encode import execute_branchpoints 3 | from ..src.steganos_decode import undo_change 4 | from ..src.branchpoints import * 5 | 6 | def test_remove_single_character_prefix_and_suffix_for_change(): 7 | # given 8 | text = "I'm here." 9 | branchpoints = [[(0, 3, 'I am')]] 10 | 11 | # when 12 | result = remove_redundant_characters(text, branchpoints) 13 | 14 | # then 15 | assert result == [[(1, 2, ' a')]] 16 | 17 | def test_remove_multiple_character_prefix_for_change(): 18 | # given 19 | text = "Therefore they are." 20 | branchpoints = [[(0, 9, 'There')]] 21 | 22 | # when 23 | result = remove_redundant_characters(text, branchpoints) 24 | 25 | # then 26 | assert result == [[(5, 9, '')]] 27 | 28 | def test_remove_single_character_suffix_for_change(): 29 | # given 30 | text = "I go where he goes." 31 | branchpoints = [[(11, 13, 'she')]] 32 | 33 | # when 34 | result = remove_redundant_characters(text, branchpoints) 35 | 36 | # then 37 | assert result == [[(11, 11, 's')]] 38 | 39 | def test_get_all_branchpoints_finds_matching_quotes(): 40 | # given 41 | text = '"Hello," he said.' 42 | 43 | # when 44 | result = get_all_branchpoints(text) 45 | 46 | # then 47 | assert [(0, 1, "'"), (7, 8, "'")] in result 48 | 49 | @pytest.mark.parametrize('text, branchpoints', [ 50 | ('\tHello.', [[(0, 1, ' ')]]), 51 | ('\tHello.\t', [[(0, 1, ' ')], [(7, 8, ' ')]]), 52 | ('No tabs!', []) 53 | ]) 54 | def test_get_tab_branchpoints(text, branchpoints): 55 | # when 56 | result = get_tab_branchpoints(text) 57 | 58 | # then 59 | assert result == branchpoints 60 | 61 | @pytest.mark.parametrize('text, branchpoints', [ 62 | ("I won't do it.", [[(2, 7, 'will not')]]) 63 | ]) 64 | def test_get_contraction_branchpoints(text, branchpoints): 65 | # when 66 | result = get_contraction_branchpoints(text) 67 | 68 | # then 69 | assert result == branchpoints 70 | 71 | @pytest.mark.parametrize('text, branchpoint', [ 72 | ('"A" and "B"', [(0, 1, "'"), (2, 3, "'"), (8, 9, "'"), (10, 11, "'")]), 73 | ('There are no quotes in this text.', []) 74 | ]) 75 | def test_get_global_single_quotes_branchpoint(text, branchpoint): 76 | # when 77 | result = get_single_quotes_branchpoint(text) 78 | 79 | # then 80 | assert result == branchpoint 81 | 82 | @pytest.mark.parametrize('text, branchpoint', [ 83 | ('He was 9', [(7, 8, 'nine')]), 84 | ('He is not 88, he is 8, he says.', [(20, 21, 'eight')]), 85 | ('7, 8, 9', [(0, 1, 'seven'), (3, 4, 'eight'), (6, 7, 'nine')]), 86 | ('There are no numbers in this text.', []) 87 | ]) 88 | def test_get_global_single_digit_branchpoint(text, branchpoint): 89 | # when 90 | result = get_single_digit_branchpoint(text) 91 | 92 | # then 93 | assert result == branchpoint 94 | 95 | @pytest.mark.parametrize('text, branchpoints', [ 96 | ('Hello. I am sam.', [[(5, 5, '\u200f\u200e')], [(15, 15, '\u200f\u200e')]]), 97 | ('Period.', [[(6, 6, '\u200f\u200e')]]), 98 | ('No periods!', []) 99 | ]) 100 | def test_directional_mark_branchpoints(text, branchpoints): 101 | # when 102 | result = get_directional_mark_branchpoints(text) 103 | 104 | # then 105 | assert result == branchpoints 106 | 107 | @pytest.mark.parametrize('text, branchpoints', [ 108 | ('Hello. I am sam.', [[(1, 1, '\u2060')], [(8, 8, '\u2060')]]), 109 | ('Capital.', [[(1, 1, '\u2060')]]), 110 | ('no caps!', []) 111 | ]) 112 | def test_non_breaking_branchpoints(text, branchpoints): 113 | # when 114 | result = get_non_breaking_branchpoints(text) 115 | 116 | # then 117 | assert result == branchpoints 118 | 119 | def test_filter_branchpoints_on_markdown(): 120 | readme = """ 121 | this is 122 | 123 | ```.py 124 | # comment 125 | def func(): 126 | 'single quote' 127 | "quote" 128 | python code 129 | ``` 130 | 131 | and but wait 132 | 133 | ```.js 134 | var some_func = function(a, b) { 135 | console.log("This string can break anything"); 136 | } 137 | ``` 138 | 139 | and the over 140 | """ 141 | 142 | assert [(26, 146), (181, 306)] == find_unchangeable_areas(readme) 143 | 144 | def test_filter_branchpoints_on_urls(): 145 | url = """ 146 | Here is a url: http://code.google.com/events?product=browser 147 | Here is another url: https://some.url 148 | """ 149 | 150 | assert [(23, 68), (97, 113)] == find_unchangeable_areas(url) 151 | 152 | @pytest.mark.parametrize('branchpoint, expected', [ 153 | ([(1, 3, 'ab')], []), 154 | ([(3, 5, 'ab')], []), 155 | ([(1, 6, 'ab')], []), 156 | ([(1, 3, 'ab'), (8, 10, 'xy')], []), 157 | ([(1, 3, 'ab'), (5, 6, 'ab')], [(5, 6, 'ab')]) 158 | ]) 159 | def test_changeable_part_of_branchpoints(branchpoint, expected): 160 | # given 161 | unchangeable_areas = [(2, 4), (7, 9)] 162 | 163 | # when 164 | result = changeable_part(branchpoint, unchangeable_areas) 165 | 166 | # then 167 | assert result == expected 168 | 169 | -------------------------------------------------------------------------------- /steganos/test/integration_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import os 3 | import gzip 4 | from ..src import steganos_decode 5 | from ..src import steganos_encode 6 | 7 | def test_when_global_change_out_of_encoded_text(): 8 | # given 9 | text = 'I am 9, but I say "I am 8".' 10 | encoded_text = steganos_encode.encode('11', text) 11 | 12 | # when 13 | result = steganos_decode.decode_partial_text(encoded_text[0:9], text) 14 | 15 | # then 16 | assert '?1' in result 17 | 18 | def test_local_changes_appear_after_global_changes_in_decoded_bits(): 19 | # given 20 | text = 'I am 9\t, but I say "I am 8".' 21 | encoded_text = steganos_encode.encode('111', text) 22 | 23 | # when 24 | result = steganos_decode.decode_partial_text(encoded_text[0:15], text) 25 | 26 | # then 27 | assert '?11' in result 28 | 29 | def test_global_change_late_in_encoded_text(): 30 | # given 31 | text = 'I am 9\t, but I say "I am 8"' 32 | encoded_text = steganos_encode.encode('111', text) 33 | 34 | # when 35 | result = steganos_decode.decode_partial_text(encoded_text[33:], text) 36 | 37 | # then 38 | assert '11?' in result 39 | 40 | def test_encode_and_decode(): 41 | # given 42 | text = '"I am 9." he said.' 43 | bits = '01' 44 | encoded_text = steganos_encode.encode(bits, text) 45 | 46 | # when 47 | result = steganos_decode.decode_full_text(encoded_text, text) 48 | 49 | # then 50 | assert bits in result 51 | 52 | def test_single_bit(): 53 | # given 54 | text = '"I am 9." he said.' 55 | bits = '1' 56 | encoded_text = steganos_encode.encode(bits, text) 57 | 58 | # when 59 | result = steganos_decode.decode_full_text(encoded_text, text) 60 | 61 | # then 62 | assert '1111' in result 63 | 64 | def test_bad_origin(): 65 | # given 66 | original_text = 'This is a bad sentence with a 9.' 67 | encoded_text = 'This does not match with a 9.' 68 | 69 | # then 70 | with pytest.raises(ValueError): 71 | steganos_decode.decode_full_text(encoded_text, original_text) 72 | 73 | def test_with_sample_fflabs_report(): 74 | # given 75 | bits = '101010101011111111' 76 | filename = (os.path.dirname(os.path.abspath(__file__)) + 77 | '/sample_text.txt.gz') 78 | with gzip.open(filename) as book: 79 | text = book.read().decode('utf8') 80 | encoded_text = steganos_encode.encode(bits, text) 81 | 82 | # when 83 | result = steganos_decode.decode_full_text(encoded_text, text, 84 | message_bits=len(bits)) 85 | 86 | # then 87 | assert bits == result 88 | 89 | -------------------------------------------------------------------------------- /steganos/test/sample_text.txt.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fastforwardlabs/steganos/7733a0d8accc90c5509a7fa69281038119ec4be3/steganos/test/sample_text.txt.gz -------------------------------------------------------------------------------- /steganos/test/steganos_decode_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from ..src import steganos_decode 3 | 4 | def test_change_was_made(): 5 | # given 6 | original_text = 'The dog can bark.' 7 | encoded_text = 'The dogs can bark.' 8 | change = (4, 7, 'dogs') 9 | 10 | # when 11 | result = steganos_decode.change_was_made(encoded_text, original_text, change) 12 | 13 | # then 14 | assert result 15 | 16 | def test_unmade_change_followed_by_made_change(): 17 | # given 18 | original_text = 'abcdef' 19 | encoded_text = 'abcdXXX' 20 | change = (3, 5, 'YYYY') 21 | 22 | # when 23 | result = steganos_decode.change_was_made(encoded_text, original_text, change) 24 | 25 | # then 26 | assert not result 27 | 28 | def test_change_detected_encoded_when_text_ends_mid_change(): 29 | # given 30 | original_text = 'abcdef' 31 | encoded_text = 'ABCD' 32 | change = (0, 5, 'ABCDE') 33 | 34 | # when 35 | result = steganos_decode.change_was_made(encoded_text, original_text, change) 36 | 37 | # then 38 | assert result 39 | 40 | def test_change_detected_when_encoded_text_starts_mid_change(): 41 | # given 42 | original_text = 'abcdef' 43 | encoded_text = 'CDEf' 44 | change = (0, 5, 'ABCDE') 45 | 46 | # when 47 | result = steganos_decode.change_was_made(encoded_text, original_text, change) 48 | 49 | # then 50 | assert result 51 | 52 | def test_change_detected_when_zero_width_change_at_start(): 53 | # given 54 | original_text = 'bcdef' 55 | encoded_text = 'Zbcdef' 56 | change = (0, 0, 'Z') 57 | 58 | # when 59 | result = steganos_decode.change_was_made(encoded_text, original_text, change) 60 | 61 | # then 62 | assert result 63 | 64 | def test_change_was_not_made(): 65 | # given 66 | text = 'The same string.' 67 | change = (4, 8, 'different') 68 | 69 | # when 70 | result = steganos_decode.change_was_made(text, text, change) 71 | 72 | # then 73 | assert not result 74 | 75 | def test_undo_change(): 76 | # given 77 | original_text = 'I am 9 years old.' 78 | encoded_text = 'I am nine years old.' 79 | change = (5, 6, 'nine') 80 | 81 | # when 82 | result = steganos_decode.undo_change(encoded_text, original_text, change) 83 | 84 | # then 85 | assert result == original_text 86 | 87 | def test_undo_change_midway(): 88 | # given 89 | encoded_text = 'not do it.' 90 | original_text = "on't do it." 91 | change = (0, 3, 'ill no') 92 | 93 | # when 94 | result = steganos_decode.undo_change(encoded_text, original_text, change) 95 | 96 | # then 97 | assert result == "on't do it." 98 | 99 | def test_get_indices_when_text_is_at_start(): 100 | # given 101 | text = 'abcdef' 102 | encoded_text = 'azc' 103 | branchpoints = [[(1, 2, 'z')]] 104 | 105 | # when 106 | result = steganos_decode.get_indices(encoded_text, text, branchpoints) 107 | 108 | # then 109 | assert result == (0, 3) 110 | 111 | def test_get_indices_when_encoded_text_not_at_start(): 112 | # given 113 | text = 'abcdef' 114 | encoded_text = 'dzf' 115 | branchpoints = [[(4, 5, 'z')]] 116 | 117 | # when 118 | result = steganos_decode.get_indices(encoded_text, text, branchpoints) 119 | 120 | # then 121 | assert result == (3, 6) 122 | 123 | def test_get_indices_when_end_is_mid_changeed(): 124 | # given 125 | text = 'abcdef' 126 | encoded_text = 'abcXY' 127 | branchpoints = [[(3, 5, 'XYZ')]] 128 | 129 | # when 130 | result = steganos_decode.get_indices(encoded_text, text, branchpoints) 131 | 132 | # then 133 | assert result == (0, 5) 134 | 135 | def test_get_indices_when_start_is_mid_change(): 136 | # given 137 | text = 'abcdef' 138 | encoded_text = 'YZdef' 139 | branchpoints = [[(1, 3, 'XYZ')]] 140 | 141 | # when 142 | result = steganos_decode.get_indices(encoded_text, text, branchpoints) 143 | 144 | # then 145 | assert result == (1, 6) 146 | 147 | def test_get_indices_when_branchpoints_not_executed(): 148 | # given 149 | text = 'abcdef' 150 | encoded_text = 'bcde' 151 | branchpoints = [[(2, 3, 'XYZ')]] 152 | 153 | # when 154 | result = steganos_decode.get_indices(encoded_text, text, branchpoints) 155 | 156 | # then 157 | assert result == (1, 5) 158 | 159 | def test_get_indices_when_no_relevant_changes(): 160 | # given 161 | text = 'abcdef' 162 | encoded_text = 'bcde' 163 | branchpoints = [] 164 | 165 | # when 166 | result = steganos_decode.get_indices(encoded_text, text, branchpoints) 167 | 168 | # then 169 | assert result == (1, 5) 170 | 171 | def test_get_indices_multiple_changes(): 172 | # given 173 | text = 'abcdef' 174 | encoded_text = 'bcXeY' 175 | branchpoints = [[(3, 4, 'X'), (5, 6, 'Y')]] 176 | 177 | # when 178 | result = steganos_decode.get_indices(encoded_text, text, branchpoints) 179 | 180 | # then 181 | assert result == (1, 6) 182 | 183 | def test_get_indices_multiple_changes_with_one_unmade(): 184 | # given 185 | text = 'abcdef' 186 | encoded_text = 'bcXef' 187 | branchpoints = [[(3, 4, 'X'), (5, 6, 'Y')]] 188 | 189 | # when 190 | result = steganos_decode.get_indices(encoded_text, text, branchpoints) 191 | 192 | # then 193 | assert result == (1, 6) 194 | 195 | -------------------------------------------------------------------------------- /steganos/test/steganos_encode_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from ..src import steganos_encode 3 | 4 | @pytest.mark.parametrize('length, expected', [ 5 | (3, 'abc'), 6 | (5, 'abcab'), 7 | (2, 'ab') 8 | ]) 9 | def test_repeated_string(length, expected): 10 | assert expected == steganos_encode.repeat('abc', length) 11 | 12 | @pytest.mark.parametrize('length, expected', [ 13 | (3, ['a', 'b', 'c']), 14 | (5, ['a', 'b', 'c', 'a', 'b']), 15 | (2, ['a', 'b']) 16 | ]) 17 | def test_repeated_list(length, expected): 18 | assert expected == steganos_encode.repeat(['a', 'b', 'c'], length) 19 | 20 | def test_filter_by_bits(): 21 | # given 22 | bits = '101' 23 | xs = ['a', 'b', 'c'] 24 | 25 | # when 26 | result = steganos_encode.filter_by_bits(xs, bits) 27 | 28 | # then 29 | assert result == ['a', 'c'] 30 | 31 | def test_make_change_for_single_change(): 32 | # given 33 | text = 'This is his dog.' 34 | changes = [(9, 11, 'er')] 35 | 36 | # when 37 | result = steganos_encode.make_changes(text, changes) 38 | 39 | # then 40 | assert result == 'This is her dog.' 41 | 42 | def test_make_changes_for_two_changes(): 43 | # given 44 | text = 'This is his dog.' 45 | changes = [(9, 11, 'er'), (12, 15, 'cat')] 46 | 47 | # when 48 | result = steganos_encode.make_changes(text, changes) 49 | 50 | # then 51 | assert result == 'This is her cat.' 52 | 53 | def test_make_changes_when_change_is_different_length(): 54 | # given 55 | text = 'This is just a sample string.' 56 | changes = [(22, 28, 'text'), (0, 4, 'It')] 57 | 58 | # when 59 | result = steganos_encode.make_changes(text, changes) 60 | 61 | # then 62 | assert result == 'It is just a sample text.' 63 | 64 | def test_execute_branchpoints_when_one_is_sandwiched(): 65 | # given 66 | text = '"How is she?" he asked.' 67 | branchpoints = [ 68 | [(0, 1, "'"), (12, 13, "'")], 69 | [(8, 9, '')] 70 | ] 71 | 72 | # when 73 | result = steganos_encode.execute_branchpoints(branchpoints, text) 74 | 75 | # then 76 | assert result == "'How is he?' he asked." 77 | 78 | --------------------------------------------------------------------------------