Konuyu Oyla:
  • Derecelendirme: 0/5 - 0 oy
  • 1
  • 2
  • 3
  • 4
  • 5
Adb auth protokolü (1 yıldır çözemedim)
#1
Ustalarım iyi günler. 1 yıldır ara ara bu konuya bakıyorum ama bir türlü bu foksiyonu çeviremedim. Amacım android cihazlarla iletişim kurmak ama adb.exe olmadan. Googlede yazan her türlü foksiyonu çevirdim ama bir türlü bu foksiyonu çeviremedim ustalarım. Çok araştırma yaptım ama bir türlü çözüm sağlayamadım sizlerden yardım bekliyorum. Farklı dillerde kaynak var ama bir türlü çevirme yapamadım. Delphi kodu olarak hiç bir kaynak çalışmadığı için paylaşmıyorum.



Google auth hakkında söyle yazmış.




--- 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 : Linkleri Görebilmeniz İçin Üye Olmanız Gerekiyor. Üye Olabilmek İçin Lütfen Buraya Tıklayınız.


Cihaza adb.exe cnxn gönderiyor. Cihazda ona özel bir kod gönderiyor.

jqWODj.png


Burada adb.exe cevap veriyor. Muhtemelen sha 256 ile.

2O93lN.png

Cihaz böyle bir cevap veriyor.

BOAQdD.png


Şimdi cihazın ekranından izin istiyor ve adb .exe bu kodu gönderiyor.

Z5EBqk.png




Eğerki ekrandan izin veriseniz cihaz böyle bir cevap veriyor.

odkWm7.png


Python kodu  : 




# 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 linki : Linkleri Görebilmeniz İçin Üye Olmanız Gerekiyor. Üye Olabilmek İçin Lütfen Buraya Tıklayınız.


C++ kodu : 

/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * 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.
 */

#define TRACE_TAG AUTH

#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined(__linux__)
#include <sys/inotify.h>
#endif

#include <map>
#include <mutex>
#include <set>
#include <string>

#include <android-base/errors.h>
#include <android-base/file.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#include <crypto_utils/android_pubkey.h>
#include <openssl/base64.h>
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/sha.h>

#include "adb.h"
#include "adb_auth.h"
#include "adb_utils.h"
#include "sysdeps.h"
#include "transport.h"

static std::mutex& g_keys_mutex = *new std::mutex;
static std::map<std::string, std::shared_ptr<RSA>>& g_keys =
    *new std::map<std::string, std::shared_ptr<RSA>>;
static std::map<int, std::string>& g_monitored_paths = *new std::map<int, std::string>;

static std::string get_user_info() {
    LOG(INFO) << "get_user_info...";

    std::string hostname;
    if (getenv("HOSTNAME")) hostname = getenv("HOSTNAME");
#if !defined(_WIN32)
    char buf[64];
    if (hostname.empty() && gethostname(buf, sizeof(buf)) != -1) hostname = buf;
#endif
    if (hostname.empty()) hostname = "unknown";

    std::string username;
    if (getenv("LOGNAME")) username = getenv("LOGNAME");
#if !defined _WIN32 && !defined ADB_HOST_ON_TARGET
    if (username.empty() && getlogin()) username = getlogin();
#endif
    if (username.empty()) hostname = "unknown";

    return " " + username + "@" + hostname;
}

static bool write_public_keyfile(RSA* private_key, const std::string& private_key_path) {
    LOG(INFO) << "write_public_keyfile...";

    uint8_t binary_key_data[ANDROID_PUBKEY_ENCODED_SIZE];
    if (!android_pubkey_encode(private_key, binary_key_data, sizeof(binary_key_data))) {
        LOG(ERROR) << "Failed to convert to public key";
        return false;
    }

    size_t expected_length;
    if (!EVP_EncodedLength(&expected_length, sizeof(binary_key_data))) {
        LOG(ERROR) << "Public key too large to base64 encode";
        return false;
    }

    std::string content;
    content.resize(expected_length);
    size_t actual_length = EVP_EncodeBlock(reinterpret_cast<uint8_t*>(&content[0]), binary_key_data,
                                           sizeof(binary_key_data));
    content.resize(actual_length);

    content += get_user_info();

    std::string path(private_key_path + ".pub");
    if (!android::base::WriteStringToFile(content, path)) {
        PLOG(ERROR) << "Failed to write public key to '" << path << "'";
        return false;
    }

    return true;
}

