Exemple #1
0
def appendixB():
    printBanner()
    print("\n***********************************************\n" +
          "Using Encrypt.py to encrypt the input given\n" +
          "in AppendixB. The result is tested against the\n" +
          "desired result listed in AppendixB of FIPS197\n" +
          "for validation.\n\n" +
          "Would you like to see the datapath between\n" +
          "rounds? You may compare state as desired\n" +
          "this way to what is listed in AppendixB.\n" +
          "***********************************************")
    demoPlainTxt = "3243f6a8885a308d313198a2e0370734"
    demoKey = "2b7e151628aed2a6abf7158809cf4f3c"
    ans = input(
        "Enter Y to see state changes,\nor return to just see the result: ")
    if ans.lower() == "y":
        encrypt = Encrypt(demoPlainTxt, demoKey, printMode=GRID)
    else:
        encrypt = Encrypt(demoPlainTxt, demoKey, printMode=OFF)

    result = encrypt.result
    appendixBResult = "3925841d02dc09fbdc118597196a0b32"
    print("***********************************************")
    print(f"Result matches FIPS197: {result == appendixBResult}")
    print("***********************************************")
Exemple #2
0
def encrypt(e, m, message):
    """
    RSA加密函数
    :param e:
    :param m:
    :param message:
    :return:
    """
    en = Encrypt(e, m)
    return en.encrypt(message)
Exemple #3
0
    def login(self):
        session = self.session
        stuid = self.stuid
        password = self.password

        time_now = int(time.time())
        session.headers.update({
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,ja;q=0.7',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0',
            'X-Requested-With': 'XMLHttpRequest',
            'Connection': 'keep-alive',
            'Content-Length': '0',
            'Host': 'jwgl.njtech.edu.cn',
            'Referer': 'https://jwgl.njtech.edu.cn/',
            'Upgrade-Insecure-Requests': '1'
        })
        # print(time_now)

        # 准备publickey
        url = 'https://jwgl.njtech.edu.cn/xtgl/login_getPublicKey.html?time=' + str(time_now)
        r = session.get(url)
        publickey = r.json()

        # 准备csrftoken
        url = 'https://jwgl.njtech.edu.cn/xtgl/login_slogin.html?language=zh_CN&_t=' + str(time_now)
        r = session.get(url)
        r.encoding = r.apparent_encoding
        soup = BeautifulSoup(r.text, 'html.parser')
        csrftoken = soup.find('input', attrs={'id': 'csrftoken'}).attrs['value']
        # print(csrftoken)

        # 准备密码
        # print(publickey['modulus'])
        # print(publickey['exponent'])
        encrypt = Encrypt(publickey['modulus'], publickey['exponent'], password)
        rsacode = encrypt.rsa_encrypt()

        try:
            url = 'https://jwgl.njtech.edu.cn/xtgl/login_slogin.html?time=' + str(time_now)
            data = {
                'csrftoken': csrftoken,
                'mm': rsacode,
                'yhm': stuid
            }
            result = session.post(url, data=data)
            if '用户名或密码不正确' in result.text:
                raise FError("用户名或密码错误")
        except FError:
            raise FError("用户名或密码错误")
        except:
            raise FError("false 未知错误,请联系网站管理员")
Exemple #4
0
def appendixC():
    printBanner()
    print("\n***********************************************\n" +
          "Using Encrypt.py to encrypt the input given\n" +
          "in AppendixC. The state is tested against the\n" +
          "state in AppendixC of FIPS197 for\n" + "for validation.\n" +
          "***********************************************")
    demoPlainTxt = "00112233445566778899aabbccddeeff"
    demoKey = "000102030405060708090a0b0c0d0e0f"
    input("Press return to start: ")
    encrypt = Encrypt(demoPlainTxt, demoKey, printMode=CMODE)

    result = encrypt.result
    appendixCResult = "69c4e0d86a7b0430d8cdb78070b4c55a"
    print("***********************************************")
    print(f"Result matches FIPS197: {result == appendixCResult}")
    print("***********************************************")
Exemple #5
0
def customEncrypt():
    printBanner()
    print("\n***********************************************\n" +
          "Using Encrypt.py to encrypt your input\n" +
          "***********************************************")
    demoPlainTxt = input("Enter PlainTxt:")
    demoKey = input("     Enter Key:")
    while len(demoPlainTxt) != 32 or len(demoKey) != 32:
        print("please make sure both inputs are 16 bytes of hex")
        demoPlainTxt = input("Enter PlainTxt:")
        demoKey = input("     Enter Key:")
    encrypt = Encrypt(demoPlainTxt, demoKey, printMode=CMODE)

    result = encrypt.result
    print("***********************************************")
    print(f"Result: {result}")
    print("***********************************************")
