Consistent hashing and encryption between Lift and .NET

Its quite often that I need to pass tokens between Scala (Java also) and .NET - this instantly provides a whole raft of issues because of how the algorithms are built under the hood in the respective platforms. This short post details how you can generate consistent base64 hashes over both platforms (this can be helpful for security purposes etc)

The Scala way:

  val input = "sample" 
  val encoding = "UTF-8" 

  base64Encode(
    hexDigest(
      input.getBytes(encoding)
    ).getBytes(encoding)
  )

The .NET way

  using System.Security.Cryptography;

  string input = "sample";

  SHA1CryptoServiceProvider shaHasher = 
       new SHA1CryptoServiceProvider();
  byte[] data = shaHasher.ComputeHash(
    Encoding.UTF8.GetBytes(input)
  );

  StringBuilder sBuilder = new StringBuilder();
  for (int i = 0; i < data.Length; i++){
    sBuilder.Append(data[i].ToString("x2"));
  }

  string hash = sBuilder.ToString();

  Convert.ToBase64String(
    Encoding.UTF8.GetBytes(hash)
  );

UPDATE After I posted this code originally, it was pointed out that it would be good / helpful to show encryption as well as hashing; so here goes:

The Scala way:

  val key: Array[Byte] = "qwehfjgtufkgurifghfkdjfg".getBytes("UTF-8")
  tripleDESEncrypt("sample", key)

The .NET way:

  using System.Security.Cryptography;

  string key = "qwehfjgtufkgurifghfkdjfg";
  string toEnc = "sample";

  TripleDESCryptoServiceProvider DES = 
       new TripleDESCryptoServiceProvider();

  byte[] bytKey = Encoding.UTF8.GetBytes(key);

  DES.Mode = CipherMode.ECB;
  DES.Key = bytKey;
  DES.Padding = PaddingMode.PKCS7;

  ICryptoTransform DESEncrypt = DES.CreateEncryptor();

  byte[] buffer = Encoding.UTF8.GetBytes(toEnc);

  string base64string = Convert.ToBase64String(
    DESEncrypt.TransformFinalBlock(buffer, 0, buffer.Length)
  );

  Response.Write(base64string);

Maybe this will help someone avoid the pain I have endured with this! lol.

comments powered by Disqus