Click here to Skip to main content
15,896,489 members
Articles / Programming Languages / C#

Send and receive messages in a LAN with broadcasting

Rate me:
Please Sign up or sign in to vote.
5.00/5 (17 votes)
6 Mar 2012MIT9 min read 95.5K   11.7K   73  
Lightweight .Net library for UDP LAN broadcasting.
using System;
using System.Security.Cryptography;
using System.Text;

namespace Orekaria.Lib.P2P
{
    /// <summary>
    ///   Code adapted from http://www.dijksterhuis.org/encrypting-decrypting-string/
    ///   You should replace it with your favourite one
    /// </summary>
    internal class EncryptHelper
    {
        private static readonly UTF8Encoding Encoder = new UTF8Encoding();

        public static string EncryptString(string message, string passphrase)
        {
            var hashProvider = new MD5CryptoServiceProvider();
            var tdesKey = hashProvider.ComputeHash(Encoder.GetBytes(passphrase));
            var tdesAlgorithm = new TripleDESCryptoServiceProvider {Key = tdesKey, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7};

            var dataToEncrypt = Encoder.GetBytes(message);
            var encryptor = tdesAlgorithm.CreateEncryptor();
            var results = encryptor.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length);
            tdesAlgorithm.Clear();
            hashProvider.Clear();
            return Convert.ToBase64String(results);
        }

        public static string DecryptString(string message, string passphrase)
        {
            var hashProvider = new MD5CryptoServiceProvider();
            var tdesKey = hashProvider.ComputeHash(Encoder.GetBytes(passphrase));
            var tdesAlgorithm = new TripleDESCryptoServiceProvider {Key = tdesKey, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7};

            var dataToDecrypt = Convert.FromBase64String(message);
            var decryptor = tdesAlgorithm.CreateDecryptor();
            var results = decryptor.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length);
            tdesAlgorithm.Clear();
            hashProvider.Clear();
            return Encoder.GetString(results);
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer (Senior)
Spain Spain
Hi, I am a Senior Generalist SDE and I have 25+ years of software development experience. My eyes, hands and brain have traveled from Spectrum Basic/assembler all the way to C++, Java and C#. In recent years I have been gluing electronics and software.

I have some Microsoft certifications along with others that I have forgotten.

http://orekaria.com

Comments and Discussions