crypto#createCipheriv TypeScript Examples

The following examples show how to use crypto#createCipheriv. 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: crypto.ts    From FIDO2Client with MIT License 6 votes vote down vote up
static encrypt(key: Buffer, message: Buffer): Buffer {
        switch (Fido2Spec) {
            case Fido2SpecVersion.FIDO_2_1: {
                let cipher = createCipheriv('aes-256-cbc', key, Buffer.alloc(16));
                return cipher.update(message);
            }
            default:
                throw new CommonFido2SpecNotImplemented();
        }
    }
Example #2
Source File: crypto.ts    From cloudmusic-vscode with MIT License 6 votes vote down vote up
aesEncrypt = (
  buffer: Buffer,
  mode: string,
  key: Uint8Array | Buffer | string,
  iv: Buffer | string
) => {
  const cipher = createCipheriv(`aes-128-${mode}`, key, iv);
  return Buffer.concat([cipher.update(buffer), cipher.final()]);
}
Example #3
Source File: utils.ts    From eufy-security-client with MIT License 6 votes vote down vote up
encryptPassword = (password: string, key: Buffer): string => {
    const cipher = createCipheriv("aes-256-cbc", key, key.slice(0, 16));
    return (
        cipher.update(password, "utf8", "base64") +
        cipher.final("base64")
    );
}
Example #4
Source File: utils.ts    From eufy-security-client with MIT License 6 votes vote down vote up
encryptAdvancedLockData = (data: string, key: Buffer, iv: Buffer): Buffer => {
    const cipher = createCipheriv("aes-128-cbc", key, iv);
    return Buffer.concat([
        cipher.update(data),
        cipher.final()]
    );
}
Example #5
Source File: prg.ts    From hoprnet with GNU General Public License v3.0 6 votes vote down vote up
digest(start: number, end: number): Uint8Array {
    if (start >= end) {
      throw Error(`Invalid range parameters. 'start' must be strictly smaller than 'end'.`)
    }

    const firstBlock = Math.floor(start / BLOCK_LENGTH)
    const startOffset = start % BLOCK_LENGTH

    const lastBlock = Math.ceil(end / BLOCK_LENGTH)
    const lastBlockSize = end % BLOCK_LENGTH

    const amountOfBlocks = lastBlock - firstBlock

    const iv = Uint8Array.from([...this.iv, ...toU8a(firstBlock, PRG_COUNTER_LENGTH)])

    return createCipheriv(PRG_ALGORITHM, this.key, iv)
      .update(new Uint8Array(amountOfBlocks * BLOCK_LENGTH))
      .subarray(startOffset, amountOfBlocks * BLOCK_LENGTH - (lastBlockSize > 0 ? BLOCK_LENGTH - lastBlockSize : 0))
  }
Example #6
Source File: node-crypto.ts    From mtcute with GNU Lesser General Public License v3.0 6 votes vote down vote up
createAesCtr(key: Buffer, iv: Buffer, encrypt: boolean): IEncryptionScheme {
        const cipher = (
            encrypt ? createCipheriv : createDecipheriv
        )(`aes-${key.length * 8}-ctr`, key, iv)

        const update = (data: Buffer) => cipher.update(data)

        return {
            encrypt: update,
            decrypt: update,
        }
    }
Example #7
Source File: node-crypto.ts    From mtcute with GNU Lesser General Public License v3.0 6 votes vote down vote up
createAesEcb(key: Buffer): IEncryptionScheme {
        const methodName = `aes-${key.length * 8}-ecb`

        return {
            encrypt(data: Buffer) {
                const cipher = createCipheriv(methodName, key, null)
                cipher.setAutoPadding(false)
                return Buffer.concat([cipher.update(data), cipher.final()])
            },
            decrypt(data: Buffer) {
                const cipher = createDecipheriv(
                    methodName,
                    key,
                    null
                )
                cipher.setAutoPadding(false)
                return Buffer.concat([cipher.update(data), cipher.final()])
            },
        }
    }