static int generate_key(const std::string& file) {
    LOG(INFO) << "generate_key(" << file << ")...";

    mode_t old_mask;
    FILE *f = NULL;
    int ret = 0;

    EVP_PKEY* pkey = EVP_PKEY_new();
    BIGNUM* exponent = BN_new();
    RSA* rsa = RSA_new();
    if (!pkey || !exponent || !rsa) {
        LOG(ERROR) << "Failed to allocate key";
        goto out;
    }

    BN_set_word(exponent, RSA_F4);
    RSA_generate_key_ex(rsa, 2048, exponent, NULL);
    EVP_PKEY_set1_RSA(pkey, rsa);

    old_mask = umask(077);

    f = fopen(file.c_str(), "w");
    if (!f) {
        PLOG(ERROR) << "Failed to open " << file;
        umask(old_mask);
        goto out;
    }

    umask(old_mask);

    if (!PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL)) {
        D("Failed to write key");
        goto out;
    }

    if (!write_public_keyfile(rsa, file)) {
        D("Failed to write public key");
        goto out;
    }

    ret = 1;

out:
    if (f) fclose(f);
    EVP_PKEY_free(pkey);
    RSA_free(rsa);
    BN_free(exponent);
    return ret;
}

static std::string hash_key(RSA* key) {
    unsigned char* pubkey = nullptr;
    int len = i2d_RSA_PUBKEY(key, &pubkey);
    if (len < 0) {
        LOG(ERROR) << "failed to encode RSA public key";
        return std::string();
    }

    std::string result;
    result.resize(SHA256_DIGEST_LENGTH);
    SHA256(pubkey, len, reinterpret_cast<unsigned char*>(&result[0]));
    OPENSSL_free(pubkey);
    return result;
}

static bool read_key_file(const std::string& file) {
    LOG(INFO) << "read_key_file '" << file << "'...";

    std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(file.c_str(), "r"), fclose);
    if (!fp) {
        PLOG(ERROR) << "Failed to open '" << file << "'";
        return false;
    }

    RSA* key = RSA_new();
    if (!PEM_read_RSAPrivateKey(fp.get(), &key, nullptr, nullptr)) {
        LOG(ERROR) << "Failed to read key";
        RSA_free(key);
        return false;
    }

    std::lock_guard<std::mutex> lock(g_keys_mutex);
    std::string fingerprint = hash_key(key);
    if (g_keys.find(fingerprint) != g_keys.end()) {
        LOG(INFO) << "ignoring already-loaded key: " << file;
        RSA_free(key);
    } else {
        g_keys[fingerprint] = std::shared_ptr<RSA>(key, RSA_free);
    }

    return true;
}

static bool read_keys(const std::string& path, bool allow_dir = true) {
    LOG(INFO) << "read_keys '" << path << "'...";

    struct stat st;
    if (stat(path.c_str(), &st) != 0) {
        PLOG(ERROR) << "failed to stat '" << path << "'";
        return false;
    }

    if (S_ISREG(st.st_mode)) {
        return read_key_file(path);
    } else if (S_ISDIR(st.st_mode)) {
        if (!allow_dir) {
            // inotify isn't recursive. It would break expectations to load keys in nested
            // directories but not monitor them for new keys.
            LOG(WARNING) << "refusing to recurse into directory '" << path << "'";
            return false;
        }

        std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
        if (!dir) {
            PLOG(ERROR) << "failed to open directory '" << path << "'";
            return false;
        }

        bool result = false;
        while (struct dirent* dent = readdir(dir.get())) {
            std::string name = dent->d_name;

            // We can't use dent->d_type here because it's not available on Windows.
            if (name == "." || name == "..") {
                continue;
            }

            if (!android::base::EndsWith(name, ".adb_key")) {
                LOG(INFO) << "skipping non-adb_key '" << path << "/" << name << "'";
                continue;
            }

            result |= read_key_file((path + OS_PATH_SEPARATOR + name));
        }
        return result;
    }

    LOG(ERROR) << "unexpected type for '" << path << "': 0x" << std::hex << st.st_mode;
    return false;
}

