Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 203
  • Last Modified:

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

0
donniedarko801
Asked:
donniedarko801
  • 3
  • 2
1 Solution
 
donniedarko801Author Commented:
Yeah... I don't think so eh.
0
 
Kusala WijayasenaSoftware EngineerCommented:
Don't worry we can help you :)

Hmmm, when it comes to code conversion (specially with custom libraries), its not straightforward. So definitely you have to put extra effort on this

OK, I have written conversion code for above program in C#. Its just initial scratch and open to improvements

-Kusala
public byte[] GenerateKeyfile(string name, string ccn, string outPath)
{
    byte[] nameBytes = Encoding.UTF8.GetBytes(NormalizeName(name) + '\x00');
    byte[] ccnBytes = Encoding.ASCII.GetBytes(ccn + '\x00');

    SHA1 sha1 = new SHA1CryptoServiceProvider();

    byte[] nameSHATemp = sha1.ComputeHash(nameBytes);
    byte[] nameSHA = new byte[16];
    
    int i;
    
    for (i = 0; i < 16; i++)
    {
        nameSHA[i] = nameSHATemp[i];
    }

    byte[] ccnSHATemp = sha1.ComputeHash(ccnBytes);
    byte[] ccnSHA = new byte[16];
    for (i = 0; i < 16; i++)
    {
        ccnSHA[i] = ccnSHATemp[i];
    }

    byte[] nameAndCcnBytes = new byte[nameBytes.Length + ccnBytes.Length];
    for (i = 0; i < nameBytes.Length; i++)
    {
        nameAndCcnBytes[i] = nameBytes[i];
    }
    for (i = nameBytes.Length; i < (nameBytes.Length + ccnBytes.Length); i++)
    {
        nameAndCcnBytes[i] = ccnBytes[i - nameBytes.Length];
    }

    byte[] bothSHA = sha1.ComputeHash(nameAndCcnBytes);
    byte[] bothSHABytes = new byte[bothSHA.Length + 0x0c];
    
    for (i = 0; i < bothSHA.Length; i++)
    {
        bothSHABytes[i] = bothSHA[i];
    }
    for (i = bothSHA.Length; i < (bothSHA.Length + 0x0c); i++)
    {
        bothSHABytes[i] = BitConverter.GetBytes('\x0c')[0];
    }

    byte[] crypt = AESEncrypt(CipherMode.CBC, nameSHA, bothSHABytes, ccnSHA);
    byte[] userKey = sha1.ComputeHash(crypt);

    using (FileStream fs = new FileStream(outPath, FileMode.Create, FileAccess.Write))
    {
        using (BinaryWriter bw = new BinaryWriter(fs))
        {
            bw.Write(Convert.ToBase64String(userKey));
        }
    }

    return userKey;
}

public byte[] AESEncrypt(CipherMode cipherMode, byte[] initVectorBytes, byte[] plainTextBytes, byte[] keyBytes)
{
    byte[] encryptResult = new byte[32];
    
    RijndaelManaged symmetricKey = new RijndaelManaged();
    symmetricKey.Mode = cipherMode;

    ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);

    using (MemoryStream memoryStream = new MemoryStream())
    {
        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
        {
            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
            cryptoStream.FlushFinalBlock();
        }

        byte[] cipherTextBytes = memoryStream.ToArray();

        for (int i = 0; i < 32; i++)
        {
            encryptResult[i] = cipherTextBytes[i];
        }
    }

    return encryptResult;
}

Open in new window

0
 
Kusala WijayasenaSoftware EngineerCommented:
Forgot to put  "NormalizeName" method :)

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

Open in new window

0
 
Kusala WijayasenaSoftware EngineerCommented:
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
0
 
donniedarko801Author Commented:
Fascinating how your resulting key is different but it works! Now on to trying to figure out how it actually works. =)
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now