.NET Basic Encryption

Discussion in 'Source Code & Tutorial Database' started by Hiyper, Jul 25, 2015 with 27 replies and 2,214 views.

  1. Hiyper

    Hiyper Enthusiast

    Messages:
    228
    Ratings:
    60
    In this tutorial, I will be teaching you the basics of encryption in VB. So lets jump right in.

    Design:
    1. Create a project.
    2. Add a textbox and name it TB_input
    3. Add another textbox and name it TB_output
    4. Add a button and name it encrypt
    5. add a button and name it decrypt
    Code:

    First we will begin our encryption function. but first include the following imports:

    Code:
    Imports System.Security.Cryptography
    Imports System.Text
    
    Now we need to set up a few variables.
    Code:
    Dim MD5 as new MD5CryptoServiceProvider
    Dim DES as new TripleDESCryptoServiceProvider
    
    Now we need to make our MD5 hash providing function. This will hash our "key".
    Code:
    Function MD5Hash(key as String) as Byte()
    Return MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key)
    End Function
    
    And our encrypt function.

    Code:
    Function Encrypt(input as String, key as String) as String
    DES.Key = MD5Hash(key) ' Sets the encryption key as a md5 hash
    DES.Mode = CipherMode.ECB ' uses electronic book cipher mode
    
    Dim buffer as Byte() = ASCIIEncoding.ASCII.GetBytes(input) ' Turn our string into bytes
    Return System.Convert.ToBase64String(DES.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length)) ' encrypts our bytes, then returns the string
    End Function
    
    That is all! You can now double click your encrypt button and add this code.
    Code:
    Private Sub encrypt_Click(sender as Object, e as EventArgs) Handles encrypt.Click
    output.Text = Encrypt(input.Text, "thisisakey") '"thisisakey can be anything you want"
    End Sub
    
    Now it will encrypt our text! You can test it out so far. Now is time for decryption.

    Code:
    'we can basically use order of operations to reverse this
    Function Decrypt(input as String, key as String) as String
    DES.Key = MD5Hash(key)
    DES.Mode = CipherMode.ECB
    Dim buffer as Byte() = System.Convert.FromBase64String(input)
    Return ASCIIEncoding.ASCII.GetString(DES.CreateDecryptor().TransformFinalBlock(buffer, 0, buffer.length))
    End Function
    
    And its as simple as that! Now all we have to do is implement that function. Double click our decrypt button

    Code:
    Private Sub decrypt_Click(sender as Object, e as EventArgs) Handles decrypt.Click
    input.Text = Decrypt(output.Text, "thisisakey") '"thisisakey can be anything you want"
    End Sub
    
    Keep in mind that this a a very simple encryption method, and is VERY unsafe. It should never be used in a professional setting, and private key method is also risky. (Consider using AES instead of DES for more safety and SHA-256 instead of MD5)

    Explanations:

    MD5Hash Function:
    A hash is a algorithm that can ONLY be encrypted, not decrypted.

    Take this string, "Hashing". Pretend our string is going to be put through a car wash. This car wash could be a lot of different washes of different speeds and how good it cleans. The car wash is our type of hash. Ours is MD5. Once a string is hashed, it can never be un-hashed. So we take our "key" and hash it.

    Hashing - > MD5 "Car Wash" -> befd1ea261d11ae5ba4f3f0363313c52

    Now our string "Hashing" has been turned into a long string of letters and numbers. This is undo-able (Well, it is, but that is a whole tutorial on itself).

    Encrypt Function:
    First thing we do is input the hashed key as our encryption key. Now our encryption method "DES" is one of many different methods. Encryption is just like hashing, but it can be undone, but only with our special key (Not really, but again a whole other tutorial for a different forum). We then set what method it is going to use (this is very complicated, just know it is how it does the encryption). Then we change our string into pure bytes. Those pure bytes are plugged into the DES encryptor, which gives us encrypted bytes, Which we convert back into a string.

    Decrypt Function:
    Same as encrypt, just in reverse.

    Hope you enjoyed! (I typed this all by hand so let me know of any errors)
     
    • Like Like x 1
    Last edited: Jul 25, 2015
  2. GoldBl4d3

    GoldBl4d3 VIP VIP Retired

    Messages:
    3,774
    Ratings:
    1,340
    This is nice, but it doesn't teach anything except how to copy the code and paste it. How does the different encryption methods work? Show charts and examples of how the various methods encrypt the data.
     
    • Like Like x 1
  3. Cakes

    Cakes Administrator Administrator

    Messages:
    20,667
    Ratings:
    17,726
    Should also mention about more than just MD5, as .NET has support for AES, SHA, XOR, etc and even custom encryption.
     
    • Like Like x 1
  4. OP
    Hiyper

    Hiyper Enthusiast

    Messages:
    228
    Ratings:
    60
    This is just the basics. No need to confuse anyone.
     
  5. Cakes

    Cakes Administrator Administrator

    Messages:
    20,667
    Ratings:
    17,726
    By mention, I was referring to going into detail. Not just throwing the names into context, lol.
     
  6. OP
    Hiyper

    Hiyper Enthusiast

    Messages:
    228
    Ratings:
    60
    I edited the post ,
    ninja'd.
     
  7. OP
    Hiyper

    Hiyper Enthusiast

    Messages:
    228
    Ratings:
    60
    Added
     
  8. GoldBl4d3

    GoldBl4d3 VIP VIP Retired

    Messages:
    3,774
    Ratings:
    1,340
    You explain the process of what you do in code. But what about the back end. What is the actual process of turning a string literal in to an encrypted string. What are the different uses of each encryption method? This tutorial is great, but you should explain things out. Then it will be even better.
     
  9. OP
    Hiyper

    Hiyper Enthusiast

    Messages:
    228
    Ratings:
    60
    So the actual algorithms and math?
     
  10. GoldBl4d3

    GoldBl4d3 VIP VIP Retired

    Messages:
    3,774
    Ratings:
    1,340
    Sure, I was talking more generally. In college they don't just teach you have to write a line of code. They teach you what that line means, how does it work even at the core levels (some times).

    Teach people ten lines of code is pointless as a google search would do better. Teach people the details, that's what really matters.
     
    • Like Like x 2
  11. OP
    Hiyper

    Hiyper Enthusiast

    Messages:
    228
    Ratings:
    60
    This was not geared as a beginner to coding tutorial, but I see where you are coming from. Thanks for the advice!
     
  12. GoldBl4d3

    GoldBl4d3 VIP VIP Retired

    Messages:
    3,774
    Ratings:
    1,340
    Yea I know man, but the basics should be how it all works, then the code. I do appreciate the tutorial though, you should make an advanced one.
     
    • Like Like x 1
  13. MatthewH

    MatthewH Member

    Messages:
    1,612
    Ratings:
    613
    For one, I would never put this in my code.
    I would rather create an extension that I would compile down into a library and secure that so that prying eyes, when they see the code...all it would be is..
    MyLibrary.Encrypt(string)
    MyLibrary.Decrypt(string)
    This way, you can use it for multiple projects, and those prying eyes wouldn't be able to grab your encryption method and be able to reverse it in less then 20 minutes like I did with Hiyper Chat (20 minutes include sniffing, setting up the other computer and VM, and so on).
    Speaking of that, this is a perfect example for this.
    Hiyper Chat.
    Simple, it had a specified port. I had 3 Windows OS up (two computers, one VM).
    Sniffed the network.
    Computer 1 [C1] & VM
    C1 -> [email protected] [data: Hashed string]
    VM -> [email protected] [data: Hashed response string]
    Basically, got the port. Grabbed the IPs, grabbed all the data.
    Used the key "jdf9j3u0t9 0999 sdmf3m0119a99" and reversed the encryption and was able to in one click of a button get the messages that C1 sent to VM and vice-versa.
    This an example of why keeping it in the code itself is a bad habbit to get into.


    Now lets take a second for me to say that I've never seen VB used in the industry. Example? Okay, I was talking to a software development company about an internship and out of pure curiousity I asked him if they ever used VB. He literally laughed and said no because it's the most ridiculous language ever created and has no practical use in the industry; and is far from secure. Which is why college courses are switching to other languages such as Java.
    Not bashing your code, I'm just saying that you shouldn't spend your time learning it; and I will say that to anyone.


    GoldBl4d3 is talking about breaking down the interface and methods. Explaining HOW they work. Now what your code does, although that's also needed.
    Ugh, here.
    Encoding.*.GetBytes (string s)
    This method takes all characters in the string (s) and encodes them into a sequence of bytes (byte array)​
    Encoding.*.GetString (byte[] arr)
    This method is the reverse of GetBytes(), it just decodes all the bytes in the byte array (arr) into a string.​

    CipherMode.ECB
    Essentially the Electronic Codebook (ECB) mode encrypts each data block individually.​

    Convert.ToBase64String(byte[] arr)
    This converts a byte array (arr) to a string representation of the array encoded with base-64 digits.​

    Convert.FromBase64String(string s)
    This method converts a string (s) to a byte array.​

    MD5CryptoServiceProvider
    This library contains a lot of MD5 computing functions, such as hashing a file or a byte array. Most of which are inherited from the HashAlgorithm class. MD5, in case you didn't know, (in simple terms) is a hash function that returns a 16-byte (or 128-bit) hash value.
    MD5CryptoServiceProvider.ComputeHash (byte[])
    This is the current method being used. To use it, you must get the bytes of the current string. Using something such as the Encoding.*.GetBytes function.
    However, this returns a byte array. So to convert it to a readable (by the user) you have turn it into a string.​

    TripleDESCryptoServiceProvider
    This is yet another service provider that allows you to have access to functions that use the TripleDES algorithm.
    The 3DES is a symmetric-key block cipher which applies the DES(Data Encryption Standard) cipher algorithm 3 times to each data block.
    A symmetric-key algorithm use the same "key" for encryption and decryption.
    TripleDESCryptoServiceProvider.Key
    This is the key used for decrypting and encrypting the data.​
    TripleDESCryptoServiceProvider.Mode
    This is just setting the CipherMode for the 3DES encryption.​
    TripleDESCryptoServiceProvider.CreateDecryptor(byte[] key)
    This creates a decryptor object with the specified key. You do not have to specify the key if you already specified it earlier in the function or class.​
    TripleDESCryptoServiceProvider.CreateDecryptor().TransformFinalBlock(byte[] buffer, int offset, int count)
    This function requires 3 arguements. The byte array which will be used to compute the transform. The offset will tell the computer how far into the byte array to start computing, and the count is how far into the byte array to compute.
    For example if you have phony data in the byte array to keep "wandering eyes" from being able to convert the byte array without knowing the offset and count.​
    TripleDESCryptoServiceProvider.CreateEncryptor(byte[] key)
    This creates a encryptor object with the specified key. You do not have to specify the key if you already specified it earlier in the function or class.​
    TripleDESCryptoServiceProvider.CreateEncryptor().TransformFinalBlock(byte[] buffer, int offset, int count)
    This function requires 3 arguements. The byte array which will be used to compute the transform. The offset will tell the computer how far into the byte array to start computing, and the count is how far into the byte array to compute.
    For example if you have phony data in the byte array to keep "wandering eyes" from being able to convert the byte array without knowing the offset and count.​
     
    • Like Like x 2
  14. OP
    Hiyper

    Hiyper Enthusiast

    Messages:
    228
    Ratings:
    60
    I was aware of this, using symmetrical encryption and storing the private key as as string in a .NET application. Probably the worst idea ever as someone with .NET Peek could get the key in less than a minute. I am actually working on a complete recode, if you read that post of the thread. I am focusing security and reliability.
     
  15. OP
    Hiyper

    Hiyper Enthusiast

    Messages:
    228
    Ratings:
    60
    Also, how would the sniffer be able to get the key used for encryption if they are not aware Hiyper Chat is encrypting and decrypting data?
     
  16. Z61

    Z61 Some times our saints are sinners Retired

    Messages:
    5,514
    Ratings:
    3,058
    It should be rather obvious when observing packets.
     
  17. MatthewH

    MatthewH Member

    Messages:
    1,612
    Ratings:
    613
    The key is not. If he read my little chart thing, whatever it is. He would of realized that I only got the hashed message from the packets, and also...that's the only data that's being sent.

    To really "secure" it, both parties would need a key; but let's not stop there. Oh and a public key.
    Let's add custom ports.
    Oh, let's take it a step farther. Phony bytes.

    Explanation?
    Okay.

    Custom Ports
    Doing this will allow you to communicate with another party on that port. Send a quick "hello" message and wait for a response. Oh look, we found our friend on that port.
    How does this protect? Well obviously it's still being sent over user datagram protocol. Which can still be found and it's obvious when you have multiple outgoing and incoming packets on one port, that something is going on...but using a custom port will help.

    Phony Bytes
    Using offset and count for the transform final block interface we can specify where in the byte array to start transforming and where to stop.
    Throw in some phony bytes and throw off the sniffer. Unless they have the offset and count, they can't do crap...well...unless they start looping the decryption with different offsets and counts until it comes out...

    Custom Keys
    Private and public. Combine this with custom ports.
    Each party...ugh. Let me explain like this.

    Computer 1 [C1] and Computer 2 [C2]
    C1 - Hello Message / Public Key -> C2
    C2 Logic
    Oh look, we got a message. Let me check my key records. Well look there, it matches my current public key. Time to send a success response. ​
    C2 - Response Message / Public Key -> C1

    Then the messages would be sent with the public key which could help stop people from hijacking the IP address on a local network (which can be done) and talking to you in place of the other person.

    And use different encryption methods with the keys...

    Obviously the private key would be used to decrypt the messages after they're received and so on.
     
  18. OP
    Hiyper

    Hiyper Enthusiast

    Messages:
    228
    Ratings:
    60
    I had already stated I am working on asymmetrical encryption.

    Joe Sam

    Joe -> Public Key (PK) Sam

    Joe <- Private Key (PK Encrypted) Sam

    Joe Decrypts message with private key

    Joe <They use key sam generated> Sam
     
  19. Xeren

    Xeren ♦♦♦ God Complex ♦♦♦

    Messages:
    5,678
    Ratings:
    1,890
    I believe I've stated this in our conversation, but in order for the best security, you're going to have to use a "middle-man" server that gives both parties the respective keys, or else you'd be sending the keys through the UDP connection, which completely defeats the purpose of asymmetric encryption and leaves you as vulnerable as the previous security measures.
     
  20. OP
    Hiyper

    Hiyper Enthusiast

    Messages:
    228
    Ratings:
    60
    The only keys sent over UDP would be the public key, and those are public for a reason.
     

Share This Page