static std::string get_user_key_path() {
    return adb_get_android_dir_path() + OS_PATH_SEPARATOR + "adbkey";
}

static bool get_user_key() {
    std::string path = get_user_key_path();
    if (path.empty()) {
        PLOG(ERROR) << "Error getting user key filename";
        return false;
    }

    struct stat buf;
    if (stat(path.c_str(), &buf) == -1) {
        LOG(INFO) << "User key '" << path << "' does not exist...";
        if (!generate_key(path)) {
            LOG(ERROR) << "Failed to generate new key";
            return false;
        }
    }

    return read_key_file(path);
}

static std::set<std::string> get_vendor_keys() {
    const char* adb_keys_path = getenv("ADB_VENDOR_KEYS");
    if (adb_keys_path == nullptr) {
        return std::set<std::string>();
    }

    std::set<std::string> result;
    for (const auto& path : android::base::Split(adb_keys_path, ENV_PATH_SEPARATOR_STR)) {
        result.emplace(path);
    }
    return result;
}

std::deque<std::shared_ptr<RSA>> adb_auth_get_private_keys() {
    std::deque<std::shared_ptr<RSA>> result;

    // Copy all the currently known keys.
    std::lock_guard<std::mutex> lock(g_keys_mutex);
    for (const auto& it : g_keys) {
        result.push_back(it.second);
    }

    // Add a sentinel to the list. Our caller uses this to mean "out of private keys,
    // but try using the public key" (the empty deque could otherwise mean this _or_
    // that this function hasn't been called yet to request the keys).
    result.push_back(nullptr);

    return result;
}

static int adb_auth_sign(RSA* key, const char* token, size_t token_size, char* sig) {
    if (token_size != TOKEN_SIZE) {
        D("Unexpected token size %zd", token_size);
        return 0;
    }

    unsigned int len;
    if (!RSA_sign(NID_sha1, reinterpret_cast<const uint8_t*>(token), token_size,
                  reinterpret_cast<uint8_t*>(sig), &len, key)) {
        return 0;
    }

    D("adb_auth_sign len=%d", len);
    return (int)len;
}

std::string adb_auth_get_userkey() {
    std::string path = get_user_key_path();
    if (path.empty()) {
        PLOG(ERROR) << "Error getting user key filename";
        return "";
    }
    path += ".pub";

    std::string content;
    if (!android::base::ReadFileToString(path, &content)) {
        PLOG(ERROR) << "Can't load '" << path << "'";
        return "";
    }
    return content;
}

int adb_auth_keygen(const char* filename) {
    return (generate_key(filename) == 0);
}

#if defined(__linux__)
static void adb_auth_inotify_update(int fd, unsigned fd_event, void*) {
    LOG(INFO) << "adb_auth_inotify_update called";
    if (!(fd_event & FDE_READ)) {
        return;
    }

    char buf[sizeof(struct inotify_event) + NAME_MAX + 1];
    while (true) {
        ssize_t rc = TEMP_FAILURE_RETRY(unix_read(fd, buf, sizeof(buf)));
        if (rc == -1) {
            if (errno == EAGAIN) {
                LOG(INFO) << "done reading inotify fd";
                break;
            }
            PLOG(FATAL) << "read of inotify event failed";
        }

        // The read potentially returned multiple events.
        char* start = buf;
        char* end = buf + rc;

        while (start < end) {
            inotify_event* event = reinterpret_cast<inotify_event*>(start);
            auto root_it = g_monitored_paths.find(event->wd);
            if (root_it == g_monitored_paths.end()) {
                LOG(FATAL) << "observed inotify event for unmonitored path, wd = " << event->wd;
            }

            std::string path = root_it->second;
            if (event->len > 0) {
                path += '/';
                path += event->name;
            }

            if (event->mask & (IN_CREATE | IN_MOVED_TO)) {
                if (event->mask & IN_ISDIR) {
                    LOG(INFO) << "ignoring new directory at '" << path << "'";
                } else {
                    LOG(INFO) << "observed new file at '" << path << "'";
                    read_keys(path, false);
                }
            } else {
                LOG(WARNING) << "unmonitored event for " << path << ": 0x" << std::hex
                             << event->mask;
            }

            start += sizeof(struct inotify_event) + event->len;
        }
    }
}

