コード例 #1
0
def authenticating_server():
    client_id = request.headers.get('id')
    print('Request from Client ID ' + str(client_id))
    client = Clients.query.filter_by(id=client_id).scalar()

    if not client:
        return make_response('Client not valid, dropping connection', 400)

    tgs = TGS.query.filter_by(is_available=1).scalar()

    if not tgs:
        return make_response('Client not valid, dropping connection', 400)

    client_secret_key = hashlib.md5(client.password.encode('utf-8'))
    print(client_secret_key)
    global tgs_secret_key
    tgs_secret_key = hashlib.md5(tgs.password.encode('utf-8'))

    sk1 = "".join(
        random.choice(string.ascii_uppercase + string.ascii_lowercase +
                      string.digits) for _ in range(16))
    print("Session key 1 " + sk1)
    encryption_obj = AES.new(client_secret_key.hexdigest().encode(),
                             AES.MODE_CBC,
                             client_secret_key.hexdigest()[:16].encode())
    # encrypted_sk1 = encryption_obj.encrypt(sk1)

    life_span = 1000
    tgt = "".join(
        str(client_id) + ' ' + str(request.remote_addr) + ' ' +
        str(life_span) + ' ' + str(datetime.now()) + ' ' + sk1)
    print("Generating TGT")
    print(tgt)
    encryption_obj = AES.new(tgs_secret_key.hexdigest().encode(), AES.MODE_CBC,
                             tgs_secret_key.hexdigest()[:16].encode())
    padded_tgt = Padding.appendPadding(tgt, AES.block_size, mode='CMS')
    encrypted_tgt = encryption_obj.encrypt(padded_tgt)

    response = {"sk1": sk1, "tgt": base64.b64encode(encrypted_tgt).decode()}
    encryption_obj = AES.new(client_secret_key.hexdigest().encode(),
                             AES.MODE_CBC,
                             client_secret_key.hexdigest()[:16].encode())
    padded_response = Padding.appendPadding(json.dumps(response),
                                            AES.block_size,
                                            mode='CMS')
    encrypted_response = encryption_obj.encrypt(padded_response)

    print(response)
    return make_response(
        {'data': base64.b64encode(encrypted_response).decode()}, 200)
コード例 #2
0
def tgs():
    data = request.headers
    encrypted_authenticator = base64.b64decode(data.get('authenticator'))
    encrypted_tgt = base64.b64decode(data.get('tgt'))

    decryption_obj = AES.new(tgs_secret_key.hexdigest().encode(), AES.MODE_CBC,
                             tgs_secret_key.hexdigest()[:16].encode())
    tgt = decryption_obj.decrypt(encrypted_tgt).decode()
    sk1 = tgt.split(' ')[-1]
    sk1 = sk1[:16]

    decryption_obj = AES.new(sk1, AES.MODE_CBC, sk1)
    authenticator = decryption_obj.decrypt(
        encrypted_authenticator).decode().strip()[1:]

    if (tgt.split(' ')[0] != authenticator.split(' ')[0]) or (
            tgt.split(' ')[1] != authenticator.split(' ')[1]):
        return make_response('Client not valid, dropping connection', 400)

    sk2 = "".join(
        random.choice(string.ascii_uppercase + string.ascii_lowercase +
                      string.digits) for _ in range(16))
    print("Session key 2 " + sk2)
    service_ticket = "".join(
        str(tgt.split(' ')[0]) + ' ' + str(tgt.split(' ')[1]) + ' ' +
        str(datetime.now()) + ' ' + sk2)
    print("Generating Service ticket")
    print(service_ticket)

    encryption_obj = AES.new(server_secret_key.hexdigest().encode(),
                             AES.MODE_CBC,
                             server_secret_key.hexdigest()[:16].encode())
    padded_service_ticket = Padding.appendPadding(service_ticket,
                                                  AES.block_size,
                                                  mode='CMS')
    encrypted_service_ticket = encryption_obj.encrypt(padded_service_ticket)

    response = {
        "sk2": sk2,
        "service_ticket": base64.b64encode(encrypted_service_ticket).decode()
    }
    encryption_obj = AES.new(sk1, AES.MODE_CBC, sk1)
    padded_response = Padding.appendPadding(json.dumps(response),
                                            AES.block_size,
                                            mode='CMS')
    encrypted_response = encryption_obj.encrypt(padded_response)

    print(response)
    return make_response(
        {'data': base64.b64encode(encrypted_response).decode()}, 200)