Exemple #6
0
def newpasswd(key, usbfile, localfile, keydata):
    rad = random.random()
    rad = int(1000 * rad)
    rad = rad % 10
    hopt = pyotp.HOTP(key)
    f = open(usbfile, "w")
    f.truncate()
    f.seek(0)
    f.write(str(hopt.at(rad)))
    f.close()

    f = open(localfile, "w")
    f.truncate()
    f.seek(0)
    key = key + '\n'
    f.write(key)
    f.write(str(rad))
    f.close()
    Encrypt(usbfile)
    return 0
Exemple #7
0
from public_private_keygen import KeyGen
from Decrypt import Decrypt
from Encrypt import Encrypt

if __name__ == '__main__':
    Generator = KeyGen(1024)
    publicKey, privateKey = Generator.getKeys()
    print(f'''
    Public Key: {publicKey}
    Length of Public Key: {len(str(publicKey[0]))}
    Private Key: {privateKey}
    Length of Private Key: {len(str(privateKey[0]))}
    ''')
    t = str(input('Enter text to encrypt\n'))
    encryptor = Encrypt(publicKey)
    decryptor = Decrypt(privateKey)
    enText = encryptor.getEncryptedText(t)
    print('Encrypted text: ', enText)
    deText = decryptor.getDecrypted(enText)
    print('Decrypted Text: ', deText)
Exemple #8
0
import sys
sys.path.append("../Encrypt_And_Decrypt")
from Encrypt import Encrypt
Encrypt("/media/foenix/tmp/code/code.txt")
Exemple #9
0
from KeyGen import KeyGen
from Encrypt import Encrypt
from Decrypt import Decrypt

assymetricKey = KeyGen()
assymetricKey.generateRsaKey()

encrypt = Encrypt()
encrypt.setImagePath("spiderman.jpg")
encrypt.setPublicKeyPath("Public Key")
encrypt.encrypter()

decrypt = Decrypt()
decrypt.setPrivateKeyPath("Private Key")
decrypt.setCipherTextPath("Cipher Text")
decrypt.decrypter()

Exemple #10
0
#FileEncrypt
from Encrypt import Encrypt
from Decrypt import Decrypt
print "-This is a short file encryption program written in Python"
print "-To encrypt, enter \"encrypt <filename>\""
print "-To decrypt, enter \"decrypt <filename>\""
print "-Please note that you must have a key stored in a text file to use this program"

command = raw_input("Enter program option: ")
print command
commandparse = command.split(" ")  #parse command

if commandparse[0] == "encrypt":
    Encrypt(commandparse[1])
elif commandparse[0] == "decrypt":
    Decrypt(commandparse[1])
Exemple #11
0
 def __init__(self, username, password):
     self._username = username
     self._enc = Encrypt()
     self._masterpassword = self.to_byte_string(password)
     self._passdict = self.get_passfile()
