This article incorporates nonces and encryption to force private members to be implemented in python, but it just doesn't make sense because it's less readable and can be easily broken.
All you have to do is design an encryption nonce.
Regarding the encryption mechanism, teitei_tk's article was plagiarized.
In particular, ʻaes_cipher.pywas saved in the directory as it is. However,
pip install pycryptoseems to cause a build error in the windows environment, so An alternative to
pip install pycryptodome`.
Private method
import numpy as np
from aes_cipher import AESCipher
import string, random;
#All imports are for private methods
class Test:
def __init__(self):
self.cipher = AESCipher(''.join([random.choice(string.ascii_letters + string.digits) for i in range(50)])) #Key creation, immediate registration
self.nonce # nonce
def caller(self):
print('From caller_private_Call callee')
self.nonce = np.random.rand() #nonce update
self._private_callee(self.cipher.encrypt(self.nonce)) #Encrypt new nonce and send it to private method
def _private_callee(self, ciphered_nonce):
nonce = cipher.decrypt(ciphered_nonce) #Decrypt the encrypted nonce sent
if nonce==self.nonce:
print('Since the nonces matched, the call from the caller was as expected.')
#Write processing here
else:
print('Illegal call')
Of course, if you do ʻobj._private_callee (obj.cipher.encrypt (obj.nonce))` from the outside, an illegal call will succeed, so it is ** a good place out of the question in terms of security **. But well, it's unlikely that you'll inadvertently call a private method if you do this much. In the first place, even java's private method can be called from the outside by using reflection. Isn't this enough just to prevent strangers from calling private methods?
You can also use the same approach to create private fields and define getters and setters.
Private field
import numpy as np
from aes_cipher import AESCipher
import string, random;
#All imports are for private fields
class Test:
def __init__(self):
self.cipher = AESCipher(''.join([random.choice(string.ascii_letters + string.digits) for i in range(50)])) #Key creation, immediate registration
self._private_field = self.cipher.encrypt('"You can be seen at worst" but "I don't want to be seen inadvertently"')
def setter(self, value):
self._private_field = self.cipher.encrypt(value)
def getter(self):
return self.cipher.decrypt(self._private_field)
After all, it seems better not to encrypt or introduce nonce, but to just negotiate "Those with _
at the beginning are private! ".
It doesn't make much sense to forcibly implement something like that, but the readability of the code is messed up.
Recommended Posts