コード例 #3
0
 def encrypt_header(self):
     key = "@xyzprinting.com"
     iv = chr(0) * 16
     aes = AESCipher(key, mode=MODE_CBC, IV=iv)
     text = self.gcode.header_text
     header = Padding.appendPadding(text)
     return aes.encrypt(header)
コード例 #4
0
    def encrypt(self):
        key = "@[email protected]"
        iv = chr(0) * 16
        aes = AESCipher(key, mode=MODE_ECB, IV=iv)
        fulltext = self.gcode.text
        padded = Padding.appendPadding(fulltext)
        enc_text = aes.encrypt(padded)

        magic = "3DPFNKG13WTW"
        magic2 = struct.pack("8B", 1, 2, 0, 0, 0, 0, 18, 76)
        blanks = chr(0) * 4684
        tag = "TagEJ256"
        magic3 = struct.pack("4B", 0, 0, 0, 68)
        crc32 = binascii.crc32(enc_text)
        crcstr = struct.pack(">l", crc32)
        encrypted_header = self.encrypt_header()
        bio = BytesIO()
        bio.write(magic)
        bio.write(magic2)
        bio.write(blanks)
        bio.write(tag)
        bio.write(magic3)
        bio.write(crcstr)
        bio.write((chr(0) * (68 - len(crcstr))))
        log.debug("Length of encrypted header: {}".format(
            len(encrypted_header)))
        if len(encrypted_header) > (8192 - bio.tell()):
            log.error("Header is too big to fit file format!")
        bio.write(encrypted_header)
        left = 8192 - bio.tell()
        bio.write((chr(0) * left))
        bio.write(enc_text)
        return bio.getvalue()
コード例 #5
0
def decrypt(ciphertext='', key=llave, iv=vector):
    if ciphertext != '':
        cipher = binascii.a2b_base64(ciphertext)
        encobj = AES.new(key, AES.MODE_OFB, iv)
        return (Padding.removePadding(encobj.decrypt(cipher), mode=0))
    else:
        return ciphertext
コード例 #6
0
def CBCDecrypt(cipherText, KEY, IV):
    cipher = AES.AESCipher(KEY, AES.MODE_ECB)
    dBlocks = []
    Blocks = Padding.pad(cipherText, 16)
    iBlock = Blocks[0]
    cBlock = cipher.decrypt(iBlock)
    dBlock = XOR(cBlock, IV)
    dBlocks.append(dBlock)
    for Block in Blocks[1:]:
        cBlock = cipher.decrypt(Block)
        dBlock = XOR(cBlock, iBlock)
        iBlock = Block
        dBlocks.append(dBlock)
    plainText = ""
    for Block in dBlocks:
        plainText += Block
    return plainText


# IV = "\x00" * 16
# KEY = "YELLOW SUBMARINE"
# file = open("CBCCipherText","r")
# cipherText = ""
# for line in file:
#     cipherText += line.strip("\n")
# file.close()
# # encrypted = CBCEncrypt("Hello World",KEY,IV)
# # print encrypted
# # decrypted = CBCDecrypt(encrypted,KEY,IV)
# # print decrypted
#
# cipherText = binascii.a2b_base64(cipherText)
#
# decrypt = CBCDecrypt(cipherText, KEY, IV)
# print decrypt
コード例 #7
0
def cipherBlock(tag):

    if tag not in block.keys():
        return redirect(url_for('index'))

    from base64 import b64encode, b64decode
    tmp, src, dest, key, iv = '', '', '', b'', b''

    if request.method == 'POST':
        tmp = src = request.form['src']
        key = request.form['key'].encode()
        iv = request.form['iv'].encode()
        mode = request.form['mode']
        padding = request.form['padding']
        c = block[str(tag)]

        try:
            if mode == 'ECB' or mode == 'CBC' or mode == 'CFB':
                src = Padding.appendPadding(src, c.block_size, padding)
            cipher = c.new(key, cipherMode[mode], iv)
            if 'encrypt' in request.url:
                dest = cipher.encrypt(src.encode())
                dest = b64encode(dest).decode()
            else:
                src = b64decode(src.encode())
                dest = cipher.decrypt(src).decode()
                dest = Padding.removePadding(dest)
        except Exception as e:
            dest = e

    if 'encrypt' in request.url:
        return render_template('cipherBlock.html',
                               tag=escape(tag.upper()),
                               flag='Encrypt',
                               src=escape(tmp),
                               dest=escape(dest),
                               key=escape(key.decode()),
                               iv=escape(iv.decode()))

    else:
        return render_template('cipherBlock.html',
                               tag=escape(tag.upper()),
                               flag='Decrypt',
                               src=escape(tmp),
                               dest=escape(dest),
                               key=escape(key.decode()),
                               iv=escape(iv.decode()))
