node.js有內置的base64編碼嗎? html
我之因此這麼說是由於來自crypto
final()
只能輸出hex,binary或ascii數據。 例如: node
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。 我試過了,它會破裂。 api
若是我這樣作: 瀏覽器
var ciph = cipher.update(plaintext, 'utf8', 'base64'); ciph += cipher.final('hex');
而後我應該用什麼解密? Hex或base64? 安全
所以,我正在尋找一個函數來對個人加密十六進制輸出進行base64編碼。 服務器
謝謝。 函數
crypto如今支持base64( 參考 ): this
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');
接受的答案包含在大於6的節點版本中被視爲安全問題的內容(儘管此用例彷佛可能始終將輸入強制轉換爲字符串)。 加密
根據文檔不推薦使用Buffer
構造函數。
如下是在ws庫中使用它可能致使的漏洞示例。
代碼段應爲:
console.log(Buffer.from("Hello World").toString('base64')); console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'));
我使用如下代碼來解碼節點API nodejs版本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 + '"');
請不要嘗試在瀏覽器的控制檯中運行上面的代碼,將沒法正常工做。 將代碼放在nodejs的服務器端文件中。 我在API開發中使用上面的代碼。
緩衝區可用於獲取字符串或數據,並對結果進行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' - 多字節編碼的Unicode字符。 許多網頁和其餘文檔格式使用UTF-8。
'ucs2' - 2字節,小端編碼的Unicode字符。 它只能編碼BMP(基本多語言平面,U + 0000 - U + FFFF)。
'base64' - Base64字符串編碼。
'binary' - 一種經過僅使用每一個字符的前8位將原始二進制數據編碼爲字符串的方法。 不推薦使用此編碼方法,應儘量避免使用Buffer對象。 在未來的Node版本中將刪除此編碼。