static void adb_auth_inotify_init(const std::set<std::string>& paths) {
    LOG(INFO) << "adb_auth_inotify_init...";

    int infd = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
    if (infd < 0) {
        PLOG(ERROR) << "failed to create inotify fd";
        return;
    }

    for (const std::string& path : paths) {
        int wd = inotify_add_watch(infd, path.c_str(), IN_CREATE | IN_MOVED_TO);
        if (wd < 0) {
            PLOG(ERROR) << "failed to inotify_add_watch on path '" << path;
            continue;
        }

        g_monitored_paths[wd] = path;
        LOG(INFO) << "watch descriptor " << wd << " registered for " << path;
    }

    fdevent* event = fdevent_create(infd, adb_auth_inotify_update, nullptr);
    fdevent_add(event, FDE_READ);
}
#endif

void adb_auth_init() {
    LOG(INFO) << "adb_auth_init...";

    if (!get_user_key()) {
        LOG(ERROR) << "Failed to get user key";
        return;
    }

    const auto& key_paths = get_vendor_keys();

#if defined(__linux__)
    adb_auth_inotify_init(key_paths);
#endif

    for (const std::string& path : key_paths) {
        read_keys(path.c_str());
    }
}

static void send_auth_publickey(atransport* t) {
    LOG(INFO) << "Calling send_auth_publickey";

    std::string key = adb_auth_get_userkey();
    if (key.empty()) {
        D("Failed to get user public key");
        return;
    }

    if (key.size() >= MAX_PAYLOAD_V1) {
        D("User public key too large (%zu B)", key.size());
        return;
    }

    apacket* p = get_apacket();
    memcpy(p->data, key.c_str(), key.size() + 1);

    p->msg.command = A_AUTH;
    p->msg.arg0 = ADB_AUTH_RSAPUBLICKEY;

    // adbd expects a null-terminated string.
    p->msg.data_length = key.size() + 1;
    send_packet(p, t);
}

void send_auth_response(const char* token, size_t token_size, atransport* t) {
    std::shared_ptr<RSA> key = t->NextKey();
    if (key == nullptr) {
        // No more private keys to try, send the public key.
        send_auth_publickey(t);
        return;
    }

    LOG(INFO) << "Calling send_auth_response";
    apacket* p = get_apacket();

    int ret = adb_auth_sign(key.get(), token, token_size, p->data);
    if (!ret) {
        D("Error signing the token");
        put_apacket(p);
        return;
    }

    p->msg.command = A_AUTH;
    p->msg.arg0 = ADB_AUTH_SIGNATURE;
    p->msg.data_length = ret;
    send_packet(p, t);
}


C++ Linki : Linkleri Görebilmeniz İçin Üye Olmanız Gerekiyor. Üye Olabilmek İçin Lütfen Buraya Tıklayınız.


Java kodu : 

package com.cgutman.adblib;
//w  ww  .  ja va2 s .co m
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.EncodedKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;

/**
 * This class encapsulates the ADB cryptography functions and provides
 * an interface for the storage and retrieval of keys.
 * @author Cameron Gutman
 */
public class AdbCrypto {
  
  /** An RSA keypair encapsulated by the AdbCrypto object */
  private KeyPair keyPair;
  
  /** The base 64 conversion interface to use */
  private AdbBase64 base64;
  