コード例 #8
0
def ECB_Encrypt(Message, Key, Addition, Rand):
    plain = Rand + Addition + Message
    Blocks = Padding.pad(plain, 16)
    plainText = ""
    for Block in Blocks:
        plainText += Block
    cipher = AES.AESCipher(Key, AES.MODE_ECB)
    return cipher.encrypt(plainText)
コード例 #9
0
def ECB_Encrypt(Message, Key, Addition):
    plain = Addition + Message
    Blocks = Padding.pad(plain, 16)
    plainText = ""
    for Block in Blocks:
        plainText += Block
    cipher = AES.AESCipher(Key, AES.MODE_ECB)
    return cipher.encrypt(plainText)
コード例 #10
0
 def des_decrypt(d_key, message):
     cipher = DES.new(d_key, DES.MODE_ECB)
     message = base64.b64decode(message)
     data_decrypt = cipher.decrypt(
         message)  # returns decrypted byte strings
     data_decrypt_rm_pad = Padding.removeNullPadding(
         data_decrypt.decode(), 8)  # removes padding from byte string
     return data_decrypt_rm_pad.encode()
コード例 #11
0
def encECB(Message, Key):
    Blocks = Padding.pad(Message, 16)
    plainText = ""
    for Block in Blocks:
        plainText += Block
    cipher = AES.AESCipher(Key, AES.MODE_ECB)
    cipherText = cipher.encrypt(plainText)
    return cipherText
コード例 #12
0
def EncryptData(UserData, Key, IV):
    UserData = UserData.replace(";","")
    UserData = UserData.replace("=","")
    Str ="comment1=cooking%20MCs;userdata=" + UserData + ";comment2=%20like%20a%20pound%20of%20bacon"
    Blocks = Padding.pad(Str, 16)
    PlainText = ""
    for Block in Blocks:
        PlainText += Block
    return CBCEncrypt(PlainText, Key, IV)
コード例 #13
0
def encCBC(Message, Key):
    Blocks = Padding.pad(Message, 16)
    IV = os.urandom(16)
    plainText = ""
    for Block in Blocks:
        plainText += Block
    cipher = AES.AESCipher(Key, AES.MODE_CBC, IV)
    cipherText = cipher.encrypt(plainText)
    return cipherText
コード例 #14
0
ファイル: encrypt.py プロジェクト: eakova/openmail
 def decrypt(self, data):
     import Padding
     passwd = CONFIG.master_passwd  # this needs to be in a secure store...
     iv, enc_data = data[:16], data[16:]
     print(len(iv),type(iv))
     decryptor = AES.new(hashlib.sha256(passwd).digest(), AES.MODE_CBC, iv)
     padded_data = decryptor.decrypt(enc_data)
     orig_data = Padding.removePadding(padded_data)
     return orig_data
コード例 #15
0
def EncryptData(UserData, Key, IV):
    UserData = UserData.replace(";", "")
    UserData = UserData.replace("=", "")
    Str = "comment1=cooking%20MCs;userdata=" + UserData + ";comment2=%20like%20a%20pound%20of%20bacon"
    Blocks = Padding.pad(Str, 16)
    PlainText = ""
    for Block in Blocks:
        PlainText += Block
    return CBCEncrypt(PlainText, Key, IV)
