Category: Snippets

Simple encryption and decryption of a string in c#

20 August, 2010 (12:32) | Cryptography, Security, Snippets, Programming, C#, Code

Here are some routines which are designed for simple use of Rijndael in C#. I’ve combined a test function in the class for simplicity of showing it’s use.

private static byte[] salt = Encoding.ASCII.GetBytes(”somerandomstuff”);

public static string Encrypt(string plainText, string […]

Simple speach example in C#.

12 May, 2008 (15:57) | .Net, Snippets

This uses reflection to avoid the clerical task of adding a project reference:

System.Type t = System.Type.GetTypeFromProgID(”SAPI.SpVoice”);
object o = System.Activator.CreateInstance(t);
t.InvokeMember(”Speak”, System.Reflection.BindingFlags.InvokeMethod, null, o, new object[] { “test”, 0 });

If you don’t mind adding a reference, then the whole thing can be done in one line:

new SpeechLib.SpVoice().Speak(”This is a test”, SpeechLib.SpeechVoiceSpeakFlags.SVSFDefault);

Finding “dead time” in a database of start and end times.

22 May, 2007 (15:28) | Snippets, SQL

The following snippet will find “dead time” (e.g. time where no events are scheduled) in a database:
1 select distinct dateadd(s,-1,starttime) as deadtime,"start" from sometable t where
2 0=(select count(*) from sometable u where u.starttime < t.deadtime and u.endtime > t.deadtime)
3 union all
[…]

MD5 in a few lines of Java

12 March, 2007 (10:58) | Cryptography, Java, Security, Snippets

1 import java.security.*;
2 import java.math.*;
3
4 public class MD5 {
5 public static void main(String args[]) throws Exception{
6 String s="This is a test";
[…]

Get the Unix Epoch time in one line of C#

3 January, 2007 (11:52) | .Net, Snippets

int epoch = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;

An alternate (possibly faster) method might be:
long time = (DateTime.UtcNow.Ticks - 621355968000000000) / 10000000;
Although the second method does conform to the Unmaintainable Code standard, I’d recommend sticking with the first method unless you really need those extra nanoseconds.

MD5 in one line of C# code.

2 October, 2006 (23:20) | Cryptography, .Net, Security, Snippets

Considering the popularity of using MD5 to hash passwords in a database, I’m litterally baffled as to why Microsoft didn’t include a System.Security.Cryptography.MD5() function. This isn’t quite as nice as that would be, but it gets the job done:
string hash = Convert.ToBase64String(new System.Security.Cryptography.MD5CryptoServiceProvider().
ComputeHash(System.Text.Encoding.Default.GetBytes(SomeString)));

Pretty much every other example I’ve seen are at […]