戻る

base64を使った文字列のエンコード・デコード
btoaとatob関数を使用します。(Unicode文字を扱う場合は、事前処理が必要です)

base64を使った文字列のエンコード


[変換前の文字列]
101匹のネコ

[変換後の文字列]


[変換前の文字列]
MTAx5Yy544Gu44ON44Kz

[変換後の文字列]

copy
const b1 = document.getElementById("btn1");
const b2 = document.getElementById("btn2");
b1.addEventListener("click", () => 
{
	const objIn = document.getElementById("encode");
	const objOut = document.getElementById("encode2");
	let data = objIn.innerText;
	data = base64Encode(data);
	objOut.innerText = data;
});
b2.addEventListener("click", () => 
{
	const objIn = document.getElementById("decode");
	const objOut = document.getElementById("decode2");
	let data = objIn.innerText;
	data = base64Decode(data);
	objOut.innerText = data;
});

function base64Encode(data) 
{
	//Unicode文字列をUint8Arrayに変換
	const utf8Encode = new TextEncoder();
	const uint8Array = utf8Encode.encode(data);
	
	//Uint8ArrayをLatin-1文字列に変換
	let latin1String = '';
	for (let i = 0; i < uint8Array.length; i++) 
	{
		latin1String += String.fromCharCode(uint8Array[i]);
	}

	//Latin-1文字列をbase64エンコード
	return btoa(latin1String);
}

function base64Decode(data) 
{
	try 
	{
		//base64文字列をLatin-1文字列にデコード
		const latin1String = atob(data);
		
		//Latin-1文字列をUint8Arrayに変換
		const uint8Array = new Uint8Array(latin1String.length);
		for (let i = 0; i < latin1String.length; i++) 
		{
			uint8Array[i] = latin1String.charCodeAt(i);
		}
	
		//Uint8ArrayをUTF-8文字列にデコード
		const utf8Decode = new TextDecoder();
		return utf8Decode.decode(uint8Array);
	
	} 
	catch (error) 
	{
		console.error("base64デコードエラー:", error);
		return null;
	}
}

JavaScriptで文字列をbase64にエンコードおよびデコードするには、btoa関数およびatob関数を使用します。
btoa関数バイナリデータをbase64エンコードされたASCII文字列に変換する関数です。
atob関数base64エンコードされたASCII文字列を元のバイナリデータにデコードする関数です。
※btoa関数はASCII文字のみを直接処理できるため、日本語などのUnicode文字を扱う場合は、事前に適切な処理が必要です。

const utf8Encode = new TextEncoder();
TextEncoder()
文字列をUTF-8でエンコードされたUint8Arrayに変換するオブジェクトです。
このUint8Arrayをbase64エンコーディングすることで、バイナリデータをテキスト形式に変換します。

base64エンコードしたデータは、元のデータよりもサイズが約33%増加します。
String.fromCharCode
UTF-16のコードユニットに対応する文字列に変換します。
String.fromCharCodeの引数は複数個可能ですが、このサンプルでは1個ずつ、変換しています。
配列に1文字ずつ変換した結果を変数に連結しています。
その結果をbtoaでbase64にエンコードしています。

Uint8Array
Uint8Arrayは、8ビット符号なし整数値の配列を表す型です。
TextDecoderクラスのdecode関数の引数には、base64でエンコードされたバイナリデータのUint8Arrayを渡すことでデコード変換をします。

const uint8Array = new Uint8Array(latin1String.length);
このサンプルでは、使用するエリア分だけ配列要素を準備しています。
uint8Array[i] = latin1String.charCodeAt(i);
atob関数でデコードした文字列を文字の長さを左から順に
1文字ずつcharCodeAt関数でUnicodeを数字に変換した結果を
Uint8Array配列の要素に格納しています。
const utf8Decode = new TextDecoder();
return utf8Decode.decode(uint8Array);
TextDecoderクラスのdecode関数の引数に変換したUint8Array配列を渡し、
デコードした結果を返しています。

[ポイント]
上記処理をしている理由は、
btoa関数とatob関数は、直接Unicode文字列を扱うことができないためです。
TextEncoderとTextDecoderを使用して、
Unicode文字列をUint8Arrayに変換し、
Latin-1文字列に変換することで、btoa() でエンコードできるようにする必要があります。
base64エンコードは、バイナリデータをテキスト形式で表現するための方法です。

