Encoding and decoding in javascript

Base64 encoding and decoding in JavaScript

Base64 is a widely used binary-to-text encoding scheme that transforms binary data into an equivalent ASCII character set by translating it into a radix-64 representation. It is commonly used for encoding and transporting data over media incompatible with transferring binary data. Base64 makes sure that the binary data doesn’t change during transportation.

It is important to remember that Base64 is not an encryption or compression scheme. It only transforms the binary data into an ASCII character set that is extremely useful for transferring obfuscated strings over the network.

For instance, a simple example is sending an image or any other binary file to an email server that typically expects textual data. You first encode the binary file into a textual format, preferably ASCII.

In this article, you’ll learn how to encode and decode Base64 strings in JavaScript. There are two built-in functions in JavaScript for encoding and decoding raw binary data into Base64 strings.

The btoa() function (stands for binary-to-ASCII) is used to create a Base64 encoded ASCII string from the binary data. It accepts the binary string as an argument and returns a Base64 encoded ASCII string. The following example shows how you can use btoa() to Base64 encode a string in JavaScript:

const str = 'JavaScript is fun!!' // encode the string const encodedStr = btoa(str) // print encoded string console.log(encodedStr) // output: SmF2YVNjcmlwdCBpcyBmdW4hIQ== 

By default, the btoa() method works fine for binary data consisting of 8-bit bytes. If your input data contains any character with more than 8 bits, for instance, a Unicode character, the btoa() function will throw an exception. Here is an example:

const str = 'JavaScript is fun 🎉' // encode the string const encodedStr = btoa(str) // print encoded string console.log(encodedStr) 
Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range. 

To encode Unicode characters, you first need to escape the input string to an array of 8-bit bytes (like UTF-8) and then use btoa() to encode it to Base64, as shown in the following example:

function encodeUnicode(str)  // First we use encodeURIComponent to get percent-encoded UTF-8, // then we convert the percent encodings into raw bytes which // can be fed into btoa. return btoa( encodeURIComponent(str).replace(/%([0-9A-F])/g, function toSolidBytes(match, p1)  return String.fromCharCode('0x' + p1) >) ) > encodeUnicode('JavaScript is fun 🎉') // SmF2YVNjcmlwdCBpcyBmdW4g8J+OiQ== encodeUnicode('🔥💡') // 8J+UpfCfkqE= 

The atob() function (stands for ASCII-to-binary) decodes a string of data encoded using Base64 encoding back to normal text in JavaScript. Here is an example that shows how you can use atob() to decode a Base64 encoding string:

const encodedStr = 'SmF2YVNjcmlwdCBpcyBmdW4hIQ==' // decode the string const str = atob(encodedStr) // print decoded string console.log(str) // output: JavaScript is fun!! 

The atob() function works perfectly if the Base64 encoded input string only has 8-bit bytes. However, it fails to properly decode if the encoded input string includes 16-bit Unicode characters, as shown in the following example:

// Encode String: 'JavaScript is fun 🎉' const encodedStr = 'SmF2YVNjcmlwdCBpcyBmdW4g8J+OiQ==' // decode the string const str = atob(encodedStr) // print decoded string console.log(str) // output: JavaScript is fun ð 

As you can see above, the Unicode character is not properly decoded. To handle Unicode DOM strings, you have to convert the Base64 encoded bytes to percent-encoded strings and then decode the percent-encoded string using decodeURIComponent() like the following:

function decodeUnicode(str)  // Going backward: from byte-stream to percent-encoding, to original string. return decodeURIComponent( atob(str) .split('') .map(function (c)  return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2) >) .join('') ) > decodeUnicode('SmF2YVNjcmlwdCBpcyBmdW4g8J+OiQ==') // JavaScript is fun 🎉 decodeUnicode('8J+UpfCfkqE=') // 🔥💡 

That’s all folks for Base64 encoding and decoding in JavaScript. Base64 is a widely used encoding scheme for securely transmitting binary data as a stream of ASCII characters over the network. Of course, you can still choose to send binary data over the network. But it can be risky sometimes, as not all applications and network communication devices can handle raw binary data. On the other hand, the ASCII character set is quite simple to consume for most applications. For more information on Base64 encoding and decoding, read this MDN guide. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

TextDecoder и TextEncoder

Что если бинарные данные фактически являются строкой? Например, мы получили файл с текстовыми данными.

Встроенный объект TextDecoder позволяет декодировать данные из бинарного буфера в обычную строку.

Для этого прежде всего нам нужно создать сам декодер:

