How to use crypto-js - 10 common examples

To help you get started, we’ve selected a few crypto-js examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github nemtech / nem2-sdk-typescript-javascript / test / core / crypto / crypto.spec.ts View on Github external
it('Can encrypt and decrypt private key for mobile', () => {
        // Arrange:
        const privateKey = '2a91e1d5c110a8d0105aad4683f962c2a56663a3cad46666b16d243174673d90';
        const password = 'TestTest';

        // Act:
        const result = Crypto.toMobileKey(password, privateKey);
        const encrypted = result.encrypted;
        const salt = CryptoJS.enc.Hex.parse(result.salt);

        const key = CryptoJS.PBKDF2(password, salt, {
            keySize: 256 / 32,
            iterations: 2000,
        });

        const iv = encrypted.substring(0, 32);
        const encryptedPrvKey = encrypted.substring(32, 128);

        const obj = {
            ciphertext: CryptoJS.enc.Hex.parse(encryptedPrvKey),
            iv: convert.hexToUint8(iv),
            key: convert.hexToUint8(key.toString()),
        };

        const decrypted = Crypto.decrypt(obj);

        // Assert:
github oddbit / tanam / functions / src / triggers / users.ts View on Github external
export const createUser = cloudFunctions.auth.user().onCreate(async (firebaseUser) => {
  const tanamConfig = configService.getConfig();

  const tanamConfigRole = tanamConfig.users ? tanamConfig.users[firebaseUser.email] : null;
  const envRole = firebaseUser.email === process.env.TANAM_SUPER_ADMIN ? 'superAdmin' : null;
  const initialRole = envRole || tanamConfigRole;

  // Use gravatar as default if photoUrl isn't specified in user data
  // https://en.gravatar.com/site/implement/images/
  const gravatarHash = MD5(firebaseUser.email || firebaseUser.uid).toString().toLowerCase();
  const user = {
    uid: firebaseUser.uid,
    name: firebaseUser.displayName || firebaseUser.email,
    email: firebaseUser.email,
    photoUrl: firebaseUser.photoURL || `https://www.gravatar.com/avatar/${gravatarHash}.jpg?s=1024&d=identicon`,
    roles: !!initialRole ? [initialRole] : [],
  };

  console.log(`Creating account: ${JSON.stringify({ user })}`);
  return Promise.all([
    siteService.initializeSite(),
    admin.firestore()
      .collection('tanam').doc(process.env.GCLOUD_PROJECT)
      .collection('users').doc(firebaseUser.uid)
      .set(user),
    setUserRoleToAuth(user),
github segmentstream / digital-data-manager / src / integrations / DDManagerStreaming.js View on Github external
trackEvent (event) {
    // identify
    if (size(event.user)) {
      const user = event.user || {}
      if (user.email) {
        this.setEmailHash(sha256(user.email.trim()).toString())
      }
      if (user.anonymousId) {
        this.setAnonymousId(user.anonymousId)
      }
      if (user.userId) {
        this.setUserId(String(user.userId))
      }
    }

    if (event.name === VIEWED_PAGE && event.website) {
      this.website = this.filters.filterWebsite(event.website)
    }
    // for SPA apps we create campaign only on first pageview
    if (event.name === VIEWED_PAGE) this.viewedPageCounter += 1

    this.sendEventHit(event)
github blocktrail / wallet-recovery-tool / src / libs / blocktrail-sdk / lib / wallet_sweeper.js View on Github external
bip39.mnemonicToEntropy(backupData.encryptedRecoverySecretMnemonic), 'hex', 'base64');
            }

            // decrypt encryption secret
            if (usePassword) {
                secret = CryptoJS.AES.decrypt(backupData.passwordEncryptedSecretMnemonic, backupData.password).toString(CryptoJS.enc.Utf8);
            } else {
                secret = CryptoJS.AES.decrypt(backupData.encryptedRecoverySecretMnemonic, backupData.recoverySecretDecryptionKey).toString(CryptoJS.enc.Utf8);
            }

            if (!secret) {
                throw new Error("Could not decrypt secret with " + (usePassword ? "password" : "decryption key"));
            }

            // now finally decrypt the primary seed and convert to buffer (along with backup seed)
            primarySeed = new Buffer(CryptoJS.AES.decrypt(backupData.encryptedPrimaryMnemonic, secret).toString(CryptoJS.enc.Utf8), 'base64');

            if (backupData.backupMnemonic) {
                backupSeed = new Buffer(bip39.mnemonicToEntropy(backupData.backupMnemonic), 'hex');
            }

        break;

        case 3:
            // convert mnemonics to hex (bip39) and then base64 for decryption
            backupData.encryptedPrimaryMnemonic = EncryptionMnemonic.decode(backupData.encryptedPrimaryMnemonic);
            if (usePassword) {
                backupData.passwordEncryptedSecretMnemonic = EncryptionMnemonic.decode(backupData.passwordEncryptedSecretMnemonic);
            } else {
                backupData.encryptedRecoverySecretMnemonic = EncryptionMnemonic.decode(backupData.encryptedRecoverySecretMnemonic);
            }
github monkybrain / progressive-web-wallet / js / wallet.js View on Github external
module.exports.decryptPrivateKey = function(encryptedKey, password) {

  // Decrypt private key and convert it to hex string
  return CryptoJS.AES.decrypt(encryptedKey, password).toString(CryptoJS.enc.Utf8)

}
github blocktrail / blocktrail-sdk-nodejs / lib / wallet.js View on Github external
options.encryptedSecret = typeof options.encryptedSecret !== "undefined" ? options.encryptedSecret : self.encryptedSecret;

        if (options.secret) {
            self.secret = options.secret;
        }

        if (options.primaryPrivateKey) {
            throw new blocktrail.WalletDecryptError("specifying primaryPrivateKey has been deprecated");
        }

        if (options.primarySeed) {
            self.primarySeed = options.primarySeed;
        } else if (options.secret) {
            try {
                self.primarySeed = new Buffer(
                    CryptoJS.AES.decrypt(CryptoJS.format.OpenSSL.parse(options.encryptedPrimarySeed), self.secret).toString(CryptoJS.enc.Utf8), 'base64');
                if (!self.primarySeed.length) {
                    throw new Error();
                }
            } catch (e) {
                throw new blocktrail.WalletDecryptError("Failed to decrypt primarySeed");
            }

        } else {
            // avoid conflicting options
            if (options.passphrase && options.password) {
                throw new blocktrail.WalletCreateError("Can't specify passphrase and password");
            }
            // normalize passphrase/password
            options.passphrase = options.passphrase || options.password;

            try {
github skyway / skyway-peer-authentication-samples / nodejs / sample.js View on Github external
function calculateAuthToken(peerId, timestamp) {
  // calculate the auth token hash
  const hash = CryptoJS.HmacSHA256(`${timestamp}:${credentialTTL}:${peerId}`, secretKey);

  // convert the hash to a base64 string
  return CryptoJS.enc.Base64.stringify(hash);
}
github cyverse / troposphere / troposphere / static / js / models / Image.js View on Github external
parse: function(attributes) {
        // todo: move this feature into ImageBookmarksStore
        attributes.isFavorited = true; //response.is_bookmarked;
        attributes.start_date = moment(attributes.start_date);
        attributes.end_date = moment(attributes.end_date); // might be null, which is an Invalid Date
        attributes.description = attributes.description || "";
        attributes.uuid_hash =
            attributes.uuid_hash ||
            CryptoJS.MD5(attributes.uuid.toString()).toString();

        return attributes;
    },
github AnomalyInnovations / serverless-stack-demo-client / src / libs / sigV4Client.js View on Github external
function hash(value) {
    return SHA256(value); // eslint-disable-line
  }
github kndt84 / aws-api-gateway-client / src / lib / apiGatewayCore / sigV4Client.js View on Github external
function hash(value) {
    return SHA256(value); // eslint-disable-line
  }