MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / encrypt

Method encrypt

ciphers/xor_cipher.py:33–66  ·  view source on GitHub ↗

input: 'content' of type string and 'key' of type int output: encrypted string 'content' as a list of chars if key not passed the method uses the key by the constructor. otherwise key = 1 Empty list >>> XORCipher().encrypt("", 5) []

(self, content: str, key: int)

Source from the content-addressed store, hash-verified

31 self.__key = key
32
33 def encrypt(self, content: str, key: int) -> list[str]:
34 """
35 input: 'content' of type string and 'key' of type int
36 output: encrypted string 'content' as a list of chars
37 if key not passed the method uses the key by the constructor.
38 otherwise key = 1
39
40 Empty list
41 >>> XORCipher().encrypt("", 5)
42 []
43
44 One key
45 >>> XORCipher().encrypt("hallo welt", 1)
46 ['i', '`', 'm', 'm', 'n', '!', 'v', 'd', 'm', 'u']
47
48 Normal key
49 >>> XORCipher().encrypt("HALLO WELT", 32)
50 ['h', 'a', 'l', 'l', 'o', '\\x00', 'w', 'e', 'l', 't']
51
52 Key greater than 255
53 >>> XORCipher().encrypt("hallo welt", 256)
54 ['h', 'a', 'l', 'l', 'o', ' ', 'w', 'e', 'l', 't']
55 """
56
57 # precondition
58 assert isinstance(key, int)
59 assert isinstance(content, str)
60
61 key = key or self.__key or 1
62
63 # make sure key is an appropriate size
64 key %= 256
65
66 return [chr(ord(ch) ^ key) for ch in content]
67
68 def decrypt(self, content: str, key: int) -> list[str]:
69 """

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected