crypto-js#enc TypeScript Examples

The following examples show how to use crypto-js#enc. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From encrypt-storage with MIT License 7 votes vote down vote up
export function getEncriptation(
  encAlgorithm: EncAlgorithm,
  secretKey: string,
): Encryptation {
  return {
    encrypt: (value: string): string => {
      return algorithms[encAlgorithm].encrypt(value, secretKey).toString();
    },
    decrypt: (value: string): string => {
      return algorithms[encAlgorithm]
        .decrypt(value, secretKey)
        .toString(enc.Utf8);
    },
  };
}
Example #2
Source File: signature.ts    From reactjs-social-login with MIT License 6 votes vote down vote up
makeSignature = (
  params: any,
  method: string,
  apiUrl: string,
  consumerSecret: string,
  oauthSecret = ''
) => {
  const paramsBaseString = Object.keys(params)
    .sort()
    .reduce((prev: string, el: any) => {
      return (prev += `&${el}=${params[el]}`)
    }, '')
    .substr(1)

  const signatureBaseString = `${method.toUpperCase()}&${encodeURIComponent(
    apiUrl
  )}&${encodeURIComponent(paramsBaseString)}`

  const signingKey = `${encodeURIComponent(
    consumerSecret
  )}&${encodeURIComponent(oauthSecret)}`

  const oauthSignature = enc.Base64.stringify(
    HmacSHA1(signatureBaseString, signingKey)
  )

  const paramsWithSignature = {
    ...params,
    oauth_signature: encodeURIComponent(oauthSignature)
  }

  return Object.keys(paramsWithSignature)
    .sort()
    .reduce((prev: string, el: any) => {
      return (prev += `,${el}="${paramsWithSignature[el]}"`)
    }, '')
    .substr(1)
}
Example #3
Source File: management.ts    From tatum-kms with MIT License 6 votes vote down vote up
removeWallet = async (id: string, path?: string) => {
    const pwd = config.getValue(ConfigOption.KMS_PASSWORD)
    const pathToWallet = path || homedir() + '/.tatumrc/wallet.dat';
    if (!existsSync(pathToWallet)) {
        console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
        return;
    }
    const data = readFileSync(pathToWallet, { encoding: 'utf8' });
    if (!data?.length) {
        console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
        return;
    }
    const wallet = JSON.parse(AES.decrypt(data, pwd).toString(enc.Utf8));
    delete wallet[id];
    writeFileSync(pathToWallet, AES.encrypt(JSON.stringify(wallet), pwd).toString());
}
Example #4
Source File: management.ts    From tatum-kms with MIT License 6 votes vote down vote up
getAddress = async (id: string, index: string, path?: string) => {
    const pwd = config.getValue(ConfigOption.KMS_PASSWORD)
    const pathToWallet = path || homedir() + '/.tatumrc/wallet.dat';
    if (!existsSync(pathToWallet)) {
        console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
        return;
    }
    const data = readFileSync(pathToWallet, { encoding: 'utf8' });
    if (!data?.length) {
        console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
        return;
    }
    const wallet = JSON.parse(AES.decrypt(data, pwd).toString(enc.Utf8));
    if (!wallet[id]) {
        console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
        return;
    }
    const pk = { address: (wallet[id].address ? wallet[id].address : await generateAddressFromXPub(wallet[id].chain, wallet[id].testnet, wallet[id].xpub, parseInt(index))) };
    console.log(JSON.stringify(pk, null, 2));
}
Example #5
Source File: management.ts    From tatum-kms with MIT License 6 votes vote down vote up
getPrivateKey = async (id: string, index: string, path?: string) => {
    const pwd = config.getValue(ConfigOption.KMS_PASSWORD)
    const pathToWallet = path || homedir() + '/.tatumrc/wallet.dat';
    if (!existsSync(pathToWallet)) {
        console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
        return;
    }
    const data = readFileSync(pathToWallet, { encoding: 'utf8' });
    if (!data?.length) {
        console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
        return;
    }
    const wallet = JSON.parse(AES.decrypt(data, pwd).toString(enc.Utf8));
    if (!wallet[id]) {
        console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
        return;
    }
    const pk = { privateKey: (wallet[id].secret
            ? wallet[id].secret
            : await generatePrivateKeyFromMnemonic(wallet[id].chain, wallet[id].testnet, wallet[id].mnemonic, parseInt(index))) };
    console.log(JSON.stringify(pk, null, 2));
}
Example #6
Source File: management.ts    From tatum-kms with MIT License 6 votes vote down vote up
getWallet = async (id: string, path?: string, pwd?: string, print = true) => {
    const password = pwd ?? config.getValue(ConfigOption.KMS_PASSWORD);
    const pathToWallet = path || homedir() + '/.tatumrc/wallet.dat';
    if (!existsSync(pathToWallet)) {
        console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
        return;
    }
    const data = readFileSync(pathToWallet, { encoding: 'utf8' });
    if (!data?.length) {
        console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
        return;
    }
    try {
        const wallet = JSON.parse(AES.decrypt(data, password).toString(enc.Utf8));
        if (!wallet[id]) {
            console.error(JSON.stringify({ error: `No such wallet for signatureId '${id}'.` }, null, 2));
            return;
        }
        if (print) {
            console.log(JSON.stringify(wallet[id], null, 2));
        }
        return wallet[id];
    } catch (e) {
        console.error(JSON.stringify({ error: `Wrong password.` }, null, 2));
        return;
    }
}
Example #7
Source File: management.ts    From tatum-kms with MIT License 6 votes vote down vote up
storePrivateKey = async (chain: Currency, testnet: boolean, privateKey: string, path?: string) => {
    const pwd = config.getValue(ConfigOption.KMS_PASSWORD)
    const pathToWallet = path || homedir() + '/.tatumrc/wallet.dat';
    const key = uuid();
    const entry = { [key]: { privateKey, chain, testnet } };
    if (!existsSync(pathToWallet)) {
        ensurePathExists(pathToWallet);
        writeFileSync(pathToWallet, AES.encrypt(JSON.stringify(entry), pwd).toString());
    } else {
        const data = readFileSync(pathToWallet, { encoding: 'utf8' });
        let walletData = entry;
        if (data?.length > 0) {
            walletData = { ...walletData, ...JSON.parse(AES.decrypt(data, pwd).toString(enc.Utf8)) };
        }
        writeFileSync(pathToWallet, AES.encrypt(JSON.stringify(walletData), pwd).toString());
    }
    console.log(JSON.stringify({ signatureId: key }, null, 2));
}
Example #8
Source File: management.ts    From tatum-kms with MIT License 6 votes vote down vote up
storeWallet = async (chain: Currency, testnet: boolean, path?: string, mnemonic?: string) => {
    const pwd = config.getValue(ConfigOption.KMS_PASSWORD);
    const pathToWallet = path || homedir() + '/.tatumrc/wallet.dat';
    let wallet: any;
    if (chain === Currency.SOL) {
        wallet = await generateSolanaWallet();
    } else if (chain === Currency.KCS) {
        wallet = await generateKcsWallet(mnemonic, {testnet});
    } else if (chain === Currency.LUNA) {
        wallet = TatumTerraSDK({apiKey: process.env.TATUM_API_KEY as string}).wallet.wallet();
    } else {
        wallet = await generateWallet(chain, testnet, mnemonic);
    }
    const key = uuid();
    const entry = {[key]: {...wallet, chain, testnet}};
    if (!existsSync(pathToWallet)) {
        ensurePathExists(pathToWallet);
        writeFileSync(pathToWallet, AES.encrypt(JSON.stringify(entry), pwd).toString());
    } else {
        const data = readFileSync(pathToWallet, { encoding: 'utf8' });
        let walletData = entry;
        if (data?.length > 0) {
            walletData = { ...walletData, ...JSON.parse(AES.decrypt(data, pwd).toString(enc.Utf8)) };
        }
        writeFileSync(pathToWallet, AES.encrypt(JSON.stringify(walletData), pwd).toString());
    }
    const value: any = { signatureId: key };
    if (wallet.address) {
        value.address = wallet.address;
    }
    if (wallet.xpub) {
        value.xpub = wallet.xpub;
    }
    console.log(JSON.stringify(value, null, 2));
}
Example #9
Source File: management.ts    From tatum-kms with MIT License 6 votes vote down vote up
getManagedWallets = (pwd: string, chain: string, testnet: boolean, path?: string) => {
    const pathToWallet = path || homedir() + '/.tatumrc/wallet.dat';
    if (!existsSync(pathToWallet)) {
        console.error(JSON.stringify({error: `No such wallet file.`}, null, 2));
        return [];
    }
    const data = readFileSync(pathToWallet, {encoding: 'utf8'});
    if (!data?.length) {
        return [];
    }
    const wallets = JSON.parse(AES.decrypt(data, pwd).toString(enc.Utf8));
    const keys = [];
    for (const walletsKey in wallets) {
        if (chain === wallets[walletsKey].chain && testnet === wallets[walletsKey].testnet) {
            keys.push(walletsKey);
        }
    }
    return keys;
}
Example #10
Source File: management.ts    From tatum-kms with MIT License 6 votes vote down vote up
exportWallets = (path?: string) => {
    const pwd = config.getValue(ConfigOption.KMS_PASSWORD)
    const pathToWallet = path || homedir() + '/.tatumrc/wallet.dat';
    if (!existsSync(pathToWallet)) {
        console.error(JSON.stringify({error: `No such wallet file.`}, null, 2));
        return;
    }
    const data = readFileSync(pathToWallet, {encoding: 'utf8'});
    if (!data?.length) {
        console.error(JSON.stringify({error: `No such wallet file.`}, null, 2));
        return;
    }
    console.log(JSON.stringify(JSON.parse(AES.decrypt(data, pwd).toString(enc.Utf8)), null, 2));
}
Example #11
Source File: paypay-rest-sdk.ts    From paypayopa-sdk-node with Apache License 2.0 6 votes vote down vote up
private createAuthHeader = (method: string, resourceUrl: string, body: unknown) => {
    const epoch = Math.floor(Date.now() / 1000);
    const nonce = uuidv4();

    const jsonified = JSON.stringify(body);
    const isempty = [undefined, null, "", "undefined", "null"];

    let contentType;
    let payloadDigest;
    if (isempty.includes(jsonified)) {
      contentType = "empty";
      payloadDigest = "empty";
    } else {
      contentType = "application/json";
      payloadDigest = algo.MD5.create()
        .update(contentType)
        .update(jsonified)
        .finalize()
        .toString(enc.Base64);
    }
    const signatureRawList = [resourceUrl, method, nonce, epoch, contentType, payloadDigest];
    const signatureRawData = signatureRawList.join("\n");
    const hashed = HmacSHA256(signatureRawData, this.auth.clientSecret);
    const hashed64 = enc.Base64.stringify(hashed);
    const headList = [this.auth.clientId, hashed64, nonce, epoch, payloadDigest];
    const header = headList.join(":");
    return `hmac OPA-Auth:${header}`;
  }
Example #12
Source File: password-encoder.ts    From malagu with MIT License 6 votes vote down vote up
async encode(rawPassword: string): Promise<string> {
        const { encodeHashAsBase64 } = this.options;
        const salt = lib.WordArray.random(8);
        const encoded = this.doEncode(rawPassword, salt.toString());
        if (encodeHashAsBase64) {
            return enc.Base64.stringify(enc.Utf8.parse(encoded));
        }
        return encoded;
    }
Example #13
Source File: error-hander.ts    From malagu with MIT License 6 votes vote down vote up
async handle(ctx: Context, err: OAuth2AuthorizationError): Promise<void> {
        const { oauth2Error } = err;
        const authorizationRequest = <AuthorizationRequest>await this.authorizationRequestManager.remove();

        let redirectUri = `${authorizationRequest.redirectUri}?${OAuth2ParameterNames.ERROR}=${oauth2Error.errorCode}`;
        if (oauth2Error.description) {
            redirectUri = `${redirectUri}&${OAuth2ParameterNames.ERROR_DESCRIPTION}=${enc.Base64.stringify(enc.Utf8.parse(oauth2Error.description))}`;
        }

        if (oauth2Error.uri) {
            redirectUri = `${redirectUri}&${OAuth2ParameterNames.ERROR_URI}=${enc.Base64.stringify(enc.Utf8.parse(oauth2Error.uri))}`;

        }

        await this.redirectStrategy.send(redirectUri);
        ctx.response.end(err.message);
    }