コード例 #16
0
ファイル: encrypt.py プロジェクト: tkanerva/openmail
 def decrypt(self, data):
     import Padding
     passwd = CONFIG.master_passwd  # this needs to be in a secure store...
     iv, enc_data = data[:16], data[16:]
     print(len(iv), type(iv))
     decryptor = AES.new(hashlib.sha256(passwd).digest(), AES.MODE_CBC, iv)
     padded_data = decryptor.decrypt(enc_data)
     orig_data = Padding.removePadding(padded_data)
     return orig_data
コード例 #17
0
def encrypt(plaintext='', key=llave, iv=vector):
    if plaintext != '':
        plaintext = Padding.appendPadding(plaintext,
                                          blocksize=Padding.AES_blocksize,
                                          mode=0)
        encobj = AES.new(key, AES.MODE_OFB, iv)
        return (binascii.b2a_base64(encobj.encrypt(plaintext)))
    else:
        return plaintext
コード例 #18
0
def encryptProfile(Str):
    Encoded = profile_for(Str)
    Blocks = Padding.pad(Encoded, 16)
    plainText = ""
    for Block in Blocks:
        plainText += Block
    Key = Detection.randKey()
    cipher = AES.AESCipher(Key, AES.MODE_ECB)
    CipherText = cipher.encrypt(plainText)
    return CipherText, Key
コード例 #19
0
ファイル: secureStorage.py プロジェクト: Polychart/builder
def encrypt(key, plaintext):
  assert key

  if plaintext == "":
    return ""

  aes = AES.new(key, AES.MODE_CBC, b"Polychart AES IV")
  padded = Padding.appendPadding(plaintext)
  cipherbytes = aes.encrypt(padded)
  return urlsafe_b64encode(cipherbytes)
コード例 #20
0
ファイル: secureStorage.py プロジェクト: rmoorman/builder
def encrypt(key, plaintext):
    assert key

    if plaintext == "":
        return ""

    aes = AES.new(key, AES.MODE_CBC, b"Polychart AES IV")
    padded = Padding.appendPadding(plaintext)
    cipherbytes = aes.encrypt(padded)
    return urlsafe_b64encode(cipherbytes)
コード例 #21
0
def encryptProfile(Str):
    Encoded = profile_for(Str)
    Blocks = Padding.pad(Encoded, 16)
    plainText = ""
    for Block in Blocks:
        plainText += Block
    Key = Detection.randKey()
    cipher = AES.AESCipher(Key,AES.MODE_ECB)
    CipherText = cipher.encrypt(plainText)
    return CipherText, Key
コード例 #22
0
ファイル: secureStorage.py プロジェクト: Polychart/builder
def decrypt(key, ciphertext):
  assert key

  if ciphertext == "":
    return ""

  aes = AES.new(key, AES.MODE_CBC, b"Polychart AES IV")
  cipherbytes = urlsafe_b64decode(ciphertext.encode('utf-8'))
  padded = aes.decrypt(cipherbytes)
  return Padding.removePadding(padded)
コード例 #23
0
ファイル: secureStorage.py プロジェクト: rmoorman/builder
def decrypt(key, ciphertext):
    assert key

    if ciphertext == "":
        return ""

    aes = AES.new(key, AES.MODE_CBC, b"Polychart AES IV")
    cipherbytes = urlsafe_b64decode(ciphertext.encode('utf-8'))
    padded = aes.decrypt(cipherbytes)
    return Padding.removePadding(padded)
コード例 #24
0
def crack(password, cipher_text):
    key = set_key(password)
    plain_text = decrypt(cipher_text, key, AES.MODE_ECB)
    try:
        plain_text = Padding.removePadding(plain_text, mode='CMS')
        print "  decrypt: " + plain_text
    except AssertionError:
        password = try_next_key(password)
        if password is not None:
            crack(password, cipher_text)