Latin-1(ISO-8859-1)は、Unicodeの最初の256文字に対応する文字エンコーディングです。
Unicode文字列をLatin-1文字として解釈して、各文字を1バイトの値に変換するために使用しています。


戻る
back

Encoding and decoding strings using base64
Use the btoa and atob functions.(pre-process them if you are dealing with Unicode characters)

Encoding and decoding strings using base64


[String before conversion]
101 Cats

[String after conversion]


[String before conversion]
MTAxIENhdHM=

[String after conversion]

copy
const b1 = document.getElementById("btn1");
const b2 = document.getElementById("btn2");
b1.addEventListener("click", () => 
{
	const objIn = document.getElementById("encode");
	const objOut = document.getElementById("encode2");
	let data = objIn.innerText;
	data = base64Encode(data);
	objOut.innerText = data;
});
b2.addEventListener("click", () => 
{
	const objIn = document.getElementById("decode");
	const objOut = document.getElementById("decode2");
	let data = objIn.innerText;
	data = base64Decode(data);
	objOut.innerText = data;
});

function base64Encode(data) 
{
	//Convert Unicode String to Uint8Array
	const utf8Encode = new TextEncoder();
	const uint8Array = utf8Encode.encode(data);
	
	//Uint8ArrayをLatin-1 Convert to String
	let latin1String = '';
	for (let i = 0; i < uint8Array.length; i++) 
	{
		latin1String += String.fromCharCode(uint8Array[i]);
	}

	//Base64 encode a Latin-1 string
	return btoa(latin1String);
}

function base64Decode(data) 
{
	try 
	{
		//Decode a base64 string to a Latin-1 string
		const latin1String = atob(data);
		
		//Decode a base64 string to a Latin-1 string
		const uint8Array = new Uint8Array(latin1String.length);
		for (let i = 0; i < latin1String.length; i++) 
		{
			uint8Array[i] = latin1String.charCodeAt(i);
		}
	
		//Decode a Uint8Array into a UTF-8 string
		const utf8Decode = new TextDecoder();
		return utf8Decode.decode(uint8Array);
	
	} 
	catch (error) 
	{
		console.error("Base64 Decoding Error:", error);
		return null;
	}
}

To encode and decode strings to base64 in JavaScript, use the btoa and atob functions.
btoa functionThis function converts binary data into a Base64-encoded ASCII string.
atob functionThis function decodes a Base64-encoded ASCII string back to its original binary data.
*The btoa function can only directly process ASCII characters, so if you are dealing with Unicode characters such as Japanese, you need to do the appropriate processing in advance.

const utf8Encode = new TextEncoder();
TextEncoder()
This object converts a string into a Uint8Array encoded in UTF-8.
By base64 encoding this Uint8Array, binary data is converted into text format.

The size of base64 encoded data increases by about 33% compared to the original data.
String.fromCharCode
Converts into a string corresponding to a UTF-16 code unit.
String.fromCharCode can take multiple arguments, but in this sample, they are converted one by one.
The result of converting each character into an array is concatenated to a variable.
The result is encoded to base64 using btoa.

Uint8Array
Uint8Array is a type that represents an array of 8-bit unsigned integer values.
The decode conversion is performed by passing a Uint8Array of binary data encoded in base64 to the argument of the decode function of the TextDecoder class.

const uint8Array = new Uint8Array(latin1String.length);
In this sample, array elements are prepared for the area to be used.
uint8Array[i] = latin1String.charCodeAt(i);
The string decoded by the atob function is sorted by character length from left to right
The Unicode is converted to numbers one character at a time by the charCodeAt function
and the results are stored in the elements of the Uint8Array array.
const utf8Decode = new TextDecoder();
return utf8Decode.decode(uint8Array);
The converted Uint8Array array is passed as an argument to the decode function of the TextDecoder class
and the decoded result is returned.

[Points]
The reason for the above processing is that
btoa and atob functions cannot handle Unicode strings directly. 
You need to use TextEncoder and TextDecoder to convert the
Unicode string to a Uint8Array and then to a Latin-1 string so that it can be encoded with btoa(). 
Base64 encoding is a way to represent binary data in text form. 

Latin-1 (ISO-8859-1) is a character encoding that corresponds to the first 256 characters of Unicode.
It is used to interpret the Unicode string as a Latin-1 character and convert each character to a 1-byte value.


back



著作権情報
ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。
ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、
または公開したりすることはできません。
当方は、ホームペーよびアプリ利用したいかなる理由によっての障害等が発生しても、
その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について
一切の責任を負わないものとします。