Example #14
Source File: encryption.ts    From nx-extend with MIT License 6 votes vote down vote up
decrypt = (cipherText: string): string | Array<Record<string, string>> => {
  if (typeof cipherText === 'string' && cipherText.trim().length > 0) {
    return AES.decrypt(cipherText, getEncryptionKey()).toString(enc.Utf8)

  } else if (Array.isArray(cipherText)) {
    return cipherText.map((item: SecretFile) => decryptFile(item, true))
  }

  return cipherText
}
Example #15
Source File: device-auth.service.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
async decryptWithDevice(params: { token?: string, identifier: string; key: string }): Promise<string> {
    if (this.platform.is('android')) {
      if (!params.token) {
        throw new Error(`Token is not available in the device, please reset the auth integration in the settings page`);
      }

      const results = await this.androidFingerprintAuth.isAvailable();
      if (results.isAvailable) {
        try {
          const result = await this.androidFingerprintAuth.decrypt({
            clientId: params.identifier,
            token: params.token,
          });

          return AES.decrypt(result.password, params.key).toString(enc.Utf8);
        } catch (e: any) {
          throw new Error(`Unauthorized, try again or contact support.`);
        }
      } else {
        throw new Error('Device auth method or password is not available');
      }
    }

    else if (this.platform.is('ios')) {
      try {
        return this.keychain.get(params.identifier, 'Confirm with Touch/Face ID to continue')
          .then(text => AES.decrypt(text, params.key).toString(enc.Utf8));
      } catch (e: any) {
        console.error(e);
        throw new Error(`We couldn't get the key from the secured storage.`);
      }
    }

    throw new Error('Platform not supported');
  }
