alik0211 / mtproto-core

Telegram API JS (MTProto) client library for Node.js and browser
https://mtproto-core.js.org
GNU General Public License v3.0
625 stars 111 forks source link

How to set a new password using api.call('account.updatePasswordSettings') #287

Open MyZest opened 11 months ago

MyZest commented 11 months ago

https://core.telegram.org/constructor/account.passwordInputSetting

Excuse me, the type of new_password_hash for setting a new password is flags.0?bytes, which is converted into JavaScript, how to express it?

MyZest commented 11 months ago

import bigInt from 'big-integer';
import {
  concatBytes,
  bytesToBigInt,
} from '@mtproto/core/src/utils/common/index.js';
import crypto from 'crypto';

export async function getVParams(api, password) {
  const getPasswordConf = await api.call('account.getPassword');
  const { new_algo = {} } = getPasswordConf;

  const {
    g, p, salt1, salt2 
  } = new_algo;

  const SH = (data, salt) => {
    const hash = crypto.createHash('sha256');
    hash.update(concatBytes(salt, data, salt));
    return hash.digest();
  };

  const PH1 = (password, salt1, salt2) => {
    const hash1 = SH(SH(password, salt1), salt2);
    return hash1;
  };

  const PH2 = (password, salt1, salt2) => {
    const ph1Result = PH1(password, salt1, salt2);
    const pbkdf2Result = crypto.pbkdf2Sync(
      ph1Result,
      salt1,
      100000,
      32,
      'sha256'
    );
    return SH(pbkdf2Result, salt2);
  };

  const encoder = new TextEncoder();

  const gBigInt = bigInt(g);
  const pBigInt = bytesToBigInt(p);
  const x = PH2(encoder.encode(password), salt1, salt2);
  const xBigInt = bytesToBigInt(x);
  const vBigInt = gBigInt.modPow(xBigInt, pBigInt);
  console.log('vBigInt:', vBigInt);
  const new_password_hash = crypto
    .createHash('sha256')
    .update(vBigInt.toString())
    .digest();
  // 将 Buffer 转换为 Uint8Array
  const new_password_hash_uint8 = new Uint8Array(new_password_hash.buffer);
  console.log('new_password_hash:', new_password_hash);
  return {
    ...getPasswordConf,
    new_password_hash: new_password_hash_uint8,
  };
}
MyZest commented 11 months ago

{ "code": 400, "msg": "NEW_SALT_INVALID" } or { "code": 400, "msg": "NEW_PASSWORD_BAD" }

MyZest commented 11 months ago

please help me