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

Method encrypt_string

ciphers/xor_cipher.py:103–142  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

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 """

Callers 1

encrypt_fileMethod · 0.95

Calls

no outgoing calls

Tested by

no test coverage detected