Cryptography on Renpy

Discuss how to use the Ren'Py engine to create visual novels and story-based games. New releases are announced in this section.
Forum rules
This is the right place for Ren'Py help. Please ask one question per thread, use a descriptive subject like 'NotFound error in option.rpy' , and include all the relevant information - especially any relevant code and traceback messages. Use the code tag to format scripts.
Post Reply
Message
Author
User avatar
Andredron
Regular
Posts: 73
Joined: Thu Dec 28, 2017 2:37 pm
Organization: https://vk.com/renpy
Location: Russia
Contact:

Cryptography on Renpy

#1 Post by Andredron » Wed Apr 25, 2018 6:21 pm

Question! Can I use the following codes in renpy? Independently does not work - mistakes write/Suddenly, there is a person who can tell how to write it in renpy can.
1) The cipher of Caesar is a classic method of encryption and one of the most
famous. The principle of encryption is in the key-position alphabetically

Code: Select all

cryptMode = input("[E]ncrypt|[D]ecrypt: ").upper() 				# Encryption mode switch.
if cryptMode not in ['E','D']: 								# If cryptMode does not equal 'E' or 'D', then output an error and
    print("Error: mode is not Found!"); raise SystemExit 			 #close the program.
startMessage = input("Write the message: ").upper()				 # The message we want to encrypt OR decrypt.
try: rotKey = int(input("Write the key: ")) 						  # Variable-key, if the key is not a number, an error is output.
except ValueError: print("Only numbers!"); raise SystemExit
def encryptDecrypt(mode, message, key, final = ""): 				# The main function that takes arguments: switch, message, key.
    for symbol in message:									 # By-pass the function of the message.   
        if mode == 'E':										 # Encrypt the message using the ASCII table.
            final += chr((ord(symbol) + key - 13)%26 + ord('A'))         
        else: 											# If the switch is equal to the character 'D', then do the same as with 'E' only
            final += chr((ord(symbol) - key - 13)%26 + ord('A')) 					#except for subtracting the variable key, rather than adding it!           
    return final 													# Return the resulting message after encryption / decryption.  
print("Final message:",encryptDecrypt(cryptMode, startMessage, rotKey))		 # Output the resulting message.
$ python file.py
[E]ncrypt|[D]ecrypt: e
Write the message: helloworld
Write the key: 3
Final message: KHOORZRUOG
$ python file.py
[E]ncrypt|[D]ecrypt: d
Write the message: KHOORZRUOG
Write the key: 3
Final message: HELLOWORLD
2) The ROT13 cipher is part of Caesar's cipher with the position 13. The feature of ROT13
is concluded in the principle of involution, which does not require a mode switch
encryption / decryption.

Code: Select all

message = list (input ("write the message:") .upper ()) 			# Enter a message for encryption / decryption.
for symbol in range (len (message)): 							# Enumerate the indexes of each character in the message list.
    message [symbol] = chr (ord (message [symbol])% 26 + ord ('A')) 	# Encrypt the message using the ASCII table.
print ("Final message:", "" .join (message)) 						# Output of the resulting message
$ python file.py
Write the message: helloworld
Final message: URYYBJBEYQ
$ python file.py
Write the message: URYYBJBEYQ
Final message: HELLOWORLD
3) The Tritemius cipher is an improved Caesar cipher in which the key is not
number, and some function. In contrast to the cipher, Caesar is not subject
frequency cryptanalysis. encrypts character by character, changing each time
the value of the argument in the function.

Code: Select all


cryptMode = input ("[E] ncrypt | [D] ecrypt:") .upper () 			# Switch modes encryption / decryption.
if cryptMode not in ['E', 'D']:
    print ("Error: mode is not Found!"); raise SystemExit
startMessage = list (input ("Write the message:") .upper ())			 # Message for encryption / decryption.
for symbol in startMessage:								 # By-character search of the message.
    if symbol is not in [chr (x) for x in range (65,91)]:				# If the character is not in the range from A to Z, then delete this symbol.
        startMessage.remove (symbol)  
