Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'crypto-js' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
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:
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),
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)
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);
}
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)
}
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 {
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);
}
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;
},
function hash(value) {
return SHA256(value); // eslint-disable-line
}
function hash(value) {
return SHA256(value); // eslint-disable-line
}