コード例 #25
0
def decrypt(base64Key, randIvString, encryptedString):

    encryptedBytes = base64.b64decode(encryptedString)

    iv = base64.b64decode(randIvString)
    key = base64.b64decode(base64Key)

    obj = AES.new(key, AES.MODE_CBC, iv)

    text = obj.decrypt(encryptedBytes)
    text = Padding.unpad(text, 16, style='pkcs7')
    return text
コード例 #26
0
ファイル: encrypt.py プロジェクト: eakova/openmail
 def encrypt(self, data):  # TODO
     import Padding
     output = ''
     passwd = CONFIG.master_passwd
     # now, encrypt
     padded_data = Padding.appendPadding(data)
     iv = ''.join(chr(random.randint(0, 0xff)) for i in range(16))  # random vector
     encryptor = AES.new(hashlib.sha256(passwd).digest(), AES.MODE_CBC, iv)
     size = len(data)
     output += iv
     output += encryptor.encrypt(padded_data)
     return output
コード例 #27
0
 def des_decrypt(d_key, message):
     """Decrypts DES encrypted data.
     input: d_key: 8-byte key; message: base64 encoded string
     output: decrypted message
     """
     cipher = DES.new(d_key, DES.MODE_ECB)
     message = base64.b64decode(message)
     data_decrypt = cipher.decrypt(
         message)  # returns decrypted byte strings
     data_decrypt_rm_pad = Padding.removeNullPadding(
         data_decrypt.decode(), 8)  # removes padding from byte string
     return data_decrypt_rm_pad
コード例 #28
0
ファイル: encrypt.py プロジェクト: tkanerva/openmail
 def encrypt(self, data):  # TODO
     import Padding
     output = ''
     passwd = CONFIG.master_passwd
     # now, encrypt
     padded_data = Padding.appendPadding(data)
     iv = ''.join(chr(random.randint(0, 0xff))
                  for i in range(16))  # random vector
     encryptor = AES.new(hashlib.sha256(passwd).digest(), AES.MODE_CBC, iv)
     size = len(data)
     output += iv
     output += encryptor.encrypt(padded_data)
     return output
コード例 #29
0
ファイル: talker1.py プロジェクト: sarthakgarg99/ros_drone
def talker():
    pub = rospy.Publisher('chatter1', String, queue_size=10)
    rospy.init_node('talker_new', anonymous=True)
    rate = rospy.Rate(50) # 10hz
    a = ""
    for i in range(0,size):
        a = a + "a"
    rospy.loginfo(sys.getsizeof(a))
    while not rospy.is_shutdown():
        a = ""
        for i in range(0,size):
            a = a + "a"
        time = rospy.get_time()
        hello_str = str(encrypt(Padding.appendPadding(a,mode='CMS'), key, AES.MODE_CBC, salt)) + "|" + str(time)
        rospy.loginfo(hello_str)
        pub.publish(hello_str)
コード例 #30
0
def encrypt(base64Key, inputString):

    # Generates a random 16-byte iv
    iv = Random.new().read(16)
    randIvString = base64.b64encode(iv)

    # Converts key into bytes
    key = base64.b64decode(base64Key)

    obj = AES.new(key, AES.MODE_CBC, iv)

    # Encrypts padded input string
    inputString = Padding.pad(inputString, 16, style='pkcs7')
    encryptedBytes = obj.encrypt(inputString)
    encryptedString = base64.b64encode(encryptedBytes)

    return randIvString, encryptedString
コード例 #31
0
 def handleSendChat(self):
     if self.serverStatus == 0:
         self.setStatus("Set server address first")
         return
     msg = self.chatVar.get().replace(' ', ' ').encode('cp1252')
     iv = '0123456789ABCDEF'
     senha = 'secretkey'
     senha1 = hashlib.sha256(senha).digest()
     aes1 = AES.new(senha1, AES.MODE_CFB, iv)
     plaintext = Padding.appendPadding(msg,
                                       blocksize=Padding.AES_blocksize,
                                       mode=0)
     cipher_text = aes1.encrypt(plaintext)
     if msg == '':
         return
     self.addChat("me", msg)
     for client in self.allClients.keys():
         client.send(cipher_text)
