input: 'content' of type string and 'key' of type int output: encrypted string 'content' if key not passed the method uses the key by the constructor. otherwise key = 1 Empty list >>> XORCipher().encrypt_string("", 5) '' One key
(self, content: str, key: int = 0)
| 101 | return [chr(ord(ch) ^ key) for ch in content] |
| 102 | |
| 103 | def encrypt_string(self, content: str, key: int = 0) -> str: |
| 104 | """ |
| 105 | input: 'content' of type string and 'key' of type int |
| 106 | output: encrypted string 'content' |
| 107 | if key not passed the method uses the key by the constructor. |
| 108 | otherwise key = 1 |
| 109 | |
| 110 | Empty list |
| 111 | >>> XORCipher().encrypt_string("", 5) |
| 112 | '' |
| 113 | |
| 114 | One key |
| 115 | >>> XORCipher().encrypt_string("hallo welt", 1) |
| 116 | 'i`mmn!vdmu' |
| 117 | |
| 118 | Normal key |
| 119 | >>> XORCipher().encrypt_string("HALLO WELT", 32) |
| 120 | 'hallo\\x00welt' |
| 121 | |
| 122 | Key greater than 255 |
| 123 | >>> XORCipher().encrypt_string("hallo welt", 256) |
| 124 | 'hallo welt' |
| 125 | """ |
| 126 | |
| 127 | # precondition |
| 128 | assert isinstance(key, int) |
| 129 | assert isinstance(content, str) |
| 130 | |
| 131 | key = key or self.__key or 1 |
| 132 | |
| 133 | # make sure key is an appropriate size |
| 134 | key %= 256 |
| 135 | |
| 136 | # This will be returned |
| 137 | ans = "" |
| 138 | |
| 139 | for ch in content: |
| 140 | ans += chr(ord(ch) ^ key) |
| 141 | |
| 142 | return ans |
| 143 | |
| 144 | def decrypt_string(self, content: str, key: int = 0) -> str: |
| 145 | """ |