programing

Node.js에서 Base64 인코딩을 수행하려면 어떻게 해야 합니까?

closeapi 2023. 6. 30. 22:23
반응형

Node.js에서 Base64 인코딩을 수행하려면 어떻게 해야 합니까?

Node.js에는 Base64 인코딩이 내장되어 있습니까?

제가 이것을 묻는 이유는final()부터crypto16진수, 2진수 또는 ASCII 데이터만 출력할 수 있습니다.예:

var cipher = crypto.createCipheriv('des-ede3-cbc', encryption_key, iv);
var ciph = cipher.update(plaintext, 'utf8', 'hex');
ciph += cipher.final('hex');

var decipher = crypto.createDecipheriv('des-ede3-cbc', encryption_key, iv);
var txt = decipher.update(ciph, 'hex', 'utf8');
txt += decipher.final('utf8');

문서에 따르면,update()Base64 인코딩 데이터를 출력할 수 있습니다.하지만,final()Base64를 지원하지 않습니다.제가 해봤는데 깨질 거예요.

이 작업을 수행할 경우:

var ciph = cipher.update(plaintext, 'utf8', 'base64');
    ciph += cipher.final('hex');

그렇다면 암호 해독을 위해 무엇을 사용해야 합니까?16진수 또는 Base64?

그래서 암호화된 16진수 출력을 Base64로 인코딩하는 기능을 찾고 있습니다.

버퍼는 문자열 또는 데이터 조각을 가져오고 결과의 Base64 인코딩을 수행하는 데 사용할 수 있습니다.예:

> console.log(Buffer.from("Hello World").toString('base64'));
SGVsbG8gV29ybGQ=
> console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'))
Hello World

버퍼는 글로벌 개체이므로 필요하지 않습니다.문자열로 작성된 버퍼는 선택적 인코딩 매개 변수를 사용하여 문자열이 어떤 인코딩에 있는지 지정할 수 있습니다.사용 가능한toString그리고.Buffer생성자 인코딩은 다음과 같습니다.

'ascii' - 7비트 ASCII 데이터에만 해당됩니다.이 인코딩 방법은 매우 빠르며 설정되면 높은 비트를 제거합니다.

'utf8' - 멀티바이트 인코딩 유니코드 문자.많은 웹 페이지 및 기타 문서 형식은 UTF-8을 사용합니다.

'ucs2' - 2바이트로 인코딩된 유니코드 문자입니다.BMP(기본 다국어 평면, U+0000 - U+FFFF)만 인코딩할 수 있습니다.

'base64' - Base64 문자열 인코딩.

'binary' - 각 문자의 처음 8비트만 사용하여 원시 이진 데이터를 문자열로 인코딩하는 방법입니다.이 인코딩 방법은 더 이상 사용되지 않으며 가능한 경우 버퍼 개체를 위해 피해야 합니다.이 인코딩은 향후 버전의 노드에서 제거될 예정입니다.

이전에 포함된 수락된 답변 new Buffer()이는 6보다 큰 Node.js 버전에서 보안 문제로 간주됩니다(이 사용 사례에서는 입력을 항상 문자열로 강제할 수 있습니다).

Buffer생성자는 문서에 따라 더 이상 사용되지 않습니다.

코드 스니펫은 다음과 같아야 합니다.

console.log(Buffer.from("Hello World").toString('base64'));
console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'));

이 답변이 작성된 후 업데이트되었으며 이제 이 답변과 일치합니다.

crypto이제 Base64(참조)를 지원합니다.

cipher.final('base64')

따라서 다음과 같은 작업을 수행할 수 있습니다.

var cipher = crypto.createCipheriv('des-ede3-cbc', encryption_key, iv);
var ciph = cipher.update(plaintext, 'utf8', 'base64');
ciph += cipher.final('base64');

var decipher = crypto.createDecipheriv('des-ede3-cbc', encryption_key, iv);
var txt = decipher.update(ciph, 'base64', 'utf8');
txt += decipher.final('utf8');

버퍼는 문자열 또는 데이터 조각을 가져오고 결과의 Base64 인코딩을 수행하는 데 사용할 수 있습니다.예:

다음과 같이 npm을 통해 버퍼를 설치할 수 있습니다.npm i buffer --save

은 이것을 당신의 당은이당에서 할 수 .js다음과 같은 파일:

var buffer = require('buffer/').Buffer;

->> console.log(buffer.from("Hello Vishal Thakur").toString('base64'));
SGVsbG8gVmlzaGFsIFRoYWt1cg==  // Result

->> console.log(buffer.from("SGVsbG8gVmlzaGFsIFRoYWt1cg==", 'base64').toString('ascii'))
Hello Vishal Thakur   // Result

다음 코드를 사용하여 Node.js API, Node.js 버전 10.7.0의 Base64 문자열을 디코딩하고 있습니다.

let data = 'c3RhY2thYnVzZS5jb20=';  // Base64 string
let buff = new Buffer(data, 'base64');  //Buffer
let text = buff.toString('ascii');  // This is the data type that you want your Base64 data to convert to
console.log('"' + data + '" converted from Base64 to ASCII is "' + text + '"');

브라우저의 콘솔에서 위의 코드를 실행하려고 하지 마십시오.작동이 안될 거에요.Node.js의 서버 측 파일에 코드를 넣습니다.API 개발에 위 라인 코드를 사용하고 있습니다.

나는 Node.js에서 Base64 인코딩/디코드 변환을 위한 궁극의 작은 자바스크립트 npm 라이브러리를 만들었습니다.

설치

npm install nodejs-base64-converter --save

사용.

var nodeBase64 = require('nodejs-base64-converter');

console.log(nodeBase64.encode("test text")); //dGVzdCB0ZXh0
console.log(nodeBase64.decode("dGVzdCB0ZXh0")); //test text

간단한 JavaScript로 Base64 인코딩 및 디코딩이 가능합니다.

$("input").keyup(function () {
    var value = $(this).val(),
        hash = Base64.encode(value);
    $(".test").html(hash);

    var decode = Base64.decode(hash);

    $(".decode").html(decode);
});

var Base64 = {_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9+/=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/rn/g,"n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}

// Define the string
var string = 'Hello World!';

// Encode the string
var encodedString = Base64.encode(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"

// Decode the string
var decodedString = Base64.decode(encodedString);
console.log(decodedString); // Outputs: "Hello World!"</script></div>

이는 이 Base64 인코더 디코더에서 구현됩니다.

언급URL : https://stackoverflow.com/questions/6182315/how-can-i-do-base64-encoding-in-node-js

반응형