A hitelesítőadat-fájl egy konfigurációs fájl, titkosítással. Felhő alkalmazásban használják, a bejelentkezéshez. Egy szkriphez kevés konfiguráció vagy hitelesítő adat szükséges a bejelentkezéshez. A hitelesítőadat-fájlt vagy konfigurációs fájlt hozzáadják a scripthez. A titkosítás itt a kriptográfiai csomag Fernet használatával történik. Tehát a kulcs egy .key fájlban tárolódik. (convert!)
----------------------
#CreateCred.py
#Creates a credential file.
from cryptography.fernet import Fernet
import re
import ctypes
import time
import os
import sys
class Credentials():
def __init__(self):
self.__username = ""
self.__key = ""
self.__password = ""
self.__key_file = 'key.key'
self.__time_of_exp = -1
#----------------------------------------
# Getter setter for attributes
#----------------------------------------
@property
def username(self):
return self.__username
@username.setter
def username(self,username):
while (username == ''):
username = input('Enter a proper User name, blank is not accepted:')
self.__username = username
@property
def password(self):
return self.__password
@password.setter
def password(self,password):
self.__key = Fernet.generate_key()
f = Fernet(self.__key)
self.__password = f.encrypt(password.encode()).decode()
del f
@property
def expiry_time(self):
return self.__time_of_exp
@expiry_time.setter
def expiry_time(self,exp_time):
if(exp_time >= 2):
self.__time_of_exp = exp_time
def create_cred(self):
"""
This function is responsible for encrypting the password and create key file for
storing the key and create a credential file with user name and password
"""
cred_filename = 'CredFile.ini'
with open(cred_filename,'w') as file_in:
file_in.write("#Credential file:\nUsername={}\nPassword={}\nExpiry={}\n"
.format(self.__username,self.__password,self.__time_of_exp))
file_in.write("++"*20)
#If there exists an older key file, This will remove it.
if(os.path.exists(self.__key_file)):
os.remove(self.__key_file)
#Open the Key.key file and place the key in it.
#The key file is hidden.
try:
os_type = sys.platform
if (os_type == 'linux'):
self.__key_file = '.' + self.__key_file
with open(self.__key_file,'w') as key_in:
key_in.write(self.__key.decode())
#Hidding the key file.
#The below code snippet finds out which current os the script is running on and does the task base on it.
if(os_type == 'win32'):
ctypes.windll.kernel32.SetFileAttributesW(self.__key_file, 2)
else:
pass
except PermissionError:
os.remove(self.__key_file)
print("A Permission error occurred.\n Please re run the script")
sys.exit()
self.__username = ""
self.__password = ""
self.__key = ""
self.__key_file
def main():
# Creating an object for Credentials class
creds = Credentials()
#Accepting credentials
creds.username = input("Enter UserName:")
creds.password = input("Enter Password:")
print("Enter the epiry time for key file in minutes, [default:Will never expire]")
creds.expiry_time = int(input("Enter time:") or '-1')
#calling the Credit
creds.create_cred()
print("**"*20)
print("Cred file created successfully at {}"
.format(time.ctime()))
if not(creds.expiry_time == -1):
os.startfile('expire.py')
print("**"*20)
if __name__ == "__main__":
main()
---------------
Kimenet:
A hitelesítő fájl beolvasása, a hitelesítő adatok visszafejtése.
--------------------
#Retrieve credentials.
from cryptography.fernet import Fernet
import os
cred_filename = 'CredFile.ini'
key_file = 'key.key'
key = ''
with open('key.key','r') as key_in:
key = key_in.read().encode()
#If you want the Cred file to be of one
# time use uncomment the below line
#os.remove(key_file)
f = Fernet(key)
with open(cred_filename,'r') as cred_in:
lines = cred_in.readlines()
config = {}
for line in lines:
tuples = line.rstrip('\n').split('=',1)
if tuples[0] in ('Username','Password'):
config[tuples[0]] = tuples[1]
passwd = f.decrypt(config['Password'].encode()).decode()
print("Password:", passwd)
--------------
Kimenet: password:almamater
---------------
Kell még egy „expire.py” fájl, ami elindit egy belső órát és amikor a hitelesítőadat-fájl létrejön, és törli a kulcsfájlt, így a visszafejtés a megadott idő lejárta után már nem lehetséges.
-------------------
expire.py
----------------
import operációs rendszer
importálási idő
kulcs_fájl = 'kulcs.kulcs'
key_exp_start = time . time ()
cred_filename = 'CredFájl.ini'
a következő paranccsal : open ( cred_filename , ' r' ) as cred_in :
sorok = cred_in . readlines ()
konfiguráció = {}
sor a sorokban esetén :
tuples = sor.rstrip ( '\n' ). split ( ' = ' , 1 )
ha a [ 0 ] sorok a ( 'Lejárat ' ) függvényben :
konfiguráció [ tuples [ 0 ]] = tuples [ 1 ]
ha nem ( config [ 'Lejárat ' ] == - 1 ):
# Az alábbi idő másodpercben van megadva.
time_for_exp = int ( config [ 'Lejárat' ]) * 60
while ( os.path.isfile ( kulcsfájl ) ) :
idő.alvás ( 10 )
ha ( nem ( idő.idő ( ) - kulcs_kifejezés_kezdése < = idő_kifejezéshez )
és os.path.isfile ( kulcsfájl ) ) :
os.remove ( kulcsfájl )
--------------
I'm writing a small Python script which will periodically pull information from a 3rd party service using a username and password combo. I don't need to create something that is 100% bulletproof (does 100% even exist?), but I would like to involve a good measure of security so at the very least it would take a long time for someone to break it. This script won't have a GUI and will be run periodically by cron, so entering a password each time it's run to decrypt things won't really work, and I'll have to store the username and password in either an encrypted file or encrypted in a SQLite database, which would be preferable as I'll be using SQLite anyway, and I might need to edit the password at some point. In addition, I'll probably be wrapping the whole program in an EXE, as it's exclusively for Windows at this point.
Nincsenek megjegyzések:
Megjegyzés küldése