Example #8
Source File: crypter.ts    From fivem with MIT License 6 votes vote down vote up
/**
     * @description
     * Encrypt a data
     *
     * @example
     * ```ts
     * encrypt('bacon'); // Result: "e7b75a472b65bc4a42e7b3f788..."
     * ```
     */
    encrypt = (text: string) => {
        const cipher = createCipheriv(this.#algorithm, this.#secretKey, this.#iv);
        const encrypted = Buffer.concat([cipher.update(text), cipher.final()]);

        return encrypted.toString("hex");
    };
Example #9
Source File: prp.ts    From hoprnet with GNU General Public License v3.0 5 votes vote down vote up
function encrypt(data: Uint8Array, k: Uint8Array, iv: Uint8Array): void {
  const cipher = createCipheriv(CIPHER_ALGORITHM, u8aXOR(false, k, data.subarray(0, HASH_LENGTH)), iv)

  const ciphertext = cipher.update(data.subarray(HASH_LENGTH))
  data.set(ciphertext, HASH_LENGTH)
}
Example #10
Source File: encrypt.ts    From server with GNU General Public License v3.0 4 votes vote down vote up
encrypt: IEncryptFunction = {
  aes: {
    /**
     * Encrypt a String using AES Algorithm
     *
     * @param {string} str - String to Encrypt
     * @returns {Promise<string>} - Encrypted String
     */
    str: (str: string): string => {
      const { GLOBAL_PASSPHRASE, IV } = process.env;
      if (GLOBAL_PASSPHRASE && IV) {
        const algorithm = 'aes-256-cbc';
        const [iv, secret] = [
          Buffer.from(IV, 'hex'),
          Buffer.from(GLOBAL_PASSPHRASE, 'hex'),
        ];
        const cipher = createCipheriv(algorithm, secret, iv);
        let encryptedData = cipher.update(str, 'utf-8', 'hex');
        encryptedData += cipher.final('hex');
        return encryptedData;
      } else {
        throw new Error(
          'GLOBAL_PASSPHRASE, IV not found in Environment Variables, Kindly Setup',
        );
      }
    },

    /**
     * Encrypts Data with AES Method
     *
     * @param {ICryptoObjData<Object>} data - Data to be Encrypted
     * @returns {Promise<string>} - Encrypted Data
     */
    obj: <T>(data: ICryptoObjData<T>): string => {
      const { GLOBAL_PASSPHRASE, IV } = process.env;
      if (GLOBAL_PASSPHRASE && IV) {
        const algorithm = 'aes-256-cbc';
        const [iv, secret] = [
          Buffer.from(IV, 'hex'),
          Buffer.from(GLOBAL_PASSPHRASE, 'hex'),
        ];
        const cipher = createCipheriv(algorithm, secret, iv);
        const dataToEncrypt = JSON.stringify(data);
        let encryptedData = cipher.update(dataToEncrypt, 'utf-8', 'hex');
        encryptedData += cipher.final('hex');
        return encryptedData;
      } else {
        throw new Error(
          'GLOBAL_PASSPHRASE, IV not found in Environment Variables, Kindly Setup',
        );
      }
    },
  },
  rsa: {
    /**
     * Encrypt a String using RSA Algorithm
     *
     * @param {string} str - String to Encrypt
     * @returns {Promise<string>} - Encrypted String
     */
    str: async (str: string): Promise<string> => {
      const publicKey = await Keys.findOne({ type: 'publickey' }).exec();
      if (publicKey) {
        const toEncrypt = new CompactEncrypt(
          new TextEncoder().encode(str),
        ).setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A256GCM' });
        const pubKey = await importJWK(publicKey.key, 'PS256');
        const encryptedString = await toEncrypt.encrypt(pubKey);
        return encryptedString;
      } else {
        throw new Error(
          'Public Key Not Available in the Database, Please Setup first, then try this',
        );
      }
    },

    /**
     * Encrypts Data with RSA Method
     *
     * @param {string | object} data - Data to be Encrypted
     * @returns {Promise<string>} - Encrypted Data
     */
    obj: async <T>(data: ICryptoObjData<T>): Promise<string> => {
      const publicKey = await Keys.findOne({ type: 'publickey' }).exec();
      if (publicKey) {
        const toEncrypt = new CompactEncrypt(
          new TextEncoder().encode(JSON.stringify(data)),
        ).setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A256GCM' });
        const pubKey = await importJWK(publicKey.key, 'PS256');
        const encryptedData = await toEncrypt.encrypt(pubKey);
        return encryptedData;
      } else {
        throw new Error(
          'Public Key Not Available in the Database, Please Setup first, then try this',
        );
      }
    },
  },
}