# <>---< Encryptor/Decrypter >---<>
#
# WARNING! USE +PYTHON 3 TO RUN THIS SCRIPT!
# NOTE: To use in python 2.7, remove all types.
#
# Dependencies: pycryptodome, python +3
# install:
#   <> Option I: pip3 install pycryptodome
#   <> Option II: pip3 install pycryptodomex (not tested)

import base64
from io import TextIOWrapper
from typing import BinaryIO
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad,unpad

# Asks an input from the user. Validates that len is the wanted_len.
# Returns it as string.
#
# param txt (str): text displayed in console to the user
# param wanted_len (int): the len that should have the input
def get_string_with_specific_len(text: str, wanted_len: int) -> str :
    value: str = ''

    while len(value) != wanted_len:
        value = str(input(text))
        if len(value) != wanted_len:
            print('      <> Format Error: date should be typed as yyyy-MM-dd format! (2023-01-01)')
            print('')
            
    return value

# Asks about the customer to the user. It applies a validation. len(customer) 
# must be > 0 and <=16. Returns a string with the user input.
def get_customer() -> str :
    customer: str = ''

    while len(customer) == 0 or len(customer) > 16:
        customer = str(input('   Customer code: '))
        if len(customer) == 0 or len(customer) > 16:
            print('      <> Format Error: customer code should have between 1 and 16 characters!')
            print('')
    return customer.upper()

# Asks the user about the expiration date and builds a formatted string
# for Angular Date() type instance. Returns it as string.
def get_expiration_date() -> str:
    print('   Expiration Date (yyyy-MM-dd):')
    year: str = get_string_with_specific_len('      > year: ', 4)
    month: str = get_string_with_specific_len('      < month: ', 2)
    day: str = get_string_with_specific_len('      > day: ', 2)

    return year + '-' + month + '-' + day

# Reads plain text from the provided file and return the content as a string.
#
# param filename (str): the name and path of the file
def read_file(filename: str) -> str:
    file: TextIOWrapper = open(filename, 'r')
    result: str = file.read()
    file.close()
    return result

# Writes a file as binary. If there is no file with
# provided name then creates a new one.
def write_file(filename: str, content: bytes):
    file: BinaryIO = open(filename, 'wb')
    file.write(content)
    file.close()

def generate_key(customer: str) -> str:
    key: str = customer
    counter: int = 0
    while len(key) < 16:
        key += key[counter]
        counter += 1

    return key

# Encrypt the provided raw using the provided key. Returns the encrypted 
# information as bytes.
#
# param raw (str): raw string to encrypt
# param key (str): key used for encryptation
def encrypt(raw: str, key: str) -> bytes:
    raw = pad(raw.encode(), 16)
    cipher = AES.new(key.encode(), AES.MODE_ECB)
    return base64.b64encode(cipher.encrypt(raw))

# Decrypt the provided bytes using the provided key. Then returns it.
#
# param enc (str): raw string to decrypt
# param key (str): key used for decryptation
def decrypt(enc: bytes, key: str):
    enc: bytes = base64.b64decode(enc)
    cipher = AES.new(key.encode(), AES.MODE_ECB)
    return unpad(cipher.decrypt(enc), 16)

if __name__ == '__main__':
    print("-----------------------------------------")
    print(">---<>---< Encryptor/Decrypter >---<>---<")
    print("-----------------------------------------")
    print("")

    # Get the info from the user
    customer: str = get_customer()
    expiration: str = get_expiration_date()

    # Format the string as json
    new_license: str = '{"expiration": "' + expiration + '","customer": "' + customer + '"}'

    # Generates the key using the customer code
    key: bytes = generate_key(customer)

    # Encrypt / decrypt the license and write it into a file
    encrypted: bytes = encrypt(new_license, key)
    decrypted = decrypt(encrypted, key)

    write_file('license.lic', encrypted)

    # Prints the results and ends the script
    print("")
    print("<==>----<=>----< Results >----<=>----<==>")
    print('')
    
    print(' -> Generated key: ', key)
    print(' -> Data: ', decrypted.decode("utf-8", "ignore"))
    print(' -> Encrypted ECB:', encrypted.decode("utf-8", "ignore"))

    print("")
    print("-----------------------------------------")
    print(">---<>---< Process Completed!! >---<>---<")
    print("-----------------------------------------")
 

Python Online Compiler

Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.

Taking inputs (stdin)

OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.

import sys
name = sys.stdin.readline()
print("Hello "+ name)

About Python

Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.

Tutorial & Syntax help

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition IF-ELSE is used.

if conditional-expression
    #code
elif conditional-expression
    #code
else:
    #code

Note:

Indentation is very important in Python, make sure the indentation is followed correctly

2. For:

For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.

Example:

mylist=("Iphone","Pixel","Samsung")
for i in mylist:
    print(i)

3. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while condition  
    #code 

Collections

There are four types of collections in Python.

1. List:

List is a collection which is ordered and can be changed. Lists are specified in square brackets.

Example:

mylist=["iPhone","Pixel","Samsung"]
print(mylist)

2. Tuple:

Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.

Example:

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)

Below throws an error if you assign another value to tuple again.

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)

3. Set:

Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.

Example:

myset = {"iPhone","Pixel","Samsung"}
print(myset)

4. Dictionary:

Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.

Example:

mydict = {
    "brand" :"iPhone",
    "model": "iPhone 11"
}
print(mydict)

Supported Libraries

Following are the libraries supported by OneCompiler's Python compiler

NameDescription
NumPyNumPy python library helps users to work on arrays with ease
SciPySciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation
SKLearn/Scikit-learnScikit-learn or Scikit-learn is the most useful library for machine learning in Python
PandasPandas is the most efficient Python library for data manipulation and analysis
DOcplexDOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling