Bitcoin Forum
June 05, 2024, 10:45:49 AM *
News: Latest Bitcoin Core release: 27.0 [Torrent]
 
   Home   Help Search Login Register More  
Pages: [1]
  Print  
Author Topic: Как получить ключи биткоин в HEX из сида  (Read 134 times)
Sanka555 (OP)
Member
**
Offline Offline

Activity: 96
Merit: 36


View Profile
November 02, 2022, 08:50:33 AM
 #1

у меня есть код на Java. С его помощью я из сида получаю адреса биткоин в формате Wif.
А мне нужно чтобы он выдавал вместо адресов ключи, причем в HEX

Подскажите пожалуйста как это сделать?


      
Code:
byte[] seed = PBKDF2SHA512.derive(seedCode, "mnemonic", 2048, 64);
DeterministicKey deterministicKey = HDKeyDerivation.createMasterPrivateKey(seed);
deterministicKey = HDKeyDerivation.deriveChildKey(deterministicKey, new ChildNumber(84, true));
deterministicKey = HDKeyDerivation.deriveChildKey(deterministicKey, new ChildNumber(0, true));
deterministicKey = HDKeyDerivation.deriveChildKey(deterministicKey, new ChildNumber(0, true));
deterministicKey = HDKeyDerivation.deriveChildKey(deterministicKey, new ChildNumber(0, false));
for (int i = 0; i <= 5; i++) {
temp = (Address.fromKey(MainNetParams.get(),
HDKeyDerivation.deriveChildKey(deterministicKey, new ChildNumber(i, false)),
Script.ScriptType.P2WPKH)).toString();

outputMap.put(temp, seedCode);
}
witcher_sense
Legendary
*
Offline Offline

Activity: 2366
Merit: 4372


🔐BitcoinMessage.Tools🔑


View Profile WWW
November 02, 2022, 03:09:53 PM
 #2

Если вам нужен код написанный на Java, то логично было бы взять основную имплепентацию протокола биткоина, написанного именно на Java. Я не эксперт в этой области, но могу посоветовать присмотреться к этой библиотеке: https://github.com/bitcoinj/bitcoinj/blob/master/core/src/main/java/org/bitcoinj/crypto/HDKeyDerivation.java Тут есть все необходимые функции для деривации ключей, думаю что и в нужном вам формате там тоже найдутся. Только вопрос зачем вам нужно если не для целей разработки. Генерировать ключи в терминале, если еще и на подключенном к интернету компьютеру, не очень безопасно и может привести к потере средств.

█▀▀▀











█▄▄▄
▀▀▀▀▀▀▀▀▀▀▀
e
▄▄▄▄▄▄▄▄▄▄▄
█████████████
████████████▄███
██▐███████▄█████▀
█████████▄████▀
███▐████▄███▀
████▐██████▀
█████▀█████
███████████▄
████████████▄
██▄█████▀█████▄
▄█████████▀█████▀
███████████▀██▀
████▀█████████
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
c.h.
▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
▀▀▀█











▄▄▄█
▄██████▄▄▄
█████████████▄▄
███████████████
███████████████
███████████████
███████████████
███░░█████████
███▌▐█████████
█████████████
███████████▀
██████████▀
████████▀
▀██▀▀
Sanka555 (OP)
Member
**
Offline Offline

Activity: 96
Merit: 36


View Profile
November 02, 2022, 04:27:11 PM
 #3

да я совсем в этом зеленая. мне б пару строчек которые делают то что надо и все .
witcher_sense
Legendary
*
Offline Offline

Activity: 2366
Merit: 4372


🔐BitcoinMessage.Tools🔑


View Profile WWW
November 03, 2022, 12:56:12 AM
Merited by xandry (2)
 #4

да я совсем в этом зеленая. мне б пару строчек которые делают то что надо и все .
Так это будет не паоу строчек: сначала там сид генерируется, потом расширенный приватный ключ и уже из него генерируются остальные приватные ключи по мере необходимости. Код что я сбросил выше содержит необходимые строки. Могу скопировать их сюда, если вам так удобнее:

