additive_hash


This is a little easy-to-code cipher I made for encrypting text. There are various issues with it, but it’s always fun to have ones own secret code.

import hashlib

def additive_encrypt(data, key):
    result = ""
    h = hashlib.md5()
    h.update(key.encode())
    keyhash = str(h.hexdigest())
    k_idx = 0
    for byte in data:
        n = byte+int(keyhash[k_idx],16)
        if n > 255:
            n = n - 255 #wrap around
        result += chr(n)
        if k_idx+1 < len(keyhash):
            k_idx = 0
        else:
            k_idx += 1
    return result

def additive_decrypt(data, key):
    result = ""
    h = hashlib.md5()
    h.update(key.encode())
    keyhash = str(h.hexdigest())
    k_idx = 0
    for byte in data:
        n = byte-int(keyhash[k_idx],16)
        if n < 0:
            n = n + 255 #wrap around
        result += chr(n)
        if k_idx+1 < len(keyhash):
            k_idx = 0
        else:
            k_idx += 1
    return result

def test(file="test.txt",key="cats"):
    f = open(file,"rb")
    string = f.read()
    f.close()
    c = additive_encrypt(string,key)
    print(c)
    print(additive_decrypt(c.encode(),key))

def simple_decrypt(file,key):
    f = open(file,"rb")
    string = f.read()
    f.close()
    print(additive_decrypt(string,key))

Posted in: Code by nsundin
Copyright © 2011-2025 Programmatic Verse · RSS Feed
Built on Skeleton
Powerered by Wordpress