0

I'm trying to code a C# crypt function that I can decrypt with JavaScript, is there a possible way to do that?

3

1 Answer 1

0

For applications that require higher security I usually encode and decode using C#, and use $.ajax in JS, but there is an easy way using JS to decode a pre-encrypted string .

You can use Base64String...

C# :

string encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(str));

JS :

function decode(str) {
  var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  var output = "";
  var chr1, chr2, chr3;
  var enc1, enc2, enc3, enc4;
  var i = 0;

  do {
     enc1 = keyStr.indexOf(str.charAt(i++));
     enc2 = keyStr.indexOf(str.charAt(i++));
     enc3 = keyStr.indexOf(str.charAt(i++));
     enc4 = keyStr.indexOf(str.charAt(i++));

     chr1 = (enc1 << 2) | (enc2 >> 4);
     chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
     chr3 = ((enc3 & 3) << 6) | enc4;

     output = output + String.fromCharCode(chr1);

     if (enc3 != 64) {
        output = output + String.fromCharCode(chr2);
     }
     if (enc4 != 64) {
        output = output + String.fromCharCode(chr3);
     }
   } while (i < str.length);

  return output;
}
Sign up to request clarification or add additional context in comments.

3 Comments

I know some may not agree with me, but I believe that having a client side script inherently conflict with aes encryption standards. This is one of the reasons I only encrypt / decrypt server side, and use json calls to communicate. That way I can also use sessions, cookies, etc... and make sure the encryption is very strong, rather than using C#/ JS encryption.
That's encoding, not encryption.
had you bothered reading my comments, and notes you'd notice that I call it encoding and not encrypting. in my comment i was making a case for encrypting, and made clear that you cannot do it on the client side, and when I do need something encrypted I do it exclusively on the server side !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.