let decoder = new TextDecoder([label], [options]);
  • label – тип кодировки, utf-8 используется по умолчанию, но также поддерживаются big5 , windows-1251 и многие другие.
  • options – объект с дополнительными настройками:
    • fatal – boolean, если значение true , тогда генерируется ошибка для невалидных (не декодируемых) символов, в ином случае (по умолчанию) они заменяются символом \uFFFD .
    • ignoreBOM – boolean, если значение true , тогда игнорируется BOM (дополнительный признак, определяющий порядок следования байтов), что необходимо крайне редко.

    …и после использовать его метод decode:

    let str = decoder.decode([input], [options]);
    • input – бинарный буфер ( BufferSource ) для декодирования.
    • options – объект с дополнительными настройками:
      • stream – true для декодирования потока данных, при этом decoder вызывается вновь и вновь для каждого следующего фрагмента данных. В этом случае многобайтовый символ может иногда быть разделён и попасть в разные фрагменты данных. Это опция указывает TextDecoder запомнить символ, на котором остановился процесс, и декодировать его со следующим фрагментом.
      let uint8Array = new Uint8Array([72, 101, 108, 108, 111]); alert( new TextDecoder().decode(uint8Array) ); // Hello
      let uint8Array = new Uint8Array([228, 189, 160, 229, 165, 189]); alert( new TextDecoder().decode(uint8Array) ); // 你好

      Мы можем декодировать часть бинарного массива, создав подмассив:

      let uint8Array = new Uint8Array([0, 72, 101, 108, 108, 111, 0]); // Возьмём строку из середины массива // Также обратите внимание, что это создаёт только новое представление без копирования самого массива. // Изменения в содержимом созданного подмассива повлияют на исходный массив и наоборот. let binaryString = uint8Array.subarray(1, -1); alert( new TextDecoder().decode(binaryString) ); // Hello

      TextEncoder

      TextEncoder поступает наоборот – кодирует строку в бинарный массив.

      Имеет следующий синтаксис:

      Источник

      How to encode/decode strings in JavaScript?

      I need to pass a variable in an onclick function that I don’t want the user to be able to view the page source and just easily read. I want to encode the string and then decode it in the function that I pass the string to. I’ve done a Google search for this and can only find information on encoding/decoding URLs to safely pass them, but not strings in general. Does JavaScript have any built in encoding/decoding functions (hopefully that PHP has too, because I will also be using PHP to send the encoded string)?

      Is it necessary to expose the string in the JavaScript code in the first place? Can you not just keep things on server side?

      «I don’t want the user to be able to view the page source and easily read» — You mean encryption/decryption then. See simliar question: stackoverflow.com/questions/3609005/…

      Well I’m not sure how else I would use it without using a string in JavaScript. It is a music player button, and there are multiple buttons on the page. When the user clicks a specific button, it has to tell my JavaScript function the URL of the mp3 to play. I don’t want the user to see the URL so they can easily download the mp3. The site is startingtofeelit.com. Scroll your mouse over the pictures to see the «play» button

      @jas7457 If they can listen to your mp3, then they have already downloading the file to their computer.

      3 Answers 3

      What you are trying to do is not feasible. No matter what decryption logic you use, you will need to ship it over to the consumer’s computer in JavaScript, which means that any sufficiently smart script-kiddie with Firebug will be able to easily decode all of your secrets. Moreover, they will be able to modify the data on the client side, in their browser console, and trick your server.

      I encourage you to keep these kinds of secrets on the server side, perhaps in session state, or in something that’s associated with the currently logged in user. Do not send it to the client.

      He wants to encrypt the url of his mp3 file location — impossible to keep that on the serverside (and while you can keep it in plain form from the source code, you can’t keep it from the network panel) 🙂

      What you are trying to implement is DRM, which is not feasible to implement using browsers and JavaScript. You can of course always make it harder for a user to get to the sound file, but beware that you can easily scare away your users.

      What you can do is to generate a large random (say 8 to 16 bytes or so) on the server side, or hash a counter. Then you make the MP3 available only once for download using the given random value. Next time any user wants to download the file, he gets a new random. The randoms are sufficiently large for a user never to guess the next file. As said, you cannot disallow the first download of course, so anybody smart enough to play with the the browsers cache will easily break the scheme.

      You could also embed a flash player that receives and decodes the data stream so you can send the data in a form that is not easily decodable by non-experts. You could mix this with the randomized URL method.

      You can URL-encode the random value using hexadecimals, or by using base64 and then an URL-encode function.

      To get your URL off the javascript try using some ID instead. You will have to translate that ID serverside then to URL. You can use simple array such as:

      function getLink($songID) < $decodeArray=array( 1=>"www.mysite.com/myfirstsong.mp3", 2=>"www.othersite.net/othersong.mp3"); return $decodeArray[$songID]; > die(getLink($_GET['songID']));//send back the URL 

      or you can use database within that translating php code (above)

      There you have 2 choices how to do this «answering service» 1) replying to the XMLHttpRequest with the url (from your php script) and pasing the returned value from javascript to flash client-side (as in the code above) or 2) answer only some «OK» status message to Javascript and send the URL directly to the flash player — you would need to be able to code a little in Actionscript to be able to do this.

      The problem still is in the fact that you need to inform the client (or Flash) about the actual song location (the readable URL string where it can find that song) so it has to travel back to the client and can be intercepted using a sniffer(packet analyzer) net tool. and in case of the code above one can query that php script directly and read the answer on screen without the need of sniffing.

      To prevent that you would need to have the communication directly with Flash either through https (not sure whether it would work) or not send the url at all and instead stream the content of that song directly to your Flash application using socket connection between the Flash player clientside and your (home-made) php socket server.

      Источник

      Читайте также:  Curl php disable ssl check
Оцените статью