Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

c# - Simple string encryption in .NET and Javascript

I'm developing an ASP.NET MVC application in which I want to encrypt a short string on the server, using C#, and send it to the client-side.

Then on the client-side it will be decrypted through Javascript code.

Any thoughts on how to implement this?

Do you know of a simple encryption algorithm (doesn't have to be bullet-proof secure) that can be easily translated from C# to Javascript or vice-versa?

NOTE: I could do this entirely in C# and do the decryption through Ajax, but I'd prefer not to do it this way, as I want to reduce website traffic as much as possible.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It sounds like you want an obfuscation or encoding, not encryption. Base64 encoding should work well here. The result will look nothing like an email address, and the encoding process is fast.

In C#, you can use:

string emailAddress = "[email protected]";
string encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(emailAddress));

And you can use this JavaScript function to decode it:

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

   do {
      enc1 = keyStr.indexOf(encoded.charAt(i++));
      enc2 = keyStr.indexOf(encoded.charAt(i++));
      enc3 = keyStr.indexOf(encoded.charAt(i++));
      enc4 = keyStr.indexOf(encoded.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 < encoded.length);

   return output;
}

The C# application encodes the string [email protected] into YWJjQGV4YW1wbGUuY29t, and the JavaScript version will decode YWJjQGV4YW1wbGUuY29t back into [email protected].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...