How can I encrypt a string in JavaScript and decrypt that string in C#

QMKevin picture QMKevin · Jul 26, 2011 · Viewed 35.9k times · Source

I've seen this question asked before, though in these cases the poster wanted to encrypt something (usually a url) on a public facing website, and the responses were mostly "don't!". In my case, however, the JavaScript will be stored within a non-public internal system, so I think I have more leeway. One example of a similar question is: How to encrypt url in javascript and decrypt in c# - and the answers don't actually answer the question.

My 'JavaScript' is actually 'SuiteScript', which is defined as "SuiteScript is a JavaScript-based API that gives developers the ability to extend NetSuite", where NetSuite is a hosted CRM package, so any coding used to encrypt my string would be hidden to everyone, except for employees of my company (so considered safely hidden).

What I want to do is:

  1. generate a querystring (e.g. userid=guidValue&firstName=stringValue&company=stringValue&...),
  2. encrypt that using a secure method (such as AES256, RSA, whatever someone can suggest that's secure),
  3. call a webpage on my C# based website passing this string in the URL (e.g. mysite.com/mypage.aspx?encStr=encryptedString)
  4. have that C# page decrypt it, separate the name/value pairs and process them.

I've googled around and search stackoverflow, but not found any articles or answers that provide clear instructions of an encryption method that can be used by both technologies. Does anyone have such instructions?

Answer

Julien Roncaglia picture Julien Roncaglia · Jul 26, 2011

Symmetrical

The simplest way is to use a library as the Stanford Javascript Crypto Library that implement a standard (AES in this case) and to use the same cipher in C# (via AesManaged or AesCryptoServiceProvider).

You'll get a symmetrical cipher but there nearly no more than one parameter (the key) to set for both libs to work.

Asymmetrical

You could also use an asymmetrical (Public-Key) cipher instead. An attacker getting it's hand on the javascript code would be able to send crafted requests to your server but won't be able to intercept other requests.

There is an implementation of RSA in javascript and the RSACryptoServiceProvider class provide the support in .Net

A full example is available in Code project including a path to the RSA in javascript lib to support padding (mandatory when using the .Net implementation)

Note

Both of theses solutions by themselves are vulnerable to replay (an attacker intercepting a string and sending it back later -- potentially multiple times -- to the server)