コード例 #32
0
 def handleClientMessages(self, clientsoc, clientaddr):
     while 1:
         try:
             iv = '0123456789ABCDEF'
             senha = 'secretkey'
             senha1 = hashlib.sha256(senha).digest()
             aes2 = AES.new(senha1, AES.MODE_CFB, iv)
             data = clientsoc.recv(self.buffsize)
             decipher_text = aes2.decrypt(data)
             plaintext1 = Padding.removePadding(decipher_text, mode=0)
             if not data:
                 break
             self.addChat("%s:%s" % clientaddr, plaintext1)
         except:
             break
     self.removeClient(clientsoc, clientaddr)
     clientsoc.close()
     self.setStatus("Client disconnected from %s:%s" % clientaddr)
コード例 #33
0
def CBCEncrypt(plainText, KEY, IV):
    cipher = AES.AESCipher(KEY, AES.MODE_ECB)
    eBlocks = []
    if len(plainText) % 16 != 0:
        Blocks = Padding.pad(plainText, 16)
    else:
        Blocks = [plainText[i:i + 16] for i in range(0,len(plainText),16)]
    iBlock = Blocks[0]
    cBlock = XOR(iBlock, IV)
    eBlock = cipher.encrypt(cBlock)
    eBlocks.append(eBlock)
    for Block in Blocks[1:]:
        cBlock = rKeyXOR(Block,eBlock)
        print cBlock
        eBlock = cipher.encrypt(cBlock)
        eBlocks.append(eBlock)
    cipherText = ""
    for Block in eBlocks:
        cipherText += Block
    return cipherText
コード例 #34
0
def CBCEncrypt(plainText, KEY, IV):
    cipher = AES.AESCipher(KEY, AES.MODE_ECB)
    eBlocks = []
    if len(plainText) % 16 != 0:
        Blocks = Padding.pad(plainText, 16)
    else:
        Blocks = [plainText[i:i + 16] for i in range(0, len(plainText), 16)]
    iBlock = Blocks[0]
    cBlock = XOR(iBlock, IV)
    eBlock = cipher.encrypt(cBlock)
    eBlocks.append(eBlock)
    for Block in Blocks[1:]:
        cBlock = rKeyXOR(Block, eBlock)
        print cBlock
        eBlock = cipher.encrypt(cBlock)
        eBlocks.append(eBlock)
    cipherText = ""
    for Block in eBlocks:
        cipherText += Block
    return cipherText
コード例 #35
0
ファイル: talker.py プロジェクト: sarthakgarg99/ros_drone
def talker():
    pub = rospy.Publisher('cam_data', CompressedImage, queue_size=10)
    pub_enc = rospy.Publisher('cam_data_enc', CompressedImage, queue_size=10)
    rospy.init_node('drone_cam', anonymous=True)

    # rate = rospy.Rate(50) # 10hz
    # a = ""
    # for i in range(0,size):
    #     a = a + "a"
    # rospy.loginfo(sys.getsizeof(a))
    while not rospy.is_shutdown():
        msg = CompressedImage()
        msg.header.stamp = rospy.Time.now()
        msg.format = "jpeg"
        msg.data = np.zeros((10, 10)).tostring()
        pub.publish(msg)
        msg_enc = CompressedImage()
        msg_enc.header.stamp = rospy.Time.now()
        msg_enc.format = "jpeg"
        msg_enc.data = encrypt(
            Padding.appendPadding(np.zeros((10, 10)).tostring(), mode='CMS'),
            key, AES.MODE_CBC, salt)
        pub_enc.publish(msg_enc)
コード例 #36
0
def CBCDecrypt(cipherText, KEY, IV):
    cipher = AES.AESCipher(KEY, AES.MODE_ECB)
    dBlocks = []
    Blocks = Padding.pad(cipherText, 16)
    iBlock = Blocks[0]
    cBlock = cipher.decrypt(iBlock)
    dBlock = XOR(cBlock, IV)
    dBlocks.append(dBlock)
    for Block in Blocks[1:]:
        cBlock = cipher.decrypt(Block)
        dBlock = XOR(cBlock, iBlock)
        iBlock = Block
        dBlocks.append(dBlock)
    plainText = ""
    for Block in dBlocks:
        plainText += Block
    return plainText




