mardi 26 octobre 2021

Is it bad practice or plainfully wrong to declare a class which has methods that returns some value from another class in Python?

I wanted to separate the logic for my code and I don't have any experience with design patterns, but this question is nogging my head. I have a class Person that should have a pair of keys for encrypting and decrypting messages. The class calls methods from another class RSA, which contains all the logic for handling this.

Here is a snippet of the code for Person:

from RSA import RSA 

class Person:
    def __init__(self, name):
        self.name = name
        self._keys = None

    def generate_keys(self):
        self._keys = RSA.generate_keys()

    def sign(self, message):
        return RSA.sign(message, self._keys)

    def verify(self, recipent_pk, signature, message):
        return RSA.verify(recipent_pk, signature, message)

And a snippet for RSA:

class RSA:

    def generate_keys():
        private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend()
        )
        return private_key

    def sign(message: int, private_key: rsa.RSAPrivateKey):
        bytes_msg = message_to_bytes(message)
        signature = private_key.sign(
            bytes_msg,
            padding.PSS(
                mgf=padding.MGF1(hashes.SHA256()),
                salt_length=padding.PSS.MAX_LENGTH
            ),
            hashes.SHA256()
        )
        return signature

I'm asking because Pylint is yelling at me for not declaring self as the first parameter for each method in RSA. However, the code works fine without declaring it, but am I missing something here? Furthermore, message_to_bytes is a helper function used to convert the input from an integer to byte representation. Is it okay that it goes outside the class at the module level, or do I need to declare it inside the RSA class? (Currently it works, but it feels wrong coming from Java).

Aucun commentaire:

Enregistrer un commentaire