На главную Наши проекты:
Журнал   ·   Discuz!ML   ·   Wiki   ·   DRKB   ·   Помощь проекту
ПРАВИЛА FAQ Помощь Участники Календарь Избранное RSS
msm.ru
! ПРАВИЛА РАЗДЕЛА · FAQ раздела Delphi · Книги по Delphi
Пожалуйста, выделяйте текст программы тегом [сode=pas] ... [/сode]. Для этого используйте кнопку [code=pas] в форме ответа или комбобокс, если нужно вставить код на языке, отличном от Дельфи/Паскаля.
Следующие вопросы задаются очень часто, подробно разобраны в FAQ и, поэтому, будут безжалостно удаляться:
1. Преобразовать переменную типа String в тип PChar (PAnsiChar)
2. Как "свернуть" программу в трей.
3. Как "скрыться" от Ctrl + Alt + Del (заблокировать их и т.п.)
4. Как прочитать список файлов, поддиректорий в директории?
5. Как запустить программу/файл?
... (продолжение следует) ...

Вопросы, подробно описанные во встроенной справочной системе Delphi, не несут полезной тематической нагрузки, поэтому будут удаляться.
Запрещается создавать темы с просьбой выполнить какую-то работу за автора темы. Форум является средством общения и общего поиска решения. Вашу работу за Вас никто выполнять не будет.


Внимание
Попытки открытия обсуждений реализации вредоносного ПО, включая различные интерпретации спам-ботов, наказывается предупреждением на 30 дней.
Повторная попытка - 60 дней. Последующие попытки бан.
Мат в разделе - бан на три месяца...
Модераторы: jack128, D[u]fa, Shaggy, Rouse_
  
> Протокол аутентификации adb , Delphi code need
    У моих мастеров хорошего дня. Я просматривал эту тему время от времени в течение года, но не смог перевести эту функцию. Моя цель - общаться с устройствами Android, но без adb.exe. Я перевел все виды функций, написанных в Google, но я не смог перевести эту функцию в своего рода мастеров. Я провел много исследований, но я не могу дать своего рода решение, я жду вашей помощи. Есть ресурсы на разных языках, но я не смог перевести. Я не делюсь ни одним источником, так как код Delphi не работает.



    Гугл написал, расскажи об аутентификации.

    ExpandedWrap disabled
      --- AUTH(type, 0, "data") ----------------------------------------------
      Command constant: A_AUTH
      The AUTH message informs the recipient that authentication is required to
      connect to the sender. If type is TOKEN(1), data is a random token that
      the recipient can sign with a private key. The recipient replies with an
      AUTH packet where type is SIGNATURE(2) and data is the signature. If the
      signature verification succeeds, the sender replies with a CONNECT packet.
      If the signature verification fails, the sender replies with a new AUTH
      packet and a new random token, so that the recipient can retry signing
      with a different private key.
      Once the recipient has tried all its private keys, it can reply with an
      AUTH packet where type is RSAPUBLICKEY(3) and data is the public key. If
      possible, an on-screen confirmation may be displayed for the user to
      confirm they want to install the public key on the device.



    Google Link : https://android.googlesource.com/platform/s...db/protocol.txt


    Устройство отправляет adb.exe cnxn. Он посылает ему специальный код на устройстве.

    user posted image


    Здесь adb.exe отвечает. Вероятно, с ша 256.

    user posted image

    Это ответ.

    user posted image

    Теперь устройство запрашивает разрешение с экрана, и adb .exe отправляет этот код.

    user posted image

    Если вы разрешите это на экране, устройство ответит.

    user posted image

    ExpandedWrap disabled
      # Copyright 2014 Google Inc. All rights reserved.
      #
      # Licensed under the Apache License, Version 2.0 (the "License");
      # you may not use this file except in compliance with the License.
      # You may obtain a copy of the License at
      #
      #     http://www.apache.org/licenses/LICENSE-2.0
      #
      # Unless required by applicable law or agreed to in writing, software
      # distributed under the License is distributed on an "AS IS" BASIS,
      # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      # See the License for the specific language governing permissions and
      # limitations under the License.
       
      import rsa
       
      from pyasn1.codec.der import decoder
      from pyasn1.type import univ
      from rsa import pkcs1
       
       
      # python-rsa lib hashes all messages it signs. ADB does it already, we just
      # need to slap a signature on top of already hashed message. Introduce "fake"
      # hashing algo for this.
      class _Accum(object):
          def __init__(self):
              self._buf = b''
       
          def update(self, msg):
              self._buf += msg
       
          def digest(self):
              return self._buf
       
       
      pkcs1.HASH_METHODS['SHA-1-PREHASHED'] = _Accum
      pkcs1.HASH_ASN1['SHA-1-PREHASHED'] = pkcs1.HASH_ASN1['SHA-1']
       
       
      def _load_rsa_private_key(pem):
          """PEM encoded PKCS#8 private key -> rsa.PrivateKey."""
          # ADB uses private RSA keys in pkcs#8 format. 'rsa' library doesn't support
          # them natively. Do some ASN unwrapping to extract naked RSA key
          # (in der-encoded form). See https://www.ietf.org/rfc/rfc2313.txt.
          # Also http://superuser.com/a/606266.
          try:
              der = rsa.pem.load_pem(pem, 'PRIVATE KEY')
              keyinfo, _ = decoder.decode(der)
              if keyinfo[1][0] != univ.ObjectIdentifier(
                      '1.2.840.113549.1.1.1'):  # pragma: no cover
                  raise ValueError('Not a DER-encoded OpenSSL private RSA key')
              private_key_der = keyinfo[2].asOctets()
          except IndexError:  # pragma: no cover
              raise ValueError('Not a DER-encoded OpenSSL private RSA key')
          return rsa.PrivateKey.load_pkcs1(private_key_der, format='DER')
       
       
      class PythonRSASigner(object):
          """Implements adb_protocol.AuthSigner using http://stuvel.eu/rsa."""
       
          @classmethod
          def FromRSAKeyPath(cls, rsa_key_path):
              with open(rsa_key_path + '.pub') as f:
                  pub = f.read()
              with open(rsa_key_path) as f:
                  priv = f.read()
              return cls(pub, priv)
       
          def __init__(self, pub=None, priv=None):
              self.priv_key = _load_rsa_private_key(priv)
              self.pub_key = pub
       
          def Sign(self, data):
              return rsa.sign(data, self.priv_key, 'SHA-1-PREHASHED')
       
          def GetPublicKey(self):
              return self.pub_key


    Python link : https://github.com/google/python-adb/tree/master/adb
    0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
    0 пользователей:


    Рейтинг@Mail.ru
    [ Script execution time: 0,0201 ]   [ 16 queries used ]   [ Generated: 16.04.24, 23:30 GMT ]