From 1611444153280236ad7a77cc3a5896eb938804d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=5BQuy=20Anh=5D=20=C2=ABElliot=C2=BB=20Nguyen?= Date: Wed, 24 Jun 2026 16:33:34 +0200 Subject: [PATCH] --- --- .gitignore | 3 + .pylintrc | 644 +++++++++++++++++++++++++++++++++++ Implementation.md | 36 ++ README.md | 12 + Specification.md | 23 ++ Testing.md | 44 +++ User Guide.md | 17 + Week 1 Report.md | 14 + Week 2 Report.md | 29 ++ Week 3 Report.md | 24 ++ Week 4 Report.md | 17 + Week 5 Report.md | 19 ++ Week 6 Report.md | 12 + coverage.sh | 10 + decrypt.py | 35 ++ encrypt.py | 29 ++ functions.py | 50 +++ generate.py | 51 +++ main.py | 60 ++++ pylint.sh | 8 + requirements.txt | 4 + test/__init__.py | 0 test/test_eea.py | 138 ++++++++ test/test_encrypt_decrypt.py | 31 ++ test/test_generator.py | 20 ++ test/test_primality_test.py | 70 ++++ 26 files changed, 1400 insertions(+) create mode 100644 .gitignore create mode 100644 .pylintrc create mode 100644 Implementation.md create mode 100644 README.md create mode 100644 Specification.md create mode 100644 Testing.md create mode 100644 User Guide.md create mode 100644 Week 1 Report.md create mode 100644 Week 2 Report.md create mode 100644 Week 3 Report.md create mode 100644 Week 4 Report.md create mode 100644 Week 5 Report.md create mode 100644 Week 6 Report.md create mode 100755 coverage.sh create mode 100755 decrypt.py create mode 100755 encrypt.py create mode 100644 functions.py create mode 100755 generate.py create mode 100755 main.py create mode 100755 pylint.sh create mode 100644 requirements.txt create mode 100644 test/__init__.py create mode 100644 test/test_eea.py create mode 100644 test/test_encrypt_decrypt.py create mode 100644 test/test_generator.py create mode 100644 test/test_primality_test.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c98c6f2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +__pycache__ +./test/__pycache__/ +.coverage \ No newline at end of file diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..4876362 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,644 @@ +[MAIN] + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Clear in-memory caches upon conclusion of linting. Useful if running pylint +# in a server-like mode. +clear-cache-post-run=no + +# Load and enable all available extensions. Use --list-extensions to see a list +# all available extensions. +#enable-all-extensions= + +# In error mode, messages with a category besides ERROR or FATAL are +# suppressed, and no reports are done by default. Error mode is compatible with +# disabling specific errors. +#errors-only= + +# Always return a 0 (non-error) status code, even if lint errors are found. +# This is primarily useful in continuous integration scripts. +#exit-zero= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. +extension-pkg-allow-list= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. (This is an alternative name to extension-pkg-allow-list +# for backward compatibility.) +extension-pkg-whitelist= + +# Return non-zero exit code if any of these messages/categories are detected, +# even if score is above --fail-under value. Syntax same as enable. Messages +# specified are enabled, while categories only check already-enabled messages. +fail-on= + +# Specify a score threshold under which the program will exit with error. +fail-under=10 + +# Interpret the stdin as a python script, whose filename needs to be passed as +# the module_or_package argument. +#from-stdin= + +# Files or directories to be skipped. They should be base names, not paths. +ignore=CVS + +# Add files or directories matching the regular expressions patterns to the +# ignore-list. The regex matches against paths and can be in Posix or Windows +# format. Because '\\' represents the directory delimiter on Windows systems, +# it can't be used as an escape character. +ignore-paths= + +# Files or directories matching the regular expression patterns are skipped. +# The regex matches against base names, not paths. The default value ignores +# Emacs file locks +ignore-patterns=^\.# + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis). It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use, and will cap the count on Windows to +# avoid hangs. +jobs=1 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# List of plugins (as comma separated values of python module names) to load, +# usually to register additional checkers. +load-plugins= + +# Pickle collected data for later comparisons. +persistent=yes + +# Minimum Python version to use for version dependent checks. Will default to +# the version used to run pylint. +py-version=3.12 + +# Discover python modules and packages in the file system subtree. +recursive=no + +# Add paths to the list of the source roots. Supports globbing patterns. The +# source root is an absolute path or a path relative to the current working +# directory used to determine a package namespace for modules located under the +# source root. +source-roots= + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + +# In verbose mode, extra non-checker-related info will be displayed. +#verbose= + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. If left empty, argument names will be checked with the set +# naming style. +#argument-rgx= + +# Naming style matching correct attribute names. +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. If left empty, attribute names will be checked with the set naming +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Bad variable names regexes, separated by a comma. If names match any regex, +# they will always be refused +bad-names-rgxs= + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. If left empty, class attribute names will be checked +# with the set naming style. +#class-attribute-rgx= + +# Naming style matching correct class constant names. +class-const-naming-style=UPPER_CASE + +# Regular expression matching correct class constant names. Overrides class- +# const-naming-style. If left empty, class constant names will be checked with +# the set naming style. +#class-const-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. If left empty, class names will be checked with the set naming style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. If left empty, constant names will be checked with the set naming +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. If left empty, function names will be checked with the set +# naming style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + ex, + Run, + _ + +# Good variable names regexes, separated by a comma. If names match any regex, +# they will always be accepted +good-names-rgxs= + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=no + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. If left empty, inline iteration names will be checked +# with the set naming style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. If left empty, method names will be checked with the set naming style. +#method-rgx= + +# Naming style matching correct module names. +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style. If left empty, module names will be checked with the set naming style. +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Regular expression matching correct type alias names. If left empty, type +# alias names will be checked with the set naming style. +#typealias-rgx= + +# Regular expression matching correct type variable names. If left empty, type +# variable names will be checked with the set naming style. +#typevar-rgx= + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. If left empty, variable names will be checked with the set +# naming style. +#variable-rgx= + + +[CLASSES] + +# Warn about protected attribute access inside special methods +check-protected-access-in-special-methods=no + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp, + asyncSetUp, + __post_init__ + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict,_fields,_replace,_source,_make,os._exit + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=mcs + + +[DESIGN] + +# List of regular expressions of class ancestor names to ignore when counting +# public methods (see R0903) +exclude-too-few-public-methods= + +# List of qualified class names to ignore when counting class parents (see +# R0901) +ignored-parents= + +# Maximum number of arguments for function / method. +max-args=5 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement (see R0916). +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when caught. +overgeneral-exceptions=builtins.BaseException,builtins.Exception + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=200 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[IMPORTS] + +# List of modules that can be imported at any level, not just the top level +# one. +allow-any-import-level= + +# Allow explicit reexports by alias from a package __init__. +allow-reexport-from-package=no + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules= + +# Output a graph (.gv or any supported image format) of external dependencies +# to the given file (report RP0402 must not be disabled). +ext-import-graph= + +# Output a graph (.gv or any supported image format) of all (i.e. internal and +# external) dependencies to the given file (report RP0402 must not be +# disabled). +import-graph= + +# Output a graph (.gv or any supported image format) of internal dependencies +# to the given file (report RP0402 must not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + +# Couples of modules and preferred modules, separated by a comma. +preferred-modules= + + +[LOGGING] + +# The type of string formatting that logging methods do. `old` means using % +# formatting, `new` is for `{}` formatting. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, +# UNDEFINED. +confidence=HIGH, + CONTROL_FLOW, + INFERENCE, + INFERENCE_FAILURE, + UNDEFINED + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once). You can also use "--disable=all" to +# disable everything first and then re-enable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use "--disable=all --enable=classes +# --disable=W". +disable=raw-checker-failed, + bad-inline-option, + locally-disabled, + file-ignored, + suppressed-message, + useless-suppression, + deprecated-pragma, + use-symbolic-message-instead, + use-implicit-booleaness-not-comparison-to-string, + use-implicit-booleaness-not-comparison-to-zero + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable= + + +[METHOD_ARGS] + +# List of qualified names (i.e., library.method) which require a timeout +# parameter e.g. 'requests.api.get,requests.api.post' +timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + +# Regular expression of note tags to take in consideration. +notes-rgx= + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit,argparse.parse_error + +# Let 'consider-using-join' be raised when the separator to join on would be +# non-empty (resulting in expected fixes of the type: ``"- " + " - +# ".join(items)``) +suggest-join-with-non-empty-separator=yes + + +[REPORTS] + +# Python expression which should return a score less than or equal to 10. You +# have access to the variables 'fatal', 'error', 'warning', 'refactor', +# 'convention', and 'info' which contain the number of messages in each +# category, as well as 'statement' which is the total number of statements +# analyzed. This score is used by the global evaluation report (RP0004). +evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details. +msg-template= + +# Set the output format. Available formats are: text, parseable, colorized, +# json2 (improved json format), json (old json format) and msvs (visual +# studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +#output-format= + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + + +[SIMILARITIES] + +# Comments are removed from the similarity computation +ignore-comments=yes + +# Docstrings are removed from the similarity computation +ignore-docstrings=yes + +# Imports are removed from the similarity computation +ignore-imports=yes + +# Signatures are removed from the similarity computation +ignore-signatures=yes + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. Available dictionaries: en_AG (hunspell), en_AU +# (hunspell), en_BS (hunspell), en_BW (hunspell), en_BZ (hunspell), en_CA +# (hunspell), en_DK (hunspell), en_GB (hunspell), en_GH (hunspell), en_HK +# (hunspell), en_IE (hunspell), en_IN (hunspell), en_JM (hunspell), en_MW +# (hunspell), en_NA (hunspell), en_NG (hunspell), en_NZ (hunspell), en_PH +# (hunspell), en_SG (hunspell), en_TT (hunspell), en_US (hunspell), en_ZA +# (hunspell), en_ZM (hunspell), en_ZW (hunspell). +spelling-dict= + +# List of comma separated words that should be considered directives if they +# appear at the beginning of a comment and should not be checked. +spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains the private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to the private dictionary (see the +# --spelling-private-dict-file option) instead of raising a message. +spelling-store-unknown-words=no + + +[STRING] + +# This flag controls whether inconsistent-quotes generates a warning when the +# character used as a quote delimiter is used inconsistently within a module. +check-quote-consistency=no + +# This flag controls whether the implicit-str-concat should generate a warning +# on implicit string concatenation in sequences defined over several lines. +check-str-concat-over-line-jumps=no + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of symbolic message names to ignore for Mixin members. +ignored-checks-for-mixins=no-member, + not-async-context-manager, + not-context-manager, + attribute-defined-outside-init + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + +# Regex pattern to define which classes are considered mixins. +mixin-class-rgx=.*[Mm]ixin + +# List of decorators that change the signature of a decorated function. +signature-mutators= + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of names allowed to shadow builtins +allowed-redefined-builtins= + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of dummy variables (i.e. expected to +# not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io diff --git a/Implementation.md b/Implementation.md new file mode 100644 index 0000000..879bea3 --- /dev/null +++ b/Implementation.md @@ -0,0 +1,36 @@ +### The general structure of the program. +\- [generate.py](./generate.py) contains the `generate() -> str` function that generates a pair of public and private keys. +\- [encrypt.py](./encrypt.py) contains the `encrypt(text: str, n: int, e: int) -> str` function which encrypts a given string using the provided public key and returns the encrypted string. +\- [decrypt.py](./decrypt.py) contains the `decrypt(text: str, d: int, n: int) -> str` function which decrypts a given string using the provided private key. +\- [functions.py](./functions.py) contains the implementations of the Miller-Rabin primality test (`primality_test(n: int, k: int = 100)`) and the Extended Euclidean Algorithm (`extended_gcd(a: int, b: int) -> tuple[int, int, int]`). +\- [main.py](./main.py) is the default CLI of the project. + +### The time and space complexities achieved (e.g., Big O analyses from pseudocode). +\- `primality_test(n: int, k: int = 100)`, where $k$ is the number of testing rounds and $n$ is the number to be tested: +\+ Time complexity: $O(k \: log^3 n)$, +\+ Space complexity: $O(log \: n)$ +\- `extended_gcd(a: int, b: int) -> tuple[int, int, int]`: +\+ Time complexity: $O(log(min(a, \: b)))$ +\+ Space complexity: $O(log(max(a, \: b)))$ +\- `generate() -> str`: +\+ Time complexity: $O(k \: log^3 n)$, +\+ Space complexity: $O(log \: n)$ +\- `encrypt(text: str, n: int, e: int) -> str`: +\+ Time complexity: $O(log(e)*log^2 n )$ +\+ Space complexity: $O(log(max(n, \: e, \: t)))$, where $t$ is the size of the integer representing the original text +\- `decrypt(text: str, d: int, n: int) -> str`: +\+ Time complexity: $O(log(d)*log^2 n )$ +\+ Space complexity: $O(log \: n)$ + +### Potential shortcomings and suggested improvements of the work. +\- `encrypt` and `decrypt` are sample proof-of-concept functions that only work for strings with quite limited sizes. Longer strings like a full essay or research paper might not be encrypted or decrypted as intended. This can be resolved by increasing the size of the generated keys, at the cost of the key generation taking more time. +\- `encrypt` and `decrypt` currently only work for strings. They can be improved to work for entire files. +\- Most of the code in this project is based on the most basic implementations of the algorithms involved. More optimisation to reduce time and space complexities can be carried out. + +### Use of extensive language models (ChatGPT, etc.) State which model was used and how. Also, state if you have not used one. This is important! +No LLM was used during the development of this project. + +### References +**[1]** Wikipedia Contributors. 2024. RSA (cryptosystem). Wikipedia. [Online]. Available: [https://en.wikipedia.org/wiki/RSA_(cryptosystem)/](https://en.wikipedia.org/wiki/RSA_(cryptosystem)/). [Accessed: April 13, 2024]. +**[2]** Wikipedia Contributors. 2024. Miller–Rabin primality test. Wikipedia. [Online]. Available: [https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test/](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test/). [Accessed: April 13, 2024]. +**[3]** Wikipedia Contributors. 2024. Extended Euclidean algorithm. Wikipedia. [Online]. Available: [https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm/](https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm/). [Accessed: April 13, 2024]. diff --git a/README.md b/README.md new file mode 100644 index 0000000..892720b --- /dev/null +++ b/README.md @@ -0,0 +1,12 @@ +### Documents: +#### [Specification](./Specification.md) +#### [Implementation](./Implementation.md) +#### [Testing](./Testing.md) +#### [User Guide](./User%20Guide.md) +#### Weekly Reports: +##### [Week 1](./Week%201%20Report.md) +##### [Week 2](./Week%202%20Report.md) +##### [Week 3](./Week%203%20Report.md) +##### [Week 4](./Week%204%20Report.md) +##### [Week 5](./Week%205%20Report.md) +##### [Week 6](./Week%206%20Report.md) diff --git a/Specification.md b/Specification.md new file mode 100644 index 0000000..1126542 --- /dev/null +++ b/Specification.md @@ -0,0 +1,23 @@ +### Degree programme: +Bachelor's Programme in Science + +### What programming language are you using? +Python + +### Also, mention any other languages you are proficient in to the extent that you can peer review projects made in them if necessary: +JavaScript, TypeScript + +### What algorithms and data structures are you implementing in your work? +The Miller-Rabin test is implemented to check the primality of numbers. In addition, the Extended Euclidean Algorithm is implemented to compute the greatest common divisor of two integers as well as coefficients of Bézout's identity. No significantly advanced data structures are needed, so far. + +### What problem are you solving? +An implementation of RSA encryption capable of producing keys of at least 1024 bits, according to the specification at [https://en.wikipedia.org/wiki/RSA_(cryptosystem)](https://en.wikipedia.org/wiki/RSA_(cryptosystem)) + +### What inputs does your program take, and how are these used? +A basic implementation of RSA key generation has been developed so far, and this requires no input. Executing main.py with no arguments simply prints out the randomly generated keys, including: +\- The public key: This includes the modulus `n` and the public exponent `e`. +\- The private key: This is the private exponent `d`. + +There are two additional functions: +\- `encrypt(text: str, n: int, e: int) -> str`: Encrypts a given string using the provided public key and returns the encrypted string. +\- `decrypt(text: str, d: int, n: int) -> str`: Decrypts a given string using the provided private key. diff --git a/Testing.md b/Testing.md new file mode 100644 index 0000000..8171f17 --- /dev/null +++ b/Testing.md @@ -0,0 +1,44 @@ +### The coverage report of the unit tests. +``` +Name Stmts Miss Cover +-------------------------------------------------- +test/__init__.py 0 0 100% +test/test_eea.py 105 1 99% +test/test_encrypt_decrypt.py 18 1 94% +test/test_generator.py 14 1 93% +test/test_primality_test.py 51 1 98% +-------------------------------------------------- +TOTAL 188 4 98% +``` + +### What has been tested and how? +\- The Extended Euclidean Algorithm has been tested to make sure that given `a` and `b`, it correctly returns a tuple `(gcd, x, y)` such that `a * x + b * y = gcd`, with `gcd` being the greatest common divisor of `a` and `b`. The following cases were tested: +\+ Both `a`, `b` are positive integers. +\+ Either `a` or `b` is zero. +\+ Both `a` and `b` are zero. +\+ Either `a` or `b` is negative, the other is positive. +\+ Both `a` and `b` are negative integers. + +\- The implementation of the Miller-Rabin primality test has been tested. The implementation correctly works as the test theoretically envisioned. The test is only probabilistic, so it might occassionally mistake a composite number as a prime. However, for our purposes, it is good enough. +\- The key generator has been tested to make sure it correctly returns the public key components `n` and `e` as well as the private key `d`. +\- The encrypt and decrypt functions have been tested to make sure that: +\+ The encrypted string is not the same as the original string. +\+ The decrypted string is the same as the original string. + +### What kind of inputs were used for the testing? +\- For the Extended Euclidean Algorithm, we inputted different values of `a` and `b`. +\- For the Miller-Rabin test, we inputted some prime numbers, non-prime numbers, as well as edge cases. Specifically, we used: +\+ 10 prime numbers, including 5 small prime numbers and 5 verified large prime numbers found on Wikipedia +\+ 10 non-prime numbers, including 4 small non-prime numbers and 6 large non-prime numbers. The 6 large non-prime numbers were generated by: +\* Adding 1 to a verified large prime number +\* Multiplying two verified large prime numbers together +\* Multiplying a verified large prime number with a random number in the range $[1, 10^{1000})$ +\* Multiplying another verified large prime number with a random number in the range $[1, 7^{750})$ +\* Multiplying two random numbers in the range $[1, 10^{1000})$ together +\* Multiplying two verified large prime numbers together, again +\+ 5 edge cases: 0, 1, 2, 3, 5 +\- For the key generator, no input is required. +\- For the encrypt and decrypt functions, we inputted a few sample strings in several different languages, including a 257-character string to ensure that the algorithm can at least encrypt and decrypt strings of length up to 256 characters. + +### How can the tests be repeated? +Running `./coverage.sh` on the terminal should execute all the written tests. New tests can also be written to the files inside the [test](./test) folder. diff --git a/User Guide.md b/User Guide.md new file mode 100644 index 0000000..5144e9b --- /dev/null +++ b/User Guide.md @@ -0,0 +1,17 @@ +### Installing the dependencies +Running `pip install -r requirements.txt` should install all the necessary packages for the project. + +### Generating a new key-pair +Running `./generate.py` should print out n, e, and d. n and e are components of the public key, while d is the private key. + +### Encrypting a string +Running `./encrypt.py text n e` should encrypt `text` and print out the encrypted string. + +### Decrypting a string +Running `./decrypt.py text d n` should decrypt `text` and print out the decrypted string. + +### Running the CLI +If you don't want to run the scripts separately, you can run `./main.py` to use the default CLI of the project. + +### Limitations +Due to the limited key size, the algorithm cannot correctly encrypt and decrypt strings exceeding certain lengths. To increase the length of supported strings, modify [generate.py](./generate.py) to increase the size of the generated keys. diff --git a/Week 1 Report.md b/Week 1 Report.md new file mode 100644 index 0000000..4903a38 --- /dev/null +++ b/Week 1 Report.md @@ -0,0 +1,14 @@ +### What have you done this week? +I initiliased the repository, registered the repository in Labtool, and chosen a topic for the course. + +### How has the project progressed? +So far I have not written any actual code. I'm currently reading on how RSA encryption works and how it is implemented, step by step. Once I have a firm understanding of what needs to be done, I will start working on the code immediately. + +### What did you learn this week / today? +RSA encryption and related mathematical algorithms. + +### What has been unclear or problematic? Please answer this question truthfully, as this is something the course assistant may be able to help with. +So far, nothing. I am confident that I will be able to complete this project. If there are any troubles, I will contact the course assistant immediately. + +### What next? +I will read up on any algorithms necessary to implement RSA encryption, and once I know how they work, I will immediately start writing code. diff --git a/Week 2 Report.md b/Week 2 Report.md new file mode 100644 index 0000000..2140047 --- /dev/null +++ b/Week 2 Report.md @@ -0,0 +1,29 @@ +### What have you done this week? + +\- Implemented a basic RSA key generator +\- Configured [pylint](https://gamedevacademy.org/pylint-tutorial-complete-guide/) to assess code quality +\- Configured unit tests for the developed functions (Miller-Rabin test and Extended Euclidean Algorithm) +\- Configured [coverage](https://www.pythontutorial.net/python-unit-testing/python-unittest-coverage/) to check that the unit tests have sufficient coverage + +### How has the project progressed? + +A basic RSA key generator has been developed. Unit tests for the Miller-Rabin test and Extended Euclidean Algorithm have also been written. + +### What did you learn this week / today? + +\- [Miller-Rabin primality test](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test) +\- [Extended Euclidean Algorithm](https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm) +\- [pylint](https://gamedevacademy.org/pylint-tutorial-complete-guide/) +\- [unittest](https://www.pythontutorial.net/python-unit-testing/python-run-unittest/) +\- [coverage](https://www.pythontutorial.net/python-unit-testing/python-unittest-coverage/) + +### What has been unclear or problematic? Please answer this question truthfully, as this is something the course assistant may be able to help with. + +So far, nothing. I am confident that I will be able to complete this project. If there are any troubles, I will contact the course assistant immediately. + +### What next? + +\- The `encrypt(text: str, n: int, e: int) -> str` and `decrypt(text: str, d: int, n: int) -> str` funcions will be developed. +\- The [Testing.md](./Testing.md) document will be updated. +\- If I receive any feedback or suggestion about a missing feature, I will consider implementing it. +\- Bug fixes (as necessary) diff --git a/Week 3 Report.md b/Week 3 Report.md new file mode 100644 index 0000000..ba336e8 --- /dev/null +++ b/Week 3 Report.md @@ -0,0 +1,24 @@ +### What have you done this week? +\- The `encrypt(text: str, n: int, e: int) -> str` and `decrypt(text: str, d: int, n: int) -> str` funcions have been developed. +\- A unit test to make sure the key generator correctly returns the public and private keys has been written. +\- A unit test to make sure that the encrypt and decrypt functions work correctly has been implemented. +\- The [Testing.md](./Testing.md) document has been updated. +\- The [User Guide.md](./User%20Guide.md) document has been updated. +\- Added [.pylintrc](./.pylintrc) + +### How has the project progressed? +Most of the main functionalities and tests have been implemented. I might consider developing additional features like a GUI for the program. If I receive any feedback or suggestion about a missing feature, I will also consider implementing it. + +### What did you learn this week / today? +Options for [.pylintrc](./.pylintrc) + +### What has been unclear or problematic? Please answer this question truthfully, as this is something the course assistant may be able to help with. + +So far, nothing. I am confident that I will be able to complete this project. If there are any troubles, I will contact the course assistant immediately. + +### What next? +\- (Potentially) developing a simple GUI for the program +\- Optimising the code to improve pylint ratings +\- Updating the [Specification.md](./Specification.md) document after everything has been completed +\- Responding to feedback and suggestions (if any) +\- Bug fixes (as necessary) diff --git a/Week 4 Report.md b/Week 4 Report.md new file mode 100644 index 0000000..3de59bb --- /dev/null +++ b/Week 4 Report.md @@ -0,0 +1,17 @@ +### What have you done this week? +\- Added a great number of test cases for each of the written tests (including very large inputs) +\- Updated the coverage report in [Testing.md](./Testing.md) +\- Provisionally updated [Specification.md](./Specification.md) +\- Updated the [coverage.sh](./coverage.sh) script + +### How has the project progressed? +The project is mostly completed from the technical perspective, although more extensive documentation can and certainly will be added. + +### What has been unclear or problematic? Please answer this question truthfully, as this is something the course assistant may be able to help with. +So far, nothing. I am confident that I will be able to complete this project. If there are any troubles, I will contact the course assistant immediately. + +### What next? +\- Updating the code to improve pylint ratings +\- Updating [Implementation.md](./Implementation.md) as the project becomes more refined +\- Responding to feedback and suggestions (if any) +\- Bug fixes (as necessary) diff --git a/Week 5 Report.md b/Week 5 Report.md new file mode 100644 index 0000000..2d1b0be --- /dev/null +++ b/Week 5 Report.md @@ -0,0 +1,19 @@ +### What have you done this week? +\- Modified the tests for Miller-Rabin to use actually verified large prime numbers +\- Added a 257-character string to [test_encrypt_decrypt.py](./test/test_encrypt_decrypt.py) to ensure that the algorithm can at least encrypt and decrypt strings of length up to 256 characters +\- Slightly modified [generate.py](./generate.py) to ensure that the generated keys are at least 1024 bits long +\- Added a CLI for the program: [main.py](./main.py) +\- Updated [Testing.md](./Testing.md) to actually detail the data used to test Miller-Rabin +\- Updated [Implementation.md](./Implementation.md) and [User Guide.md](./User%20Guide.md) to include information about [main.py](./main.py) + +### How has the project progressed? +The project is mostly completed. There will be some final updates to the project. + +### What has been unclear or problematic? Please answer this question truthfully, as this is something the course assistant may be able to help with. +So far, nothing. I am confident that I will be able to complete this project. If there are any troubles, I will contact the course assistant immediately. + +### What next? +\- Updating the code to improve pylint ratings +\- Responding to feedback and suggestions (if any) +\- Fixing bugs (as necessary) +\- Wrapping up the project diff --git a/Week 6 Report.md b/Week 6 Report.md new file mode 100644 index 0000000..62ab739 --- /dev/null +++ b/Week 6 Report.md @@ -0,0 +1,12 @@ +### What have you done this week? +\- Added a [requirements.txt](./requirements.txt) file for the project's dependencies +\- Made a few modifications to improve [pylint](./pylint.sh) ratings to `10.00/10` +\- Responded to the peer review by making the suggested adjustments +\- Updated the [User Guide.md](./User%20Guide.md) to include instructions for installing the dependencies + +### How has the project progressed? +The project is officially completed. + +### What next? +\- Demonstrating the project in the demo session +\- Archiving the project diff --git a/coverage.sh b/coverage.sh new file mode 100755 index 0000000..15daf71 --- /dev/null +++ b/coverage.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +if pip list | grep -q 'coverage'; then + python -m coverage run --omit=*/dist-packages/*,functions.py,generate.py,encrypt.py,decrypt.py -m unittest + python -m coverage report +else + pip install coverage + python -m coverage run --omit=*/dist-packages/*,functions.py,generate.py,encrypt.py,decrypt.py -m unittest + python -m coverage report +fi diff --git a/decrypt.py b/decrypt.py new file mode 100755 index 0000000..2dcb326 --- /dev/null +++ b/decrypt.py @@ -0,0 +1,35 @@ +#!/usr/bin/python +import sys + + +def decrypt(text: str, d: int, n: int) -> str: + try: + # Convert the encrypted string into an integer + cyphertext_int = int(text) + + # Calculate the plaintext m (in integer form) according to the formula c^d = (m^e)^d = m, where c is the cyphertext (in integer form) + plaintext_int = pow(cyphertext_int, d, n) + + # Convert m from integer form back to the original string + plaintext_bytes = plaintext_int.to_bytes((n.bit_length() + 7) // 8, 'big') + plaintext = plaintext_bytes.strip(b'\x00').decode('utf-8') + return plaintext + except: + return 'Decryption Error!' + + +def main(): + if len(sys.argv) != 4: + print('Usage: ./decrypt.py text d n') + sys.exit(1) + + cyphertext = sys.argv[1] + d = int(sys.argv[2]) + n = int(sys.argv[3]) + + decrypted_text = decrypt(cyphertext, d, n) + print(f'Decrypted Text: {decrypted_text}') + + +if __name__ == '__main__': + main() diff --git a/encrypt.py b/encrypt.py new file mode 100755 index 0000000..4f01071 --- /dev/null +++ b/encrypt.py @@ -0,0 +1,29 @@ +#!/usr/bin/python +import sys + + +def encrypt(text: str, n: int, e: int) -> str: + # Convert the given string into an integer using utf-8 encoding + plaintext_int = int.from_bytes(text.encode('utf-8'), 'big') + + # Compute the cyphertext c (in integer form) according to the formula c = m^e mod n + cyphertext_int = pow(plaintext_int, e, n) + + return str(cyphertext_int) + + +def main(): + if len(sys.argv) != 4: + print('Usage: ./encrypt.py text n e') + sys.exit(1) + + text = sys.argv[1] + n = int(sys.argv[2]) + e = int(sys.argv[3]) + + encrypted_text = encrypt(text, n, e) + print(f'Encrypted Text: {encrypted_text}') + + +if __name__ == '__main__': + main() diff --git a/functions.py b/functions.py new file mode 100644 index 0000000..de6431d --- /dev/null +++ b/functions.py @@ -0,0 +1,50 @@ +"""This module implements the Miller-Rabin primality test and the Extended Euclidean Algorithm.""" +import random + + +# Python implementation of the Miller-Rabin test according to the pseudocode at +# https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Pseudocode:~:text=prime%E2%80%9D%20otherwise-,let%20s%20%3E%200%20and%20d%20odd%20%3E%200%20such%20that%20n%20%E2%88%92%201,1%20then%0A%20%20%20%20%20%20%20%20return%20%E2%80%9Ccomposite%E2%80%9D%0Areturn%20%E2%80%9Cprobably%20prime%E2%80%9D,-Complexity%5Bedit +# n is the number to be tested; k is the number of testing rounds +def primality_test(n: int, k: int = 100) -> bool: + """Miller-Rabin primality test""" + if n <= 1: + return False + if n in (2, 3): + return True + if n % 2 == 0: + return False + s = 0 + d = n - 1 + while d % 2 == 0: + d //= 2 + s += 1 + for _ in range(k): + a = random.randint(2, n - 2) + x = pow(a, d, n) + if x in (1, n - 1): + continue + for _ in range(s - 1): + x = pow(x, 2, n) + if x == n - 1: + break + else: + return False + return True + + +# Python implementation of the Extended Euclidean Algorithm according to the pseudoode at +# https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Pseudocode:~:text=function%20extended_gcd(a,gcd%3A%22%2C%20(t%2C%20s) +# Returns a tuple (gcd, x, y) such that a * x + b * y = gcd, with gcd being the greatest common divisor of a and b. +def extended_gcd(a: int, b: int) -> tuple[int, int, int]: + """Extended Euclidean Algorithm""" + old_r, r = a, b + old_s, s = 1, 0 + old_t, t = 0, 1 + + while r != 0: + quotient = old_r // r + old_r, r = r, old_r - quotient * r + old_s, s = s, old_s - quotient * s + old_t, t = t, old_t - quotient * t + + return (abs(old_r), old_s, old_t) diff --git a/generate.py b/generate.py new file mode 100755 index 0000000..c3e7c73 --- /dev/null +++ b/generate.py @@ -0,0 +1,51 @@ +#!/usr/bin/python +import math + +from functions import primality_test +from functions import extended_gcd +from Cryptodome.Random.random import getrandbits + + +def generate() -> tuple[int, int, int]: + # Step 1: Find two large prime number p and q such that their produce has length of at least 1024 bits. + p = None + q = None + + # p*q will certainly be at least 1024 bits long if p and q are at least 1024 bits long each. + while p == None: + num_bits = 2048 + random_number = getrandbits(num_bits - 1) | (1 << (num_bits - 1)) # Generate 2047 random bits and add an additional 1-bit to the left to create a random 2048-bit integer + if random_number >= 2**1023 and primality_test(random_number): + p = random_number + + while q == None: + num_bits = 2048 + random_number = getrandbits(num_bits - 1) | (1 << (num_bits - 1)) + if random_number >= 2**1023 and primality_test(random_number) and p != random_number: + q = random_number + + # Step 2: Compute n = p * q + n = p * q + + # Step 3: Compute λ(n) + delta_n = math.lcm(p - 1, q - 1) + + # Step 4: Choose an integer e such that 1 < e < λ(n) and gcd(e, λ(n)) = 1; that is, e and λ(n) are coprime. + e = 65537 + + # Step 5: Determine d as d ≡ e^(-1)(mod λ(n)); that is, d is the modular multiplicative inverse of e modulo λ(n). + _, x, _ = extended_gcd(e, delta_n) + d = x % delta_n + + return (n, e, d) + + +def main(): + (n, e, d) = generate() + print(f'n: {n}') + print(f'e: {e}') + print(f'd: {d}') + + +if __name__ == '__main__': + main() diff --git a/main.py b/main.py new file mode 100755 index 0000000..2194440 --- /dev/null +++ b/main.py @@ -0,0 +1,60 @@ +#!/usr/bin/python +from generate import generate +from encrypt import encrypt +from decrypt import decrypt + + +def main(): + while True: + choice = input("""What do you want to do? +1. Generate a new key pair +2. Encrypt a string +3. Decrypt a string +4. Exit the program + +Enter your choice (1, 2, 3, or 4): """) + if choice == '1': + print() + (n, e, d) = generate() + print('A new key pair has been successfully generated!') + print('Public key components:') + print(f'n: {n}') + print(f'e: {e}') + print('Private key component:') + print(f'd: {d}') + print() + pass + elif choice == '2': + print() + text = input('Enter the string to encrypt: ') + n = int(input('Enter n: ')) + e = int(input('Enter e: ')) + try: + encrypted_text = encrypt(text, n, e) + print(f'The string has been encrypted to: {encrypted_text}') + except: + print('Encryption Error!') + print() + pass + elif choice == '3': + print() + text = input('Enter the string to decrypt: ') + d = int(input('Enter d: ')) + n = int(input('Enter n: ')) + try: + decrypted_text = decrypt(text, d, n) + print(f'The string has been decrypted to: {decrypted_text}') + except: + print('Decryption Error!') + print() + pass + elif choice == '4': + break + else: + print() + print('Invalid input. Exitting the program...') + break + + +if __name__ == '__main__': + main() diff --git a/pylint.sh b/pylint.sh new file mode 100755 index 0000000..c59a186 --- /dev/null +++ b/pylint.sh @@ -0,0 +1,8 @@ +#!/bin/bash + +if which pylint >/dev/null; then + pylint functions +else + pip install pylint + pylint functions +fi diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..6dcd759 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +coverage +pycryptodome +pylint +sympy diff --git a/test/__init__.py b/test/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/test/test_eea.py b/test/test_eea.py new file mode 100644 index 0000000..c3be1d8 --- /dev/null +++ b/test/test_eea.py @@ -0,0 +1,138 @@ +import sys +import unittest + +sys.path.append('../') +from functions import extended_gcd + +from sympy import prevprime +import random + + +class TestExtendedEuclideanAlgorithm(unittest.TestCase): + + def test_positive_numbers(self): + gcd, x, y = extended_gcd(240, 46) + self.assertEqual(gcd, 2) + self.assertEqual(240 * x + 46 * y, gcd) + + gcd, x, y = extended_gcd(123456, 789012) + self.assertEqual(gcd, 12) + self.assertEqual(123456 * x + 789012 * y, gcd) + + gcd, x, y = extended_gcd(65345, 323160) + self.assertEqual(gcd, 5) + self.assertEqual(65345 * x + 323160 * y, gcd) + + gcd, x, y = extended_gcd(2330646462, 3044333) + self.assertEqual(gcd, 1) + self.assertEqual(2330646462 * x + 3044333 * y, gcd) + + gcd, x, y = extended_gcd(926467262, 6430314335) + self.assertEqual(gcd, 1) + self.assertEqual(926467262 * x + 6430314335 * y, gcd) + + def test_one_zero(self): + gcd, x, y = extended_gcd(7, 0) + self.assertEqual(gcd, 7) + self.assertEqual(7 * x + 0 * y, gcd) + + gcd, x, y = extended_gcd(0, 239402839) + self.assertEqual(gcd, 239402839) + self.assertEqual(0 * x + 239402839 * y, gcd) + + gcd, x, y = extended_gcd(0, 29342093849283409283984234) + self.assertEqual(gcd, 29342093849283409283984234) + self.assertEqual(0 * x + 29342093849283409283984234 * y, gcd) + + gcd, x, y = extended_gcd(888888888888888888888888, 0) + self.assertEqual(gcd, 888888888888888888888888) + self.assertEqual(888888888888888888888888 * x + 0 * y, gcd) + + gcd, x, y = extended_gcd(10**100, 0) + self.assertEqual(gcd, 10**100) + self.assertEqual(10**100 * x + 0 * y, gcd) + + def test_both_zeros(self): + gcd, x, y = extended_gcd(0, 0) + self.assertEqual(gcd, 0) + self.assertEqual(0 * x + 0 * y, gcd) + + def test_negative_numbers(self): + gcd, x, y = extended_gcd(-120, 23) + self.assertEqual(gcd, 1) + self.assertEqual(abs((-120) * x + 23 * y), gcd) + + gcd, x, y = extended_gcd(-120, 23) + self.assertEqual(gcd, 1) + self.assertEqual(abs((-120) * x + 23 * y), gcd) + + gcd, x, y = extended_gcd(-15, 4) + self.assertEqual(gcd, 1) + self.assertEqual(abs((-15) * x + 4 * y), gcd) + + gcd, x, y = extended_gcd(-123456, 78901) + self.assertEqual(gcd, 1) + self.assertEqual(abs((-123456) * x + 78901 * y), gcd) + + gcd, x, y = extended_gcd(101, -50) + self.assertEqual(gcd, 1) + self.assertEqual(abs(101 * x + (-50) * y), gcd) + + gcd, x, y = extended_gcd(100000, -45000) + self.assertEqual(gcd, 5000) + self.assertEqual(abs(100000 * x + (-45000) * y), gcd) + + def test_both_negatives(self): + gcd, x, y = extended_gcd(-10, -25) + self.assertEqual(gcd, 5) + self.assertEqual(abs((-10) * x + (-25) * y), gcd) + + gcd, x, y = extended_gcd(-120, -360) + self.assertEqual(gcd, 120) + self.assertEqual(abs((-120) * x + (-360) * y), gcd) + + gcd, x, y = extended_gcd(-123456, -789012) + self.assertEqual(gcd, 12) + self.assertEqual(abs((-123456) * x + (-789012) * y), gcd) + + gcd, x, y = extended_gcd(-101, -103) + self.assertEqual(gcd, 1) + self.assertEqual(abs((-101) * x + (-103) * y), gcd) + + gcd, x, y = extended_gcd(-1001, -997) + self.assertEqual(gcd, 1) + self.assertEqual(abs((-1001) * x + (-997) * y), gcd) + + def test_very_large_numbers(self): + large_prime_1 = prevprime(10**50) + large_prime_2 = prevprime(10**100) + gcd, x, y = extended_gcd(large_prime_1, large_prime_2) + self.assertEqual(gcd, 1) + self.assertEqual(large_prime_1 * x + large_prime_2 * y, gcd) + + random_num = random.randint(1, 10**50) + gcd, x, y = extended_gcd(random_num, random_num * large_prime_2) + self.assertEqual(gcd, random_num) + self.assertEqual(random_num * x + random_num * large_prime_2 * y, gcd) + + random_num = random.randint(1, 10**50) + large_prime_2 = prevprime(10**500) + gcd, x, y = extended_gcd(random_num, random_num * large_prime_2) + self.assertEqual(gcd, random_num) + self.assertEqual(random_num * x + random_num * large_prime_2 * y, gcd) + + random_num = random.randint(1, 10**50) + large_prime_2 = prevprime(10**750) + gcd, x, y = extended_gcd(random_num, random_num * large_prime_2) + self.assertEqual(gcd, random_num) + self.assertEqual(random_num * x + random_num * large_prime_2 * y, gcd) + + random_num = random.randint(1, 10**50) + large_prime_2 = prevprime(10**1000) + gcd, x, y = extended_gcd(random_num, random_num * large_prime_2) + self.assertEqual(gcd, random_num) + self.assertEqual(random_num * x + random_num * large_prime_2 * y, gcd) + + +if __name__ == '__main__': + unittest.main() diff --git a/test/test_encrypt_decrypt.py b/test/test_encrypt_decrypt.py new file mode 100644 index 0000000..db1f598 --- /dev/null +++ b/test/test_encrypt_decrypt.py @@ -0,0 +1,31 @@ +import sys +import unittest + +sys.path.append('../../') +from generate import generate +from encrypt import encrypt +from decrypt import decrypt + + +class TestEncryptDecrypt(unittest.TestCase): + + def test_encrypt_decrypt(self): + test_strings = [ + "Manifesto of the Communist Party A spectre is haunting Europe — the spectre of communism. All the powers of old Europe have entered into a holy alliance to exorcise this spectre: Pope and Tsar, Metternich and Guizot, French Radicals and German police-spies.", # 257-character string + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', + '没有共产党就没有新中国', + 'nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän kymmenen', + 'Jag förstår inte.', + '12 апреля 1961 года Юрий Гагарин стал первым человеком в мировой истории, совершившим полёт в космическое пространство.' + ] + for ORIGINAL_STRING in test_strings: + (n, e, d) = generate() + encrypted = encrypt(ORIGINAL_STRING, n, e) + self.assertNotEqual(ORIGINAL_STRING, encrypted, 'The encrypted string is not the same as the original string.') + self.assertIsInstance(encrypted, str, 'The result of the encryption is indeed a string.') + decrypted = decrypt(encrypted, d, n) + self.assertEqual(ORIGINAL_STRING, decrypted, 'The decrypted string matches the original string.') + + +if __name__ == '__main__': + unittest.main() diff --git a/test/test_generator.py b/test/test_generator.py new file mode 100644 index 0000000..79f981a --- /dev/null +++ b/test/test_generator.py @@ -0,0 +1,20 @@ +import sys +import unittest + +sys.path.append('../../') +from generate import generate +from functions import primality_test + + +class TestGenerator(unittest.TestCase): + + def test_generate(self): + (n, e, d) = generate() + self.assertIsInstance(n, int, 'n is correctly returned as an integer.') + self.assertIsInstance(e, int, 'e is correctly returned as an integer.') + self.assertIsInstance(d, int, 'd is correctly returned as an integer.') + self.assertFalse(primality_test(n), 'n is not a prime number.') + + +if __name__ == '__main__': + unittest.main() diff --git a/test/test_primality_test.py b/test/test_primality_test.py new file mode 100644 index 0000000..64fbb17 --- /dev/null +++ b/test/test_primality_test.py @@ -0,0 +1,70 @@ +import sys +import unittest +import random + +sys.path.append('../') +from functions import primality_test + + +class TestPrimalityTest(unittest.TestCase): + + def test_prime_number(self): + self.assertTrue(primality_test(5), msg='5 is a prime number.') + self.assertTrue(primality_test(7), msg='7 is a prime number.') + self.assertTrue(primality_test(29), msg='29 is a prime number.') + self.assertTrue(primality_test(34841), msg='34841 is a prime number.') + self.assertTrue(primality_test(8328989), msg='8328989 is a prime number.') + + large_prime = (2**32 + 1) // 641 + self.assertTrue(primality_test(large_prime), msg=f'{large_prime} is a prime number.') + + large_prime = (10**18 + 1) // 1000001 + self.assertTrue(primality_test(large_prime), msg=f'{large_prime} is a prime number.') + + large_prime = 170141183460469231731687303715884105727 + self.assertTrue(primality_test(large_prime), msg=f'{large_prime} is a prime number.') + + large_prime = 180 * large_prime**2 + 1 + self.assertTrue(primality_test(large_prime), msg=f'{large_prime} is a prime number.') + + large_prime = 531137992816767098689588206552468627329593117727031923199444138200403559860852242739162502265229285668889329486246501015346579337652707239409519978766587351943831270835393219031728127 + self.assertTrue(primality_test(large_prime), msg=f'{large_prime} is a prime number.') + + def test_non_prime_number(self): + self.assertFalse(primality_test(4), msg='4 is not a prime number.') + self.assertFalse(primality_test(6), msg='6 is not a prime number.') + self.assertFalse(primality_test(8), msg='8 is not a prime number.') + self.assertFalse(primality_test(17650839), msg='17650839 is not a prime number.') + + large_non_prime = 6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151 + 1 + self.assertFalse(primality_test(large_non_prime), msg=f'{large_non_prime} is not a prime number.') + + large_prime = (2**64 + 1) // 274177 + large_prime_2 = (2 * 32 + 1) // 641 + large_non_prime = large_prime * large_prime_2 + self.assertFalse(primality_test(large_non_prime), msg=f'{large_non_prime} is not a prime number.') + + large_non_prime = large_prime * random.randint(1, 10**1000) + self.assertFalse(primality_test(large_non_prime), msg=f'{large_non_prime} is not a prime number.') + + large_non_prime = large_prime_2 * random.randint(1, 7**750) + self.assertFalse(primality_test(large_non_prime), msg=f'{large_non_prime} is not a prime number.') + + large_non_prime = random.randint(1, 10**1000) * random.randint(1, 10**1000) + self.assertFalse(primality_test(large_non_prime), msg=f'{large_non_prime} is not a prime number.') + + large_prime = 531137992816767098689588206552468627329593117727031923199444138200403559860852242739162502265229285668889329486246501015346579337652707239409519978766587351943831270835393219031728127 + large_prime_2 = (2**64 + 1) // 274177 + large_non_prime = large_prime * large_prime_2 + self.assertFalse(primality_test(large_non_prime), msg=f'{large_non_prime} is not a prime number.') + + def test_edge_cases(self): + self.assertFalse(primality_test(0), msg='0 is not a prime number.') + self.assertFalse(primality_test(1), msg='1 is not a prime number.') + self.assertTrue(primality_test(2), msg='2 is a prime number.') + self.assertTrue(primality_test(3), msg='3 is a prime number.') + self.assertTrue(primality_test(5), msg='5 is a prime number.') + + +if __name__ == '__main__': + unittest.main()