Exemple #12
0
class Account():
    def __init__(self, username, password):
        self._username = username
        self._enc = Encrypt()
        self._masterpassword = self.to_byte_string(password)
        self._passdict = self.get_passfile()

    @property
    def username(self):
        return self._username

    @username.setter
    def username(self, username):
        self._username = username

    # Create a new user account
    def create_account(self, masterpassword):
        password = self.to_byte_string(masterpassword)
        self._masterpassword = password

        # Unencrypted state; key to encrypt passfile
        fileKey = get_random_bytes(16)
        self._enc.encrypt_user_info(self.to_byte_string(self._username),
                                    password, fileKey)

        # Create passfile
        # passfile = json.dumps(self._passdict)
        # passfile = self.to_byte_string(passfile)
        self._enc.encrypt_pass(fileKey, self._passdict)
        fileKey = None  # Make sure to delete this unencrypted key!

    # Get unencrypted password file dictionary
    def get_passfile(self):
        return self._enc.decrypt_passfile(self._masterpassword)

    def set_passdict(self, passfiledict):
        self._passdict = passfiledict

    def get_passdict(self):
        return self._passdict

    def set_masterpassword(self, password):
        self._masterpassword = self.to_byte_string(password)

    def change_master_pass(self, newMaster):
        newMaster = self.to_byte_string(newMaster)
        # Decrypt passwordFileKey
        dkey, authkey = self._enc.derive_key_pass(self._masterpassword,
                                                  self._enc.get_salt())
        passwordFileKey = self._enc.decrypt_ciphertext(
            dkey, self._enc.get_obsc_key(), self._enc.get_IV(),
            self._enc.get_tag())

        # Encypt passwordFileKey with newMaster
        username = self.to_byte_string(self._username)
        self._enc.encrypt_user_info(username, newMaster, passwordFileKey)
        self._masterpassword = newMaster
        passwordFileKey = None

    # ==========================================================================
    # Manage passwords in the password manager
    # Add account to passfile (dictionary type)
    # username = account username, not the password manager username
    # passdict = {organisation: {username1: pass1, username2: pass2}, organisation2....}
    def add_account(self, organisation, username, password):
        passdict = self._passdict
        if passdict.get(organisation) is None:
            passdict[organisation] = {}
        passdict[organisation][username] = password
        print(passdict)
        self.set_passdict(passdict)

    # Remove account frrom passfile
    def remove_account(self, organisation, username):
        passdict = self._passdict
        del passdict[organisation][username]
        if len(passdict[organisation]) == 0: del passdict[organisation]
        self.set_passdict(passdict)

    # Edit account username
    def edit_acc_username(self, organisation, oldUsername, newUsername):
        passdict = self._passdict
        password = passdict[organisation][oldUsername]
        del passdict[organisation][oldUsername]
        passdict[organisation][newUsername] = password
        self.set_passdict(passdict)

    # Edit account password
    def edit_acc_password(self, organisation, username, password):
        passdict = self._passdict
        print(passdict)
        print(organisation)
        print(username)
        passdict[organisation][username] = password
        self.set_passdict(passdict)

    # Check if given password has already been used for another account
    def existing_pass(self, addPass):
        passdict = self._passdict
        for organisation, orgdict in passdict.items():
            for username, password in orgdict.items():
                if addPass == password:
                    return True
        return False

    # Remove account
    def remove_passman_account(self):
        print('in remove function')
        os.remove('passfile.bin')
        os.remove('stored_cred.bin')
        self._username = None
        self._enc = None
        self._masterpassword = None
        self._passdict = None

    #===========================================================================
    # Helper methods
    # Validate password form...returns byte string
    def to_byte_string(self, masterpassword):
        try:
            password = masterpassword.encode('utf-8')  # Convert to byte string
        except ValueError:
            with open('Error.txt', 'a+') as f:
                f.write('Password invalid value' + datetime.today())
                print('Password invalid value')
        return password
Exemple #13
0
if __name__ == '__main__':

    #initialzing a 1024 bit key generator
    Generator = KeyGen(1024)

    #public and private key
    publicKey, privateKey = Generator.getKeys()
    print(f'''
    Public Key is: {publicKey}
    Private Key is: {privateKey}
    ''')

    #initializing the encryptor and decryptor with public and private keys
    encryptor = Encrypt(
        privateKey
    )  #using private key to encrypt which is only availaible to the home agent
    decryptor = Decrypt(
        publicKey
    )  #this public key is used to decrypt which is availaible to anyone

    #taking input of the message
    message = str(input('Enter the message to sign\n'))
    #hashing the message
    hashed_message = str(hash(message))

    #encrypting the hashed message
    encrypted_hashed_message = encryptor.getEncryptedText(hashed_message)

    print(f'''
    The message that is sending is this: {message}
Exemple #14
0
          '5: check one user encrypted files;\n' +
          '6: check one user decrypted files;\n' +
          '7: check own encrypted files;\n' +
          '8: check own decrypted files;\n' + '9: check own history;\n' +
          '10: check users list\n' + '11: make other updates\n' + '0: quit\n')
    opt = input("Enter option: ")
    return opt


if __name__ == "__main__":

    cnxn = pyodbc.connect(
        'Driver={ODBC Driver 13 for SQL Server};Server=tcp:cs-server666.database.windows.net,1433;Database=FileEncryption;Uid=alvin;Pwd={pwd};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;'
    )
    cursor = cnxn.cursor()
    encrypt = Encrypt()
    user = 0
    ulogin = False
    while True:
        opt = pmenu()
        #adm.loadUserInfo()
        if opt == '1':
            user = login(cursor)
            if user != False and (isinstance(user, User)
                                  or isinstance(user, Suser)):
                ulogin = True
                while True:
                    optu = pumenu()
                    if optu == '1':
                        torf = user.encrypt_File(encrypt)
                        if torf == True: