crypto-js#AES TypeScript Examples

The following examples show how to use crypto-js#AES. 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 6 votes vote down vote up
algorithms = {
  AES,
  Rabbit,
  RC4,
  RC4Drop,
}
Example #2
Source File: events.service.ts    From sixpg with MIT License 6 votes vote down vote up
async init() {
        const savedBots = await this.bots.getAll();

        let loggedInCount = 0;
        for (const { tokenHash } of savedBots) {
            const token = AES
                .decrypt(tokenHash || '', process.env.ENCRYPTION_KEY)
                .toString(CryptoJS.enc.Utf8);
            const isValidToken = /^[A-Za-z\d]{24}\.[A-Za-z\d-]{6}\.[A-Za-z\d-_]{27}$/.test(token);
            if (!isValidToken) continue;
            
            try {
                await this.startBot(token);
                loggedInCount++;
            } catch {
                Log.error(`Invalid bot token.`, 'events');
                await SavedBot.deleteOne({ tokenHash });
            }
        }
        Log.info(`Logged in ${loggedInCount} bots`, 'events');
    }
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: 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 #12
Source File: encryption.ts    From nx-extend with MIT License 6 votes vote down vote up
encrypt = (content: string): string | Array<Record<string, string>> => {
  if (typeof content === 'string' && content.trim().length > 0) {
    return AES.encrypt(content, getEncryptionKey()).toString()

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

  return content
}
Example #13
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 #14
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 #15
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 #16
Source File: useEncryptedStore.ts    From back-home-safe with GNU General Public License v3.0 5 votes vote down vote up
encryptValue = (input: string, password: string) =>
  AES.encrypt(input, password).toString()
Example #17
Source File: device-auth.service.ts    From xBull-Wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
async encryptWithDevice(text: string): Promise<{ token?: string; identifier: string; key: string; }> {
    const identifier = 'xBull:' + randomBytes(32).toString('hex');
    const key = randomBytes(32).toString('hex');
    const encryptedText = AES.encrypt(text, key).toString();
    if (this.platform.is('android')) {
      const results = await this.androidFingerprintAuth.isAvailable();
      if (results.isAvailable) {
        try {
          const result = await this.androidFingerprintAuth.encrypt({
            clientId: identifier,
            password: encryptedText,
            disableBackup: true,
            dialogTitle: 'Auth with device',
          });

          return {
            token: result.token,
            identifier,
            key,
          };
        } catch (e: any) {
          throw new Error(`We were not able to encrypt with the device, try again or contact support.`);
        }
      } else {
        throw new Error('Device auth method or password required to continue');
      }
    }

    else if (this.platform.is('ios')) {
      try {
        await this.touchId.isAvailable();
      } catch (e: any) {
        console.error(e);
        throw new Error(`Touch/Face ID is not available.`);
      }

      try {
        await this.touchId.verifyFingerprint('Scan your fingerprint/face please');
      } catch (e: any) {
        console.error(e);
        throw new Error(`Authentication failed`);
      }

      try {
        await this.keychain.set(identifier, encryptedText, true);
      } catch (e: any) {
        console.error(e);
        throw new Error(`We couldn't save the value in the secured storage`);
      }

      return {
        identifier,
        key,
      };
    }

    throw new Error('Platform not supported');
  }
Example #18
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);
  }
Example #19
Source File: crypto.service.ts    From xBull-Wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
encryptText(text: string, secret: string): string {
    return AES.encrypt(text, secret).toString();
  }
Example #20
Source File: encryptMessage.ts    From 0Auth with MIT License 5 votes vote down vote up
export function encryptMessage(message: string, key: string): string {
  return AES.encrypt(message, key).toString();
}
Example #21
Source File: vaultStore.spec.ts    From pali-wallet with MIT License 4 votes vote down vote up
describe('Vault store actions', () => {
  it('should return the initial state', () => {
    expect(reducer(undefined, { type: undefined })).toEqual(initialState);
  });

  //* setNetworks
  describe('setNetworks methods', () => {
    it('should create a network', () => {
      const payloadNetwork: INetwork = {
        chainId: 25,
        url: 'https://evm-cronos.crypto.org/',
        label: 'Cronos',
        currency: 'CRO',
        default: false,
      };
      const payload = { chain: 'ethereum', network: payloadNetwork };

      const newState = reducer(initialState, setNetworks(payload));

      const network = newState.networks[payload.chain][payloadNetwork.chainId];
      expect(network).toEqual(payloadNetwork);
    });

    it('should update an existing network', () => {
      const sysMain = networks.syscoin[57];
      const payloadNetwork: INetwork = {
        ...sysMain,
        label: 'New Label',
      };
      const payload = { chain: 'syscoin', network: payloadNetwork };

      const newState = reducer(initialState, setNetworks(payload));

      const network = newState.networks[payload.chain][payloadNetwork.chainId];
      expect(network).toEqual(payloadNetwork);
    });
  });

  //* setTimer
  it('should set the autolock timer', () => {
    const payload = 10;
    const newState = reducer(initialState, setTimer(payload));

    expect(newState.timer).toEqual(payload);
  });

  //* setEncryptedMnemonic
  it('should set the encrypted mnemonic', () => {
    const mnemonic =
      'buffalo parade cotton festival trap gap judge slush wall top tired club';
    const password = 'st0rngp@ssword';
    const payload = AES.encrypt(mnemonic, password).toString();

    const newState = reducer(initialState, setEncryptedMnemonic(payload));

    expect(newState.encryptedMnemonic).toEqual(payload.toString());
  });

  //* setLastLogin
  it('should set the last login to current datetime', () => {
    const startTime = Date.now();

    const newState = reducer(initialState, setLastLogin());

    const { lastLogin } = newState;
    expect(lastLogin).toBeGreaterThanOrEqual(startTime);
    expect(lastLogin).toBeLessThanOrEqual(Date.now());
  });

  //* createAccount
  it('should create an account', () => {
    const newState = reducer(initialState, createAccount(MOCK_ACCOUNT));

    expect(newState.accounts[MOCK_ACCOUNT.id]).toEqual(MOCK_ACCOUNT);
  });

  describe('accounts removal methods', () => {
    const fakeAccount1 = MOCK_ACCOUNT;
    const fakeAccount2 = {
      ...fakeAccount1,
      id: 27,
    };

    const stateWithAccounts: IVaultState = {
      ...initialState,
      accounts: {
        [fakeAccount1.id]: fakeAccount1,
        [fakeAccount2.id]: fakeAccount2,
      },
    };

    //* removeAccount
    it('should remove an account', () => {
      const payload = { id: fakeAccount1.id };
      const newState = reducer(stateWithAccounts, removeAccount(payload));

      expect(newState.accounts[fakeAccount1.id]).not.toBeDefined();
      expect(newState.accounts[fakeAccount2.id]).toBeDefined();
    });

    //* removeAccounts
    it('should remove all accounts', () => {
      const newState = reducer(stateWithAccounts, removeAccounts());

      expect(newState.accounts).toEqual({});
    });
  });

  //* forgetWallet
  it('should forget the wallet', () => {
    const newState = reducer(undefined, forgetWallet());

    expect(newState).toEqual(initialState);
  });

  //* setActiveNetwork
  it('should set the active network)', () => {
    const sysTestnet = networks.syscoin[5700];
    const newState = reducer(initialState, setActiveNetwork(sysTestnet));

    expect(newState.activeNetwork).toEqual(sysTestnet);
  });

  //* setActiveAccount
  it('should set the active account)', () => {
    const newState = reducer(initialState, setActiveAccount(MOCK_ACCOUNT));

    expect(newState.activeAccount).toEqual(MOCK_ACCOUNT);
  });

  //* setActiveAccountProperty
  it('should set a property for the active account)', () => {
    // state with `accounts` and `activeAccount` populated
    let customState = reducer(initialState, createAccount(MOCK_ACCOUNT));
    customState = reducer(customState, setActiveAccount(MOCK_ACCOUNT));

    const payload = { property: 'label', value: 'New Account Label' };
    const newState = reducer(customState, setActiveAccountProperty(payload));

    const { activeAccount } = newState;
    expect(activeAccount[payload.property]).toEqual(payload.value);
  });

  //* setActiveToken
  it('should set the active token)', () => {
    const payload = 'ETH';
    const newState = reducer(initialState, setActiveToken(payload));

    expect(newState.activeToken).toEqual(payload);
  });

  //* setAccountLabel
  it('should set the label for an account)', () => {
    // 15 = mock account id
    const payload = { id: 15, label: 'Label' };
    const newState = reducer(STATE_W_ACCOUNT, setAccountLabel(payload));

    const account = newState.accounts[payload.id];
    expect(account.label).toEqual(payload.label);
  });

  //* setIsPendingBalances
  it('should set the label for an account)', () => {
    const payload = true;
    const newState = reducer(initialState, setIsPendingBalances(payload));

    expect(newState.isPendingBalances).toBe(true);
  });

  //* setAccountTransactions
  it('should add a transaction for the active account)', () => {
    const payload = { hmm: 'hue' };

    const customState = reducer(
      STATE_W_ACCOUNT,
      setActiveAccount(MOCK_ACCOUNT)
    );
    const newState = reducer(customState, setAccountTransactions(payload));

    const { id } = newState.activeAccount;
    const account = newState.accounts[id];
    expect(account.transactions).toContain(payload);
  });

  //* removeNetwork
  it('should remove a network)', () => {
    const payload = { prefix: 'ethereum', chainId: 4 };
    const newState = reducer(initialState, removeNetwork(payload));

    const { networks } = newState;
    expect(networks.ethereum).toBeDefined();
    expect(networks.ethereum[4]).toBeUndefined();
  });
});