  /** The ADB RSA key length in bits */
  public static final int KEY_LENGTH_BITS = 2048;
  
  /** The ADB RSA key length in bytes */
  public static final int KEY_LENGTH_BYTES = KEY_LENGTH_BITS / 8;
  
  /** The ADB RSA key length in words */
  public static final int KEY_LENGTH_WORDS = KEY_LENGTH_BYTES / 4;
  
  /** The RSA signature padding as an int array */
  public static final int[] SIGNATURE_PADDING_AS_INT = new int[]
      {
        0x00,0x01,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
        0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
        0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
        0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
        0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
        0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
        0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
        0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
        0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
        0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
        0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
        0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
        0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
        0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
        0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
        0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
        0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,
        0x30,0x21,0x30,0x09,0x06,0x05,0x2b,0x0e,0x03,0x02,0x1a,0x05,0x00,
        0x04,0x14
      };
  
  /** The RSA signature padding as a byte array */
  public static byte[] SIGNATURE_PADDING;
  
  static {
    SIGNATURE_PADDING = new byte[SIGNATURE_PADDING_AS_INT.length];
    
    for (int i = 0; i < SIGNATURE_PADDING.length; i++)
      SIGNATURE_PADDING[i] = (byte)SIGNATURE_PADDING_AS_INT[i];
  }
  
  /**
   * Converts a standard RSAPublicKey object to the special ADB format
   * @param pubkey RSAPublicKey object to convert
   * @return Byte array containing the converted RSAPublicKey object
   */
  private static byte[] convertRsaPublicKeyToAdbFormat(RSAPublicKey pubkey)
  {
    /*
     * ADB literally just saves the RSAPublicKey struct to a file.
     * 
     * typedef struct RSAPublicKey {
         * int len; // Length of n[] in number of uint32_t
         * uint32_t n0inv;  // -1 / n[0] mod 2^32
         * uint32_t n[RSANUMWORDS]; // modulus as little endian array
         * uint32_t rr[RSANUMWORDS]; // R^2 as little endian array
         * int exponent; // 3 or 65537
         * } RSAPublicKey;
     */

    /* ------ This part is a Java-ified version of RSA_to_RSAPublicKey from adb_host_auth.c ------ */
    BigInteger r32, r, rr, rem, n, n0inv;
    
    r32 = BigInteger.ZERO.setBit(32);
    n = pubkey.getModulus();
    r = BigInteger.ZERO.setBit(KEY_LENGTH_WORDS * 32);
    rr = r.modPow(BigInteger.valueOf(2), n);
    rem = n.remainder(r32);
    n0inv = rem.modInverse(r32);
    
    int myN[] = new int[KEY_LENGTH_WORDS];
    int myRr[] = new int[KEY_LENGTH_WORDS];
    BigInteger res[];
    for (int i = 0; i < KEY_LENGTH_WORDS; i++)
    {
      res = rr.divideAndRemainder(r32);
      rr = res[0];
      rem = res[1];
      myRr[i] = rem.intValue();
      
      res = n.divideAndRemainder(r32);
      n = res[0];
      rem = res[1];
      myN[i] = rem.intValue();
    }

    /* ------------------------------------------------------------------------------------------- */
    
    ByteBuffer bbuf = ByteBuffer.allocate(524).order(ByteOrder.LITTLE_ENDIAN);

    
    bbuf.putInt(KEY_LENGTH_WORDS);
    bbuf.putInt(n0inv.negate().intValue());
    for (int i : myN)
      bbuf.putInt(i);
    for (int i : myRr)
      bbuf.putInt(i);
    
    bbuf.putInt(pubkey.getPublicExponent().intValue());
    return bbuf.array();
  }
  