Example #16
Source File: decryptMessage.ts    From 0Auth with MIT License 5 votes vote down vote up
export function decryptMessage(encryptedMessage: string, key: string): string {
  return AES.decrypt(encryptedMessage, key).toString(enc.Utf8);
}
Example #17
Source File: useEncryptedStore.ts    From back-home-safe with GNU General Public License v3.0 5 votes vote down vote up
decryptValue = (input: string, password: string) =>
  AES.decrypt(input, password).toString(enc.Utf8)
Example #18
Source File: password-encoder.ts    From malagu with MIT License 5 votes vote down vote up
protected doDecode(encoded: string): string {
        const { encodeHashAsBase64 } = this.options;
        if (encodeHashAsBase64) {
            return enc.Base64.parse(encoded).toString(enc.Utf8);
        }
        return encoded;
    }
Example #19
Source File: base64-string-key-generator.ts    From malagu with MIT License 5 votes vote down vote up
async generateKey(keyLength?: number) {
        const key = lib.WordArray.random(keyLength || this.keyLength);
        return enc.Base64.stringify(key);
    }
Example #20
Source File: authorization-request-resolver.ts    From malagu with MIT License 5 votes vote down vote up
protected createHash(nonce: string) {
        return enc.Base64.stringify(SHA256(nonce));
    }
Example #21
Source File: crypto.service.ts    From xBull-Wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
decryptText(text: string, secret: string): string {
    return AES.decrypt(text, secret).toString(enc.Utf8);
  }