0

I have a code in c#

public static string Encriptar(string _cadenaAencriptar)
{
    string result = string.Empty;
    byte[] encodedData = System.Text.Encoding.Unicode.GetBytes(_cadenaAencriptar);
    result = Convert.ToBase64String(encodedData );
    return result;
}

I want this code in javaScript. Helpme please.

Tom
  • 6,325
  • 4
  • 31
  • 55
Mario
  • 11
  • 3
  • This is *not* encryption... this is *encoding*. The variable name "encrypted" should be changed to reflect that. – JoelFan Apr 08 '20 at 23:16

1 Answers1

0

So you are taking a utf16 encoded string and converting the utf16 bytes to a Base64 encoded string.

The following JavaScript first converts the string to a array of utf16 bytes. Then converts the array to a Base64 encoded string.

_arrayBufferToBase64(strToUtf16Bytes(_cadenaAencriptar))

https://stackoverflow.com/a/9458996/361714

function _arrayBufferToBase64( buffer ) {
    var binary = '';
    var bytes = new Uint8Array( buffer );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode( bytes[ i ] );
    }
    return window.btoa( binary );
}

https://stackoverflow.com/a/51904484/361714

function strToUtf16Bytes(str) {
  const bytes = [];
  for (ii = 0; ii < str.length; ii++) {
    const code = str.charCodeAt(ii); // x00-xFFFF
    bytes.push(code & 255, code >> 8); // low, high
  }
  return bytes;
}

Output from javascript:

_arrayBufferToBase64(strToUtf16Bytes("hi"))
"aABpAA=="

Which matches the output from C#.

Tom
  • 6,325
  • 4
  • 31
  • 55