  /**
   * Creates a new AdbCrypto object from a key pair loaded from files.
   * @param base64 Implementation of base 64 conversion interface required by ADB 
   * @param privateKey File containing the RSA private key
   * @param publicKey File containing the RSA public key
   * @return New AdbCrypto object
   * @throws IOException If the files cannot be read
   * @throws NoSuchAlgorithmException If an RSA key factory cannot be found
   * @throws InvalidKeySpecException If a PKCS8 or X509 key spec cannot be found
   */
  public static AdbCrypto loadAdbKeyPair(AdbBase64 base64, File privateKey, File publicKey) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException
  {
    AdbCrypto crypto = new AdbCrypto();
    
    int privKeyLength = (int)privateKey.length();
    int pubKeyLength = (int)publicKey.length();
    byte[] privKeyBytes = new byte[privKeyLength];
    byte[] pubKeyBytes = new byte[pubKeyLength];
    
    FileInputStream privIn = new FileInputStream(privateKey);
    FileInputStream pubIn = new FileInputStream(publicKey);
    
    privIn.read(privKeyBytes);
    pubIn.read(pubKeyBytes);
    
    privIn.close();
    pubIn.close();
    
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privKeyBytes);
    EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubKeyBytes);
    
    crypto.keyPair = new KeyPair(keyFactory.generatePublic(publicKeySpec),
        keyFactory.generatePrivate(privateKeySpec));
    crypto.base64 = base64;
    
    return crypto;
  }
  
  /**
   * Creates a new AdbCrypto object by generating a new key pair.
   * @param base64 Implementation of base 64 conversion interface required by ADB 
   * @return A new AdbCrypto object
   * @throws NoSuchAlgorithmException If an RSA key factory cannot be found
   */
  public static AdbCrypto generateAdbKeyPair(AdbBase64 base64) throws NoSuchAlgorithmException
  {
    AdbCrypto crypto = new AdbCrypto();

    KeyPairGenerator rsaKeyPg = KeyPairGenerator.getInstance("RSA");
    rsaKeyPg.initialize(KEY_LENGTH_BITS);
    
    crypto.keyPair = rsaKeyPg.genKeyPair();
    crypto.base64 = base64;
    
    return crypto;
  }
  
  /**
   * Signs the ADB SHA1 payload with the private key of this object.
   * @param payload SHA1 payload to sign
   * @return Signed SHA1 payload
   * @throws GeneralSecurityException If signing fails
   */
  public byte[] signAdbTokenPayload(byte[] payload) throws GeneralSecurityException
  {  
    Cipher c = Cipher.getInstance("RSA/ECB/NoPadding");
    
    c.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate());
    
    c.update(SIGNATURE_PADDING);
    
    return c.doFinal(payload);
  }
  
  /**
   * Gets the RSA public key in ADB format.
   * @return Byte array containing the RSA public key in ADB format.
   * @throws IOException If the key cannot be retrived
   */
  public byte[] getAdbPublicKeyPayload() throws IOException
  {
    byte[] convertedKey = convertRsaPublicKeyToAdbFormat((RSAPublicKey)keyPair.getPublic());
    StringBuilder keyString = new StringBuilder(720);
    
    /* The key is base64 encoded with a user@host suffix and terminated with a NUL */
    keyString.append(base64.encodeToString(convertedKey));
    keyString.append(" unknown@unknown");
    keyString.append('\0');
    
    return keyString.toString().getBytes("UTF-8");
  }
  
  /**
   * Saves the AdbCrypto's key pair to the specified files.
   * @param privateKey The file to store the encoded private key
   * @param publicKey The file to store the encoded public key
   * @throws IOException If the files cannot be written
   */
  public void saveAdbKeyPair(File privateKey, File publicKey) throws IOException
  {    
    FileOutputStream privOut = new FileOutputStream(privateKey);
    FileOutputStream pubOut = new FileOutputStream(publicKey);
    
    privOut.write(keyPair.getPrivate().getEncoded());
    pubOut.write(keyPair.getPublic().getEncoded());
    
    privOut.close();
    pubOut.close();
  }
}

