Skip to content

Commit

Permalink
feat: add crypto
Browse files Browse the repository at this point in the history
  • Loading branch information
sarabveer committed Jan 31, 2024
1 parent 4293adf commit 3b44796
Show file tree
Hide file tree
Showing 4 changed files with 1,077 additions and 663 deletions.
20 changes: 20 additions & 0 deletions lib/build-gutka.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
require( './string-colors' )
const GURMUKHI_SOURCES = require( '../data/sourcesList' )
const build = require( './build-database' )
const { encrypt } = require( './utils' )
const { filename } = require( '..' )
const fs = require( 'fs' )
const prompts = require( 'prompts' )

const OUTPUT_PATH = './build'
const outputFile = `${OUTPUT_PATH}/gutka-db.sqlite`
Expand Down Expand Up @@ -88,6 +90,24 @@ const afterBuild = async knex => {
table.dropColumn( 'visible' )
} )

// Ecrypt data
const response = await prompts( {
type: 'password',
name: 'key',
message: 'Enter encryption key:',
} )
await knex.select().from( 'line_content' ).then( lines => {
console.log( 'Encrypting data...' )
lines.forEach( async line => {
await knex( 'line_content' )
.where( 'line_id', line.line_id )
.update( {
gurmukhi: encrypt( line.gurmukhi, response.key ),
larivaar: encrypt( line.larivaar, response.key ),
} )
} )
} )

// Compact sqlite db
await knex.raw( 'VACUUM' )

Expand Down
11 changes: 11 additions & 0 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

const { anyid } = require( 'anyid' )
const { basename } = require( 'path' )
const crypto = require( 'crypto' )
const { findBestMatch } = require( 'string-similarity' )
const memoize = require( 'memoizee' )
const { promisify } = require( 'util' )
Expand Down Expand Up @@ -82,6 +83,15 @@ const larivaar = input => input
.replace( /\s+\u200B/ug, ' ' )
.replace( /\u200B\s+/ug, ' ' )

const encrypt = ( string, password ) => {
const passwordHash = crypto.createHash( 'sha256' ).update( password ).digest()
const iv = crypto.randomBytes( 16 )
const cipher = crypto.createCipheriv( 'aes-256-gcm', passwordHash, iv )
const encrypted = Buffer.concat( [ cipher.update( string, 'utf8' ), cipher.final() ] )
const tag = cipher.getAuthTag()
return Buffer.concat( [ iv, tag, encrypted ] ).toString( 'base64' )
}

module.exports = {
writeJSON,
stripExtension,
Expand All @@ -90,4 +100,5 @@ module.exports = {
findIndex,
fsCopy,
larivaar,
encrypt,
}
Loading

0 comments on commit 3b44796

Please sign in to comment.