Code:
public static DeterministicKey createMasterPrivateKey(byte[] seed) throws HDDerivationException {
        checkArgument(seed.length > 8, "Seed is too short and could be brute forced");
        // Calculate I = HMAC-SHA512(key="Bitcoin seed", msg=S)
        byte[] i = HDUtils.hmacSha512(HDUtils.createHmacSha512Digest("Bitcoin seed".getBytes()), seed);
        // Split I into two 32-byte sequences, Il and Ir.
        // Use Il as master secret key, and Ir as master chain code.
        checkState(i.length == 64, i.length);
        byte[] il = Arrays.copyOfRange(i, 0, 32);
        byte[] ir = Arrays.copyOfRange(i, 32, 64);
        Arrays.fill(i, (byte)0);
        DeterministicKey masterPrivKey = createMasterPrivKeyFromBytes(il, ir);
        Arrays.fill(il, (byte)0);
        Arrays.fill(ir, (byte)0);
        // Child deterministic keys will chain up to their parents to find the keys.
        masterPrivKey.setCreationTimeSeconds(Utils.currentTimeSeconds());
        return masterPrivKey;
    }

    /**
     * @throws HDDerivationException if privKeyBytes is invalid (not between 0 and n inclusive).
     */
    public static DeterministicKey createMasterPrivKeyFromBytes(byte[] privKeyBytes, byte[] chainCode) throws HDDerivationException {
        BigInteger priv = ByteUtils.bytesToBigInteger(privKeyBytes);
        assertNonZero(priv, "Generated master key is invalid.");
        assertLessThanN(priv, "Generated master key is invalid.");
        return new DeterministicKey(HDPath.m(), chainCode, priv, null);
    }

    public static DeterministicKey createMasterPubKeyFromBytes(byte[] pubKeyBytes, byte[] chainCode) {
        return new DeterministicKey(HDPath.M(), chainCode, new LazyECPoint(ECKey.CURVE.getCurve(), pubKeyBytes), null, null);
    }

    /**
     * Derives a key given the "extended" child number, ie. the 0x80000000 bit of the value that you
     * pass for {@code childNumber} will determine whether to use hardened derivation or not.
     * Consider whether your code would benefit from the clarity of the equivalent, but explicit, form
     * of this method that takes a {@code ChildNumber} rather than an {@code int}, for example:
     * {@code deriveChildKey(parent, new ChildNumber(childNumber, true))}
     * where the value of the hardened bit of {@code childNumber} is zero.
     */
    public static DeterministicKey deriveChildKey(DeterministicKey parent, int childNumber) {
        return deriveChildKey(parent, new ChildNumber(childNumber));
    }

    /**
     * Derives a key of the "extended" child number, ie. with the 0x80000000 bit specifying whether to use
     * hardened derivation or not. If derivation fails, tries a next child.
     */
    public static DeterministicKey deriveThisOrNextChildKey(DeterministicKey parent, int childNumber) {
        int nAttempts = 0;
        ChildNumber child = new ChildNumber(childNumber);
        boolean isHardened = child.isHardened();
        while (nAttempts < MAX_CHILD_DERIVATION_ATTEMPTS) {
            try {
                child = new ChildNumber(child.num() + nAttempts, isHardened);
                return deriveChildKey(parent, child);
            } catch (HDDerivationException ignore) { }
            nAttempts++;
        }
        throw new HDDerivationException("Maximum number of child derivation attempts reached, this is probably an indication of a bug.");

    }

    /**
     * Generate an infinite stream of {@link DeterministicKey}s from the given parent and index.
     * <p>
     * Note: Use {@link Stream#limit(long)} to get the desired number of keys.
     * @param parent The parent key
     * @param childNumber The index of the first child to supply/generate
     * @return A stream of {@code DeterministicKey}s
     */
    public static Stream<DeterministicKey> generate(DeterministicKey parent, int childNumber) {
        return Stream.generate(new KeySupplier(parent, childNumber));
    }

    /**
     * @throws HDDerivationException if private derivation is attempted for a public-only parent key, or
     * if the resulting derived key is invalid (eg. private key == 0).
     */
    public static DeterministicKey deriveChildKey(DeterministicKey parent, ChildNumber childNumber) throws HDDerivationException {
        if (!parent.hasPrivKey())
            return deriveChildKeyFromPublic(parent, childNumber, PublicDeriveMode.NORMAL);
        else
            return deriveChildKeyFromPrivate(parent, childNumber);
    }

    public static DeterministicKey deriveChildKeyFromPrivate(DeterministicKey parent, ChildNumber childNumber)
            throws HDDerivationException {
        RawKeyBytes rawKey = deriveChildKeyBytesFromPrivate(parent, childNumber);
        return new DeterministicKey(parent.getPath().extend(childNumber), rawKey.chainCode,
                ByteUtils.bytesToBigInteger(rawKey.keyBytes), parent);
    }

    public static RawKeyBytes deriveChildKeyBytesFromPrivate(DeterministicKey parent,
                                                              ChildNumber childNumber) throws HDDerivationException {
        checkArgument(parent.hasPrivKey(), "Parent key must have private key bytes for this method.");
        byte[] parentPublicKey = parent.getPubKeyPoint().getEncoded(true);
        checkState(parentPublicKey.length == 33, "Parent pubkey must be 33 bytes, but is " + parentPublicKey.length);
        ByteBuffer data = ByteBuffer.allocate(37);
        if (childNumber.isHardened()) {
            data.put(parent.getPrivKeyBytes33());
        } else {
            data.put(parentPublicKey);
        }
        data.putInt(childNumber.i());
        byte[] i = HDUtils.hmacSha512(parent.getChainCode(), data.array());
        checkState(i.length == 64, i.length);
        byte[] il = Arrays.copyOfRange(i, 0, 32);
        byte[] chainCode = Arrays.copyOfRange(i, 32, 64);
        BigInteger ilInt = ByteUtils.bytesToBigInteger(il);
        assertLessThanN(ilInt, "Illegal derived key: I_L >= n");
        final BigInteger priv = parent.getPrivKey();
        BigInteger ki = priv.add(ilInt).mod(ECKey.CURVE.getN());
        assertNonZero(ki, "Illegal derived key: derived private key equals 0.");
        return new RawKeyBytes(ki.toByteArray(), chainCode);
    }


Но я не совсем понимаю для каких целей вам это нужно. Быструю конвертацию сид фразы можно провести и без этих танцев с бубном. Есть готовые решения типа https://iancoleman.io/bip39/ или https://www.bitaddress.org/ где из сид фразы можно сгенерировать всю необходимую информацию в нужном формате. Если вам нужен код на Java, то погуглите биткоин кошельки, написанные на этом языке и там должен быть необходимый код.

█▀▀▀











█▄▄▄
▀▀▀▀▀▀▀▀▀▀▀
e
▄▄▄▄▄▄▄▄▄▄▄
█████████████
████████████▄███
██▐███████▄█████▀
█████████▄████▀
███▐████▄███▀
████▐██████▀
█████▀█████
███████████▄
████████████▄
██▄█████▀█████▄
▄█████████▀█████▀
███████████▀██▀
████▀█████████
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
c.h.
▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
▀▀▀█











▄▄▄█
▄██████▄▄▄
█████████████▄▄
███████████████
███████████████
███████████████
███████████████
███░░█████████
███▌▐█████████
█████████████
███████████▀
██████████▀
████████▀
▀██▀▀
Pages: [1]
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.19 | SMF © 2006-2009, Simple Machines Valid XHTML 1.0! Valid CSS!