Java Linki : Linkleri Görebilmeniz İçin Üye Olmanız Gerekiyor. Üye Olabilmek İçin Lütfen Buraya Tıklayınız.
Cevapla
#2
Güncel ustalarım.
Cevapla
#3
Konu güncel hala bir çözüm bulunamadı.
Cevapla
#4
Python fonksiyonu çalışıyorsa Python dilinde bir script haline getirip uygulaman ile onu kullan. İlla Delphi olması zorunda değil. Bazı durumlarda başka dillerde scriptler yazıp işlemlerimi hızlandırıyorum. Çalışan başka dilde bir kod varsa ortada 1 yıl uğraş vermek ne kadar doğru olmuş bilemiyorum.
Linkleri Görebilmeniz İçin Üye Olmanız Gerekiyor. Üye Olabilmek İçin Lütfen Buraya Tıklayınız.
Cevapla
#5
(09-08-2019, Saat: 11:51)Halil Han Badem Adlı Kullanıcıdan Alıntı: Linkleri Görebilmeniz İçin Üye Olmanız Gerekiyor. Üye Olabilmek İçin Lütfen Buraya Tıklayınız.Python fonksiyonu çalışıyorsa Python dilinde bir script haline getirip uygulaman ile onu kullan. İlla Delphi olması zorunda değil. Bazı durumlarda başka dillerde scriptler yazıp işlemlerimi hızlandırıyorum. Çalışan başka dilde bir kod varsa ortada 1 yıl uğraş vermek ne kadar doğru olmuş bilemiyorum.

Bir yil gece gunduz bununla ugrasmadim tabikide ara ara baktim. O zaman adb.exe kullanmaktan bir farki kalmayacak. Adb.exe ne kadar iyi yazilirsa yazilsin malasef stabil olmuyor. O yüzden delphi ile yazmam gerekli. Zaten çoğu foksiyonu yazdim, read write connect hepsini yazdim bir tek auth kaldi.
Cevapla
#6
Merhaba,
Android platformu için harici bir bileşen seti var. Bu konu ile ilgili mi bilmiyorum.
Linkleri Görebilmeniz İçin Üye Olmanız Gerekiyor. Üye Olabilmek İçin Lütfen Buraya Tıklayınız.
While true do; Hayat döngüsü, kısır değildir! Yapılan bir yanlış, o döngünün dışına çıkmanızı sağlayacaktır.
WWW
Cevapla
#7
(09-08-2019, Saat: 16:33)Fesih ARSLAN Adlı Kullanıcıdan Alıntı: Linkleri Görebilmeniz İçin Üye Olmanız Gerekiyor. Üye Olabilmek İçin Lütfen Buraya Tıklayınız.Merhaba,
Android platformu için harici bir bileşen seti var. Bu konu ile ilgili mi bilmiyorum.
Linkleri Görebilmeniz İçin Üye Olmanız Gerekiyor. Üye Olabilmek İçin Lütfen Buraya Tıklayınız.

Cevap verdiğiniz için teşekkür ederim hocam. Bu tamamen farklı bir konu hocam malesef Sad
Cevapla
#8
Güncel sorun hala devam ediyor.... Sad
Cevapla
#9
Fonksiyonlar çevrildiğinde, problemi çözeceğinden, ya da işe yaracağından emin misiniz ?
WWW
Cevapla
#10
(16-08-2019, Saat: 15:02)ismailkocacan Adlı Kullanıcıdan Alıntı: Linkleri Görebilmeniz İçin Üye Olmanız Gerekiyor. Üye Olabilmek İçin Lütfen Buraya Tıklayınız.Fonksiyonlar çevrildiğinde, problemi çözeceğinden, ya da işe yaracağından emin misiniz ?

Evet ben zaten diğer foksiyonları yaptım bir tek auth yapamadım. Auth hesaplaması olsa yeterli gelecektir.
Cevapla


Konu ile Alakalı Benzer Konular
Konular Yazar Yorumlar Okunma Son Yorum
  winusb protokolü hakkında yardım seci20 1 559 31-05-2018, Saat: 10:26
Son Yorum: SimaWB
  [Çözüldü] UTF8ToString çözemedim.. Lord_Ares 14 2.700 05-04-2017, Saat: 13:36
Son Yorum: Lord_Ares



Konuyu Okuyanlar: 1 Ziyaretçi