AES-шифр между узлом Crypto и CryptoJS - PullRequest
0 голосов
/ 20 марта 2020

Я пытаюсь зашифровать данные в Auth0, используя Crypto , а затем расшифровать в моем приложении Vue, используя Crypto JS.

Я проверил, что пароль и IV, которые используются в функции шифрования, совпадают с тем, что используется в функции дешифрования. Я также проверил, что выходные данные функции шифрования передаются функции дешифрования

Текущая проблема, с которой я столкнулся, заключается в том, что я не могу получить ожидаемый ответ от моей функции дешифрования. В настоящее время в приведенном ниже коде окончательное возвращение из decrypt представляет собой пустую строку

Я следовал инструкциям auth0 здесь для шифрования.

ФУНКЦИЯ ENCRYPT ON AUTH0

  const namespace = 'http://localhost:8080/';
  const random = randomString(16, 'AN');
  const client_iv = context.clientID.substring(0,16);

  user.app_metadata = user.app_metadata || {};
  user.app_metadata.random = random;

  /* The keys below are sent to the Vue front end to decrypt */
  context.idToken[namespace + 'ENCRYPT_PASSWORD'] = user.app_metadata.random;
  context.idToken[namespace +'jwt_secret'] = encrypt(user.app_metadata.dashboard.jwt_secret);


  auth0.users.updateUserMetadata(user.user_id, user.user_metadata)
    .then(function(){
        callback(null, user, context);
    })
    .catch(function(err){
        callback(err);
    });

  function encrypt(data) {
     var decodeKey = crypto.createHash('sha256')
       .update(random, 'utf8').digest('base64').substr(0, 32);

    /* VERIFIED the keys being used in encrypt MATCH w
    console.log("Decode Key", decodeKey); 
    console.log("encrypt IV = " , client_iv); function

    var cipher = crypto.createCipheriv('aes-256-cbc', decodeKey, client_iv);
    return cipher.update(JSON.stringify(data || {}), 'utf8', 'base64') + cipher.final('base64');
  }

  function randomString(len, an) {
  an = an && an.toLowerCase();
  var str = "",
    i = 0,
    min = an === "a" ? 10 : 0,
    max = an === "n" ? 10 : 62;
  for (; i++ < len;) {
    var r = Math.random() * (max - min) + min << 0;
    str += String.fromCharCode(r += r > 9 ? r < 36 ? 55 : 61 : 48);
  }
  return str;
}

}

ОТКЛЮЧИТЬ ФУНКЦИЮ НА VUE APP

function decrypt (data, ENCRYPT_IV, ENCRYPT_PASSWORD) {
  if (!data) {
    return {}
  }
  let key = CryptoJS.SHA256(ENCRYPT_PASSWORD)
  let encodeKey = CryptoJS.enc.Base64.stringify(key).substr(0, 32)

  /**
   * The Keys Below Match Whats Being Used in Auth0
   **/
  console.log('encodeKey  = ', encodeKey)
  console.log('ENCRYPT_IV = ', ENCRYPT_IV)
  console.log('Encrypted Data = ', data) // Matches the response from auth0 encrypt function

  /**
   * Auth0 Returns Message in Base64 format
   * Return From Auth0 : return cipher.update(JSON.stringify(data || {}), 'utf8', 'base64') + cipher.final('base64');
   **/

  /* Convert base64 to word array object */
  let payloadWords = CryptoJS.enc.Base64.parse(data)
  /* Convert Base64 Word Array to String */
  let payloadB64 = CryptoJS.enc.Base64.stringify(payloadWords)
  /* Convert Base64 string to utf8 string */
  let payloadString = payloadB64.toString(CryptoJS.enc.Utf8)

  var cipher = CryptoJS.AES.decrypt(payloadString, encodeKey, { iv: ENCRYPT_IV, mode: CryptoJS.mode.CBC })

  /**
   *  Cipher returns Word Array -- Convert to String
  **/
  let parseData = CryptoJS.enc.Utf8.parse(cipher)
  return CryptoJS.enc.Utf8.stringify(parseData)
}
...