# IV = "\x00" * 16
# KEY = "YELLOW SUBMARINE"
# file = open("CBCCipherText","r")
# cipherText = ""
# for line in file:
#     cipherText += line.strip("\n")
# file.close()
# # encrypted = CBCEncrypt("Hello World",KEY,IV)
# # print encrypted
# # decrypted = CBCDecrypt(encrypted,KEY,IV)
# # print decrypted
# 
# cipherText = binascii.a2b_base64(cipherText)
# 
# decrypt = CBCDecrypt(cipherText, KEY, IV)
# print decrypt
コード例 #37
0
    return cipher.encrypt(pt)


def dec(ct, key, iv):
    cipher = AES.new(key, AES.MODE_CBC, iv)
    return cipher.decrypt(ct)


key_raw = 'YELLOW SUBMARINE'
block_size = len(key_raw)
iv = chr(0) * block_size
#f = open("cp2-10.txt","ro")
#enc_b64 = ''.join(f.read().strip().split('\n'))
#enc_raw = b64decode(enc_b64)

#print Padding.removePadding(pt, blocksize=block_size, mode='CMS')
#print Padding.removePadding(pt, mode=0)

pt = "Well that's my DJ Deshay cuttin' all them Z's"
#pt = pad_PKCS7(pt, block_size)
pt = Padding.appendPadding(pt, mode=0)

enc_b64 = enc(pt, key_raw, iv)
enc_raw = b64decode(enc_b64)

pt = dec(enc_raw, key_raw, iv)
pt = Padding.removePadding(pt, mode=0)

print enc_b64
print pt
コード例 #38
0
ファイル: padding.py プロジェクト: ryanmcarr99/College

def encrypt(plaintext, key, mode):
    encobj = AES.new(key, mode)
    return (encobj.encrypt(plaintext))


def decrypt(ciphertext, key, mode):
    encobj = AES.new(key, mode)
    return (encobj.decrypt(ciphertext))


key = hashlib.sha256(password.encode()).digest()

plaintext = Padding.appendPadding(plaintext,
                                  blocksize=Padding.AES_blocksize,
                                  mode='CMS')

print("After padding (CMS): ", binascii.hexlify(bytearray(plaintext.encode())))

ciphertext = encrypt(plaintext.encode(), key, AES.MODE_ECB)
print("Cipher (ECB): ", binascii.hexlify(bytearray(ciphertext)))

plaintext = decrypt(ciphertext, key, AES.MODE_ECB)

plaintext = Padding.removePadding(plaintext.decode(), mode='CMS')
print("  decrypt: ", plaintext)

plaintext = val

