Skip to content

Compress encrypted data #231

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 27 additions & 14 deletions cli/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const pathModule = require("path");
const fs = require("fs");
const readline = require("readline");

const { generateRandomSalt, generateRandomString } = require("../lib/cryptoEngine.js");
const { generateRandomSaltString, generateRandomString } = require("../lib/cryptoEngine.js");
const { renderTemplate } = require("../lib/formater.js");
const Yargs = require("yargs");

Expand Down Expand Up @@ -74,14 +74,14 @@ function prompt(question) {
}

/**
* @param {string} password
* @param {string} passwordString
* @param {boolean} isShortAllowed
* @returns {Promise<void>}
*/
async function validatePassword(password, isShortAllowed) {
if (password.length < 14 && !isShortAllowed) {
async function validatePasswordString(passwordString, isShortAllowed) {
if (passwordString.length < 14 && !isShortAllowed) {
const shouldUseShort = await prompt(
`WARNING: Your password is less than 14 characters (length: ${password.length})` +
`WARNING: Your password is less than 14 characters (length: ${passwordString.length})` +
" and it's easy to try brute-forcing on public files, so we recommend using a longer one. Here's a generated one: " +
generateRandomString(21) +
"\nYou can hide this warning by increasing your password length or adding the '--short' flag." +
Expand All @@ -94,7 +94,7 @@ async function validatePassword(password, isShortAllowed) {
}
}
}
exports.validatePassword = validatePassword;
exports.validatePasswordString = validatePasswordString;

/**
* Get the config from the config file.
Expand Down Expand Up @@ -124,7 +124,7 @@ exports.writeConfig = writeConfig;
* @param {string} passwordArgument - password from the command line
* @returns {Promise<string>}
*/
async function getPassword(passwordArgument) {
async function getPasswordString(passwordArgument) {
// try to get the password from the environment variable
const envPassword = process.env.STATICRYPT_PASSWORD;
const hasEnvPassword = envPassword !== undefined && envPassword !== "";
Expand All @@ -140,7 +140,7 @@ async function getPassword(passwordArgument) {
// prompt the user for their password
return prompt("Enter your long, unusual password: ");
}
exports.getPassword = getPassword;
exports.getPasswordString = getPasswordString;

/**
* @param {string} filepath
Expand All @@ -155,13 +155,26 @@ function getFileContent(filepath) {
}
exports.getFileContent = getFileContent;

/**
* @param {string} filepath
* @returns {Uint8Array}
*/
function getFileContentBytes(filepath) {
try {
return new Uint8Array(fs.readFileSync(filepath));
} catch (e) {
exitWithError(`input file '${filepath}' does not exist!`);
}
}
exports.getFileContentBytes = getFileContentBytes;

/**
* @param {object} namedArgs
* @param {object} config
* @returns {string}
*/
function getValidatedSalt(namedArgs, config) {
const salt = getSalt(namedArgs, config);
function getValidatedSaltString(namedArgs, config) {
const salt = getSaltString(namedArgs, config);

// validate the salt
if (salt.length !== 32 || /[^a-f0-9]/.test(salt)) {
Expand All @@ -174,16 +187,16 @@ function getValidatedSalt(namedArgs, config) {

return salt;
}
exports.getValidatedSalt = getValidatedSalt;
exports.getValidatedSaltString = getValidatedSaltString;

/**
* @param {object} namedArgs
* @param {object} config
* @returns {string}
*/
function getSalt(namedArgs, config) {
function getSaltString(namedArgs, config) {
// either a salt was provided by the user through the flag --salt
if (!!namedArgs.salt) {
if (namedArgs.salt) {
return String(namedArgs.salt).toLowerCase();
}

Expand All @@ -192,7 +205,7 @@ function getSalt(namedArgs, config) {
return config.salt;
}

return generateRandomSalt();
return generateRandomSaltString();
}

/**
Expand Down
84 changes: 58 additions & 26 deletions cli/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const fs = require("fs");

const cryptoEngine = require("../lib/cryptoEngine.js");
const codec = require("../lib/codec.js");
const { generateRandomSalt } = cryptoEngine;
const { generateRandomSaltString } = cryptoEngine;
const { decode, encodeWithHashedPassword } = codec.init(cryptoEngine);
const {
OUTPUT_DIRECTORY_DEFAULT_PATH,
Expand All @@ -26,12 +26,13 @@ const {
genFile,
getConfig,
getFileContent,
getPassword,
getValidatedSalt,
getFileContentBytes,
getPasswordString,
getValidatedSaltString,
isOptionSetByUser,
parseCommandLineArguments,
recursivelyApplyCallbackToHtmlFiles,
validatePassword,
validatePasswordString,
writeConfig,
writeFile,
getFullOutputPath,
Expand Down Expand Up @@ -63,31 +64,36 @@ async function runStatiCrypt() {

// if the 's' flag is passed without parameter, generate a salt, display & exit
if (hasSaltFlag && !namedArgs.salt) {
const generatedSalt = generateRandomSalt();
const generatedSaltString = generateRandomSaltString();

// show salt
console.log(generatedSalt);
console.log(generatedSaltstring);

// write to config file if it doesn't exist
if (!config.salt) {
config.salt = generatedSalt;
config.salt = generatedSaltstring;
writeConfig(configPath, config);
}

return;
}

// get the salt & password
const salt = getValidatedSalt(namedArgs, config);
const password = await getPassword(namedArgs.password);
const saltString = getValidatedSaltString(namedArgs, config);
const salt = cryptoEngine.HexEncoder.parse(saltString);

const passwordString = await getPasswordString(namedArgs.password);
const password = cryptoEngine.UTF8Encoder.parse(passwordString);

const hashedPassword = await cryptoEngine.hashPassword(password, salt);
const hashedPasswordString = cryptoEngine.HexEncoder.stringify(hashedPassword);

// display the share link with the hashed password if the --share flag is set
if (hasShareFlag) {
await validatePassword(password, namedArgs.short);
await validatePasswordString(passwordString, namedArgs.short);

let url = namedArgs.share || "";
url += "#staticrypt_pwd=" + hashedPassword;
url += "#staticrypt_pwd=" + hashedPasswordString;

if (namedArgs.shareRemember) {
url += `&remember_me`;
Expand Down Expand Up @@ -124,11 +130,11 @@ async function runStatiCrypt() {
return;
}

await validatePassword(password, namedArgs.short);
await validatePasswordString(passwordString, namedArgs.short);

// write salt to config file
if (config.salt !== salt) {
config.salt = salt;
if (config.salt !== saltString) {
config.salt = saltString;
writeConfig(configPath, config);
}

Expand Down Expand Up @@ -157,7 +163,7 @@ async function runStatiCrypt() {
fullPath,
fullRootDirectory,
hashedPassword,
salt,
saltString,
baseTemplateData,
isRememberEnabled,
namedArgs
Expand All @@ -169,20 +175,46 @@ async function runStatiCrypt() {
});
}

function getEncryptedData(encryptedFileContent, path) {
let encrypted = null;

const encryptedMatch = encryptedFileContent.match(
/data-encrypted="data:application\/octet-stream\;base64\,([^"]+)"/
);
if (!encryptedMatch) {
console.log(`ERROR: could not extract cipher text from ${path}`);
} else {
encrypted = cryptoEngine.Base64Encoder.parse(encryptedMatch[1]);
}

return encrypted;
}

async function decodeAndGenerateFile(path, fullRootDirectory, hashedPassword, outputDirectory) {
// get the file content
const encryptedFileContent = getFileContent(path);

// extract the cipher text from the encrypted file
const cipherTextMatch = encryptedFileContent.match(/"staticryptEncryptedMsgUniqueVariableName":\s*"([^"]+)"/);
const ivMatch = encryptedFileContent.match(/"staticryptIvUniqueVariableName":\s*"([^"]+)"/);
const hmacMatch = encryptedFileContent.match(/"staticryptHmacUniqueVariableName":\s*"([^"]+)"/);
const saltMatch = encryptedFileContent.match(/"staticryptSaltUniqueVariableName":\s*"([^"]+)"/);

if (!cipherTextMatch || !saltMatch) {
return console.log(`ERROR: could not extract cipher text or salt from ${path}`);
if (!ivMatch || !hmacMatch || !saltMatch) {
return console.log(`ERROR: could not extract cipher text, iv, hmac, or salt from ${path}`);
}

const iv = cryptoEngine.HexEncoder.parse(ivMatch[1]);
const hmac = cryptoEngine.HexEncoder.parse(hmacMatch[1]);
const salt = cryptoEngine.HexEncoder.parse(saltMatch[1]);

// decrypt input
const { success, decoded } = await decode(cipherTextMatch[1], hashedPassword, saltMatch[1]);
const { success, decoded } = await decode(
iv,
() => getEncryptedData(encryptedFileContent, path),
hmac,
hashedPassword,
salt
);

if (!success) {
return console.log(`ERROR: could not decrypt ${path}`);
Expand All @@ -197,28 +229,28 @@ async function encodeAndGenerateFile(
path,
rootDirectoryFromArguments,
hashedPassword,
salt,
saltString,
baseTemplateData,
isRememberEnabled,
namedArgs
) {
// get the file content
const contents = getFileContent(path);

// encrypt input
const encryptedMsg = await encodeWithHashedPassword(contents, hashedPassword);
const encryptedMsg = await encodeWithHashedPassword(() => getFileContentBytes(path), hashedPassword);

let rememberDurationInDays = parseInt(namedArgs.remember);
rememberDurationInDays = isNaN(rememberDurationInDays) ? 0 : rememberDurationInDays;

const staticryptConfig = {
staticryptEncryptedMsgUniqueVariableName: encryptedMsg,
staticryptIvUniqueVariableName: cryptoEngine.HexEncoder.stringify(encryptedMsg.iv),
staticryptHmacUniqueVariableName: cryptoEngine.HexEncoder.stringify(encryptedMsg.hmac),

isRememberEnabled,
rememberDurationInDays,
staticryptSaltUniqueVariableName: salt,
staticryptSaltUniqueVariableName: saltString,
};
const templateData = {
...baseTemplateData,
encrypted_data: cryptoEngine.Base64Encoder.stringify(encryptedMsg.encrypted),
staticrypt_config: staticryptConfig,
};

Expand Down
Loading