how to Encrypt and Decrypt by AES algorithm in both python and ios xcode -
i have python code encryption aes. i've made compatible with android. googled couldn't fine same solution in ios xcode. big problem deal options padding, hashing key, iv size , mode_cbc. can me?
import base64 import hashlib crypto import random crypto.cipher import aes class aescipher: def __init__(self, key): self.bs = 16 self.key = hashlib.sha256(key.encode()).digest() def encrypt(self, message): message = self._pad(message) iv = random.new().read(aes.block_size) cipher = aes.new(self.key, aes.mode_cbc, iv) return base64.b64encode(iv + cipher.encrypt(message)).decode('utf-8') def decrypt(self, enc): enc = base64.b64decode(enc) iv = enc[:aes.block_size] cipher = aes.new(self.key, aes.mode_cbc, iv) return self._unpad(cipher.decrypt(enc[aes.block_size:])).decode('utf-8') def _pad(self, s): return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs) @staticmethod def _unpad(s): return s[:-ord(s[len(s)-1:])] t = aescipher('this key') enc = t.encrypt('hello world') print(enc.decode('utf-8')) t2 = aescipher('this key') print(t2.decrypt(enc))
Comments
Post a Comment