plaintext = Padding.appendPadding(plaintext,
コード例 #39
0
 def pad(data):
     return Padding.appendNullPadding(data, 8).encode()
コード例 #40
0
def decrypt(ciphertext,key,iv):
    cipher = binascii.a2b_base64(ciphertext)
    encobj = AES.new(key,AES.MODE_OFB,iv)
    return(Padding.removePadding(encobj.decrypt(cipher),mode=0))
コード例 #41
0
'''
URL: https://pypi.python.org/pypi/Padding
Description: Padding methods for password based encryption
'''

import Padding

msg = 'this'
DES_BS = Padding.DES_blocksize
AES_BS = Padding.AES_blocksize


print "DES has fixed block size of %d bits = %d bytes" % (DES_BS*8, DES_BS)

padded_msgDES = Padding.appendPadding(msg, DES_BS)
print padded_msgDES.encode('hex'), len(padded_msgDES)

msgDES = Padding.removePadding(padded_msgDES)
print msgDES, len(msgDES)

print 
print "AES has fixed block size of %d bits = %d bytes" % (AES_BS*8, AES_BS)

padded_msgAES = Padding.appendPadding(msg)
print padded_msgAES.encode('hex'), len(padded_msgAES)

msgAES = Padding.removePadding(padded_msgAES)
print msgAES, len(msgAES)
コード例 #42
0
ファイル: f_01.py プロジェクト: samm606/appliedcrypto
val='hello'
password='******'

plaintext=val

def encrypt(plaintext,key, mode):
	encobj = AES.new(key,mode)
	return(encobj.encrypt(plaintext))

def decrypt(ciphertext,key, mode):
	encobj = AES.new(key,mode)
	return(encobj.decrypt(ciphertext))

key = hashlib.sha256(password.encode()).digest()


plaintext = Padding.appendPadding(plaintext,blocksize=Padding.AES_blocksize,mode='CMS')

print("After padding (CMS): ",binascii.hexlify(bytearray(plaintext.encode())))

ciphertext = encrypt(plaintext.encode(),key,AES.MODE_ECB)
print("Cipher (ECB): ",binascii.hexlify(bytearray(ciphertext)))

plaintext = decrypt(ciphertext,key,AES.MODE_ECB)

plaintext = Padding.removePadding(plaintext.decode(),mode='CMS')
print("  decrypt: ",plaintext)

plaintext=val

コード例 #43
0
def decryptProfile(CipherText, Key):
    cipher = AES.AESCipher(Key, AES.MODE_ECB)
    Encoded = cipher.decrypt(CipherText)
    endMessage = Padding.unPad(Encoded, 16)
    return decode(endMessage)
コード例 #44
0
ファイル: server.py プロジェクト: throsby/miniSSL
    def init_connection(self, message_tuple):
        all_sent_msgs = ''
        all_recv_msgs = ''

        cert = self.readCertificate(SERVERCERT)
        clientNonce = message_tuple[1]
        initNonce = keyutils.generate_nonce(28)

        if AUTHMETHOD == 'ClientAuth':
            reqClientCert = 'CertReq'
        else:
            reqClientCert = ''

        print 'Initiating handshake...'
        initMsg = ('ServerInit', initNonce, message_tuple[2], cert,
                   reqClientCert)
        initMsg = pickle.dumps(initMsg)
        all_sent_msgs += initMsg
        self.smartSend(self.client_sock, initMsg)

        data = self.smartRecv(self.client_sock)
        all_recv_msgs += data
        initResponse = pickle.loads(data)

        # VALIDATING CERTIFICATE #

        if reqClientCert:
            if not self.validate_certificate(initResponse[RECV_CERT]):
                print 'Bad Certificate!'
                self.client_sock.close()
                exit()
                return

        # DERIVING PUBLIC KEY FROM CERTIFICATE + PRIVATE KEY#

        private_key = \
            keyutils.read_privkey_from_pem(self.readCertificate(SERVERPRIVKEY))

        # COMPUTING SECRET #

        rsa_cipher = PKCS1_OAEP.new(private_key)
        aes_key = rsa_cipher.decrypt(initResponse[3])
        aes_cipher = AES.new(aes_key, AES.MODE_CFB, initResponse[2])
        secret = aes_cipher.decrypt(initResponse[1])

        # DERIVING KEYS FROM SECRET #

        session_key_one = keyutils.create_hmac(secret, initNonce
                + clientNonce + '00000000')
        session_key_two = keyutils.create_hmac(secret, initNonce
                + clientNonce + '11111111')

        if not self.verifyHash(session_key_two, all_sent_msgs,
                               initResponse[RECV_CERT - 1]):
            print 'BAD HASH'
            return
        finalMsg = keyutils.create_hmac(session_key_two, all_sent_msgs)
        all_sent_msgs += finalMsg

        self.smartSend(self.client_sock, finalMsg)

        print 'Handshake was succesful. Waiting for command...'
        data = self.smartRecv(self.client_sock)
        command = pickle.loads(data)

        if command[0] == 'GET':

            # FINAL STEP #

            print 'Received GET command.'
            file = open(PAYLOAD, 'r')
            file_data = file.read()
            init_vector = keyutils.generate_random(16)
            aes_cipher = AES.new(session_key_one, AES.MODE_CFB,
                                 init_vector)
            file_data = Padding.appendPadding(file_data)
            print 'Encrypting file...'
            encrypted_data = aes_cipher.encrypt(file_data)
            pickle_payload = (init_vector, encrypted_data)
            print 'Pickleing payload...'
            pickle_payload = pickle.dumps(pickle_payload)
            print 'Sending payload...'
            self.smartSend(self.client_sock, pickle_payload)
            print 'File sent to client.'