Life: The Soundtrack

Wednesday, March 23, 2005

Encryption

Track/Stream: Brandston - King of Pain

I just threw a spiffy chunk of code in. There's a task which needs to be run from a command line (so we can do it manually or via a cron job). It uses the same transport mechanism as the rest of my communications, so to prevent a wayward developer from allowing unauthorized clients from running the job, it requires a username and password. However, the LAN guys don't want to put a password in plain text.

So in about 5 lines of code I implemented the ability to encrypt the password using RSA. The encrypted password may be fed in in place of the plain-text one. It auto-detects between encrypted and plain-text password and decrypts if necessary. The password is then sent to the server who authenticates it. As a bonus, if you tell it to encrypt, but don't give it text to encrypt, it dumps the encryption key.

      using System.Text;
      using System.Security.Cryptography;
 
      private const string ENCRYPTION_KEYS = 
        "<RSAKeyValue><Modulus>...</Modulus>" +
        "<Exponent>...</Exponent><P>...</P>" + 
        "<Q>...</Q><DP>...</DP><DQ>...</DQ>" +
        "<InverseQ>...</InverseQ><D>...</D></RSAKeyValue>";
 
      // Create and initializes our encryption/decryption
      RSACryptoServiceProvider Provider = 
        new RSACryptoServiceProvider();
      Provider.FromXmlString(ENCRYPTION_KEYS);
 
      if (Encrypting && (Password == null))
        // Dump Encryption Key
        System.Console.WriteLine(Provider.ToXmlString(false));
      else if (Encrypting)
        // Dump Encrypted Password
        System.Console.WriteLine(Convert.ToBase64String(
          Provider.Encrypt(
            Encoding.ASCII.GetBytes(args[1]), true)));
      else
        // Decrypt Password and Replace.  
        // If there's an error, user supplied plain text already
        try { Password = Encoding.ASCII.GetString(
          Provider.Decrypt(
            Convert.FromBase64String(args[2]), true)); }
        catch { }

0 Comments:

Post a Comment