funcKey = lambda x: x * 2 									# A key function that takes a numeric value and multiplies it by 2.
def encryptDecrypt (mode, message, key, final = ""):				#  The main function for encryption / decryption is taking the 4 argumentsmode, message, key, final.
    for index, symbol in enumerate (message): 					# Compounding the message. Index - symbol index in the message, Symbol of the message.
        if mode == 'E':										# If the switch is 'E', then assign to the temp variable the resulting numerical value.
            temp = ord (symbol) + key (index) - 13
        else:													# If the switch is equal to the character 'D', then do the same as with 'E' onlyexcept for subtracting the function key, rather than adding it!
           temp = ord (symbol) - key (index) - 13
        final + = chr (temp% 26 + ord ('A'))						# Assign the resulting symbol to the final variable.
    return final # Return the resulting message.
print ("Final message:", encryptDecrypt (cryptMode, startMessage, funcKey))		# Output of the resulting message
$ python file.py
[E]ncrypt|[D]ecrypt: e
Write the message: helloworld
Final message: HGPRWGAFBV
$ python file.py
[E]ncrypt|[D]ecrypt: d
Write the message: HGPRWGAFBV
Final message: HELLOWORLD
4)The replacement code is one of the most common encryption methods. AT
The difference from the cipher of Caesar does not have a specific key and algorithm.

Code: Select all


symbolsAlpha = [chr (x) for x in range (65,91)]				#Declare a list of characters from 'A' to 'Z'.
symbolsCrypt = ('!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '=' ,    		# Declare a list of characters for encryption.
'+', '?', ':', ';', '<', '>', '/', '[', ']', '{', '}', '|', '. ',', ',' ~ ')
cryptMode = input ("[E] ncrypt | [D] ecrypt:") .upper () 			 # Switch for encryption / decryption.
if cryptMode not in ['E', 'D']:
    print ("Error: mode is not Found!"); raise SystemExit
startMessage = input ("Write the message:") .upper ()  			 # Message for encryption / decryption.
keys = dict (zip (symbolsAlpha, symbolsCrypt)) 					# Create a dictionary of this type → an alphabetic character: the character of the hex.
def encryptDecrypt (mode, message, final = ""): 				 # Declare a function with 3 arguments.
    if mode == 'E':										# If the switch is 'E', then do a character search of the message and if the character is in the keys' locks (alphabetic character), then 
        for symbol in message: 								#the variable final to add the value of the key (the hexadecimal character).
            if symbol in keys: final + = keys [symbol]
    else:												# If the switch is 'D', then do a character search of the message and search all keys in the dictionary keys. And if there is a match between the 
        for symbol in message: 									#symbol in message and the key value (the encryption symbol), then to the final variable, add the key itself (alphabetic 
            for key in keys: 												#character).
                if symbol == keys [key]: final + = key
    return final 												 # Return the resulting message.
print ("Final message:", encryptDecrypt (cryptMode, startMessage))  			# Output the resulting message.
$ python file.py
[E]ncrypt|[D]ecrypt: e
Write the message: helloworld
Final message: *%==:}:>=$
$ python file.py
[E]ncrypt|[D]ecrypt: d
Write the message: *%==:}:>=$
Final message: HELLOWORLD
5) The Atbash cipher is one of the easiest encryption methods. Does not require
switch and key for encryption / decryption.

Code: Select all


message = input ("Write the message:") .upper ()		# Message for encryption / decryption.
alphaDefault = [chr (x) for x in range (65,91)]		# Create a list with a character from 'A' to 'Z'.
alphaReverse = list (alphaDefault); alphaReverse.reverse ()		# Create a list with a character from 'A' to 'Z' with a reversal.
final = ""			# Create a final variable.
for symbolMessage in message:		# By-character search in the message.
	for indexAlpha, symbolAlpha in enumerate (alphaDefault):		# By-character search in the alphabet list.
		if symbolMessage == symbolAlpha:		# If the character of the message is equal to the character of the alphabet, then to finalAdd a symbol from the list of the reversed alphabet by index.
			final + = alphaReverse [indexAlpha]
