Link to home
Start Free TrialLog in
Avatar of donniedarko801
donniedarko801

asked on

Small piece of python code to C#. Can you help?

Hello experts,

I am usually good at understanding new programming languages but I can't port this code to C# since I haven't messed with C# AES encryption before. Basically, I wanted to port this small piece of code to C#. It grabs 2 pieces of information and it creates a key.


try:
    from Crypto.Cipher import AES
except ImportError:
    AES = None

def normalize_name(name):
    return ''.join(x for x in name.lower() if x != ' ')

def generate_keyfile(name, ccn, outpath):
    name = normalize_name(name) + '\x00'
    ccn = ccn + '\x00'
    name_sha = hashlib.sha1(name).digest()[:16]
    ccn_sha = hashlib.sha1(ccn).digest()[:16]
    both_sha = hashlib.sha1(name + ccn).digest()
    aes = AES.new(ccn_sha, AES.MODE_CBC, name_sha)
    crypt = aes.encrypt(both_sha + ('\x0c' * 0x0c))
    userkey = hashlib.sha1(crypt).digest()
    with open(outpath, 'wb') as f:
        f.write(userkey.encode('base64'))
    return userkey

Open in new window

Avatar of donniedarko801
donniedarko801

ASKER

Yeah... I don't think so eh.
ASKER CERTIFIED SOLUTION
Avatar of Kusala Wijayasena
Kusala Wijayasena
Flag of Sri Lanka image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Forgot to put  "NormalizeName" method :)

-Kusala
public string NormalizeName(string name)
{
    return name.ToLower().Replace(" ", "");
}

Open in new window

One final thing. I have used functions in "System.Security.Cryptography" to write above code and therefore you have to add that reference along with "System.Text" and "System.IO" in you project

-Kusala
Fascinating how your resulting key is different but it works! Now on to trying to figure out how it actually works. =)