Skip to content

Commit

Permalink
Merge pull request #6 from consenlabs/feature/bindCode
Browse files Browse the repository at this point in the history
支持加密存储绑定码并导出
  • Loading branch information
XuNeal authored Jul 6, 2020
2 parents 98f096a + d494726 commit f4cdc88
Show file tree
Hide file tree
Showing 5 changed files with 416 additions and 301 deletions.
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
bindCode_encryptionKey=8c5fab512604d93f836afd5071ac0688
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@
"@sentry/electron": "^1.3.0",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"electron-updater": "^4.3.1",
"element-ui": "^2.13.1",
"express": "^4.17.1",
Expand Down
53 changes: 53 additions & 0 deletions src/api/crypto.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@

import crypto from 'crypto'

// /!\ changing those presets would lock out users with already encrypted databases due to breaking changes.
const ENCRYPTION_ALGORITHM = 'aes-256-cbc'
const IV_LENGTH = 16
const PBKDF2_ITERATIONS = 10000
const PBKDF2_KEY_LENGTH = 32
const PBKDF2_DIGEST = 'sha512'

export const encryptData = (data, encryptionKey) => {
// in any case, we save new data using an initialization vector
const initializationVector = crypto.randomBytes(IV_LENGTH)
const password = crypto.pbkdf2Sync(
encryptionKey,
initializationVector.toString(),
PBKDF2_ITERATIONS,
PBKDF2_KEY_LENGTH,
PBKDF2_DIGEST
)
const cipher = crypto.createCipheriv(ENCRYPTION_ALGORITHM, password, initializationVector)
return Buffer.concat([
initializationVector,
Buffer.from(':'),
cipher.update(data, 'utf8'),
cipher.final()
]).toString('base64')
}

export const decryptData = (raw, encryptionKey) => {
const data = Buffer.from(raw, 'base64')

// We check if the data include an initialization vector
if (data.slice(IV_LENGTH, IV_LENGTH + 1).toString() === ':') {
const initializationVector = data.slice(0, IV_LENGTH)
const password = crypto.pbkdf2Sync(
encryptionKey,
initializationVector.toString(),
PBKDF2_ITERATIONS,
PBKDF2_KEY_LENGTH,
PBKDF2_DIGEST
)
const decipher = crypto.createDecipheriv(ENCRYPTION_ALGORITHM, password, initializationVector)
return Buffer.concat([decipher.update(data.slice(IV_LENGTH + 1)), decipher.final()]).toString(
'utf8'
)
}

// if not, then we fallback to the deprecated API
// eslint-disable-next-line node/no-deprecated-api
const decipher = crypto.createDecipher(ENCRYPTION_ALGORITHM, encryptionKey)
return Buffer.concat([decipher.update(data), decipher.final()]).toString('utf8')
}
Loading

0 comments on commit f4cdc88

Please sign in to comment.