print ("Final message:", final)		# Output the resulting message.
$ python file.py
Write the message: helloworld
Final message: SVOOLDLIOW
$ python file.py
Write the message: SVOOLDLIOW
Final message: HELLOWORLD
6) BruteForce cipher Caesar.

Code: Select all

# Message for decryption.
cryptMessage = input ("Write the message:") .upper ()
# Output of the resulting decryption options.
print ("All possible variants of decrypt:")
# Enumerate all the keys from 0 to 25 inclusive.
for key in range (26):
# If the key is less than 10 - output the index first with zero.
	if key <10: print ("[0% d]"% (key), end = '')
# Otherwise, display the key index without a zero.
	else: print ("[% d]"% (key), end = '')
# By-character search of the encrypted message and key substitution.
	for symbol in cryptMessage:
		print (chr ((ord (symbol) -key-13)% 26 + ord ('A')), end = '')
	print ()
$ python file.py
Write the message: PMTTWEWZTL
All possible variants of decrypt:
[ 00 ] PMTTWEWZTL
[ 01 ] OLSSVDVYSK
[ 02 ] NKRRUCUXRJ
[ 03 ] MJQQTBTWQI
[ 04 ] LIPPSASVPH
[ 05 ] KHOORZRUOG
[ 06 ] JGNNQYQTNF
[ 07 ] IFMMPXPSME
[ 08 ] HELLOWORLD #Wow
[ 09 ] GDKKNVNQKC
[ 10 ] FCJJMUMPJB
[ 11 ] EBIILTLOIA
[ 12 ] DAHHKSKNHZ
[ 13 ] CZGGJRJMGY
[ 14 ] BYFFIQILFX
[ 15 ] AXEEHPHKEW
[ 16 ] ZWDDGOGJDV
[ 17 ] YVCCFNFICU
[ 18 ] XUBBEMEHBT
[ 19 ] WTAADLDGAS
[ 20 ] VSZZCKCFZR
[ 21 ] URYYBJBEYQ
[ 22 ] TQXXAIADXP
[ 23 ] SPWWZHZCWO
[ 24 ] ROVVYGYBVN
[ 25 ] QNUUXFXAUM
7) The cipher is based on AES encryption, but it encrypts not one
file, and the whole directory, which will be the root directory.
Caution: Files are overwritten!

Code: Select all

# The root directory with which to begin encryption of files.
direct = input ("Write the root directory:")
# Set the password for all files.
password = input ("Write the password:")
# Create a python script that will encrypt the files.
with open ("encrypt.py", "w") as encryptFile:
	encryptFile.write ('' '
# Import the os module and the functions argv and encryptFile.
import os
from sys import argv
from pyAesCrypt import encryptFile
# The encrypt function, which is responsible for encrypting an individual file.
def encrypt (file):
# Transfer the password from the server to the encryption script.
	print ("----------------------------------------------- ---------------- ")
	password = "'' '+ str (password) +' '' '
# Set the buffer size for encryption.
	bufferSize = 128 * 1024
# Encrypt the file.
	encryptFile (file, file + ".crp", password, bufferSize)
# Print the result and delete a copy of the unencrypted file.
	print ("[encrypted] '{name} .crp'". format (name = file))
	os.remove (file)
# Function walk, which is responsible for walking through directories and selecting files.
def walk (dir):
# Browse all files and directories in the selected directory.
	for name in os.listdir (dir):
# Full path to the file or directory.
		path = os.path.join (dir, name)
# If the object is a file, then use the encrypt function.
		if os.path.isfile (path): encrypt (path)
# If the object is a directory, then go to this directory.
		else: walk (path)
# Specify the root directory of the builder.
walk ("'' '+ str (direct) +' '' ')
print ("----------------------------------------------- ---------------- ")
# Remove the encryption script file after all the functions have been performed.
os.remove (argv [0])
'' ')
# Output the result of creating the script.
	print ("[+] File 'encrypt.py' successfully saved!")
# Create a python script that will decrypt the files.
with open ("decrypt.py", "w") as decryptFile:
	decryptFile.write ('' '
# Import the os module and the functions argv and decryptFile.
import os
from sys import argv
from pyAesCrypt import decryptFile
# The decrypt function, which is responsible for decrypting a single file.
def decrypt (file):
# Transfer the password from the server to the encryption script.
	print ("----------------------------------------------- ---------------- ")
	password = "'' '+ str (password) +' '' '
# Set the buffer size for encryption.
	bufferSize = 128 * 1024
# Decrypt the file.
	decryptFile (file, os.path.splitext (file) [0], password, bufferSize)
# Print the result and delete the copy of the encrypted file.
	print ("[decrypted] '{name}'". format (name = os.path.splitext (file) [0]))
	os.remove (file)
# Function walk, which is responsible for walking through directories and selecting files.
def walk (dir):
# Browse all files and directories in the selected directory.
	for name in os.listdir (dir):
# Full path to the file or directory.
		path = os.path.join (dir, name)
# If the object is a file, then try decrypting the file. Ifthe file is not encrypted, then skip.
		if os.path.isfile (path):
			try: decrypt (path)
			except: pass
# If the object is a directory, then go to this directory.
		else: walk (path)
# Specify the root directory of the builder.
walk ("'' '+ str (direct) +' '' ')
print ("----------------------------------------------- ---------------- ")
# Deleting the decryption script file after all the functions have been executed.
os.remove (argv [0])
'' ')
# Output the result of creating the script.
	print ("[+] File 'decrypt.py' successfully saved!")
$ python file.py
Write the root directory: /home/user/Templates/Python/TEST/
Write the password: helloworld
[+] File 'encrypt.py' successfully saved!
[+] File 'decrypt.py' successfully saved!
$ python encrypt.py
---------------------------------------------------------------
[encrypted] '/home/user/Templates/Python/TEST/DIR/some.rb.crp'
---------------------------------------------------------------
[encrypted] '/home/user/Templates/Python/TEST/DIR/picture.jpeg.crp'
---------------------------------------------------------------
[encrypted] '/home/user/Templates/Python/TEST/crypter.py.crp'
---------------------------------------------------------------
[encrypted] '/home/user/Templates/Python/TEST/SOMETHING/main.py.crp'
---------------------------------------------------------------
[encrypted] '/home/user/Templates/Python/TEST/SOMETHING/file.txt.crp'
---------------------------------------------------------------
[encrypted] '/home/user/Templates/Python/TEST/decrypt.py.crp'
---------------------------------------------------------------
[encrypted] '/home/user/Templates/Python/TEST/encrypt.py.crp'
---------------------------------------------------------------
$ python decrypt.py
---------------------------------------------------------------
[decrypted] '/home/user/Templates/Python/TEST/crypter.py'
---------------------------------------------------------------
[decrypted] '/home/user/Templates/Python/TEST/DIR/some.rb'
---------------------------------------------------------------
[decrypted] '/home/user/Templates/Python/TEST/DIR/picture.jpeg'
---------------------------------------------------------------
[decrypted] '/home/user/Templates/Python/TEST/encrypt.py'
---------------------------------------------------------------
[decrypted] '/home/user/Templates/Python/TEST/SOMETHING/file.txt'
---------------------------------------------------------------
[decrypted] '/home/user/Templates/Python/TEST/SOMETHING/main.py'
---------------------------------------------------------------
[decrypted] '/home/user/Templates/Python/TEST/decrypt.py'
---------------------------------------------------------------
I know - I have a HORRIBLE ENGLISH
I'm writing a Renpy textbook (in Russian). I would be glad if someone translated into an English or German textbook https://yadi.sk/d/ZX_DonP63USRru Update 24.05.18

Post Reply

Who is online

Users browsing this forum: Remix