- Hex to bitcoin address
- About
- Как создать адрес биткоин-кошелька с помощью закрытого ключа
- Криптография с использованием эллиптической кривой
- Шифрование открытого ключа
- Добавление сетевого байта
- Контрольная сумма
- Получение адреса
- Вывод
- Hex to bitcoin address
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
Hex to bitcoin address
Hash SHA-256 «CoinAddressGeneratorV3.1.0.jar» = 5f5fa204b1d5505c3056a6432f39ad2628aff47ffcbc73494e566757bce08e60
The Coin-AddressGenerator creates a private key in Bitcoin Wallet Import Format WIF, as well as the associated coin address and public key. A paper wallet with QR code can be created and printed out.
This is a Java application, so you need to install Java!
Start the program
The «Coin_Address_Generator.jar» file is located in the «release» folder. You can start this under Windows if Java is installed simply by double-clicking. On Linux, type in the console: java -jar CoinAddressGeneratorV3.1.0.jar
The project was created with eclipse. You can either import it back into eclipse or use the java source files. All necessary source files are in the src folder. To import to eclipse go to File / Open Projects from File System, select the ZIP archive, finish! All required libraries are already included in the project (in the lib folder). So you can start the project directly.
There is a large list of coins to choose from that can be imported. However, some coins may not work properly because the coin parameter list is quickly out of date and cannot be kept up to date. It is the responsibility of each user to check that the keys created are correct! Use of this software is at your own risk!
There are three ways to create the private key:
Entry as text: Any text can be entered. This text then becomes the private key with a hash, Public key and the Bitcoin address generated.
cube sign:
There can be 100 dice characters in Base6 (also characters between 1 and 6). This includes: 1=1, 2=2, 3=3, 4=4, 5=5, 6=0.
The private key can also be entered directly in all common formats: Hexa, Base58, Base58 compressed and Base64. Checksum check is implemented.
- The format of the generated keys and addresses can be set under «Settings»
- the public key is given in hexa
- The coin address can be output in WIF-uncompressed, WIF-compressed, P2SH and Bech32
- The QR code of the private key and the coin address is displayed
Issue of the coin amount
- If the internet connection is active, the coin amount belonging to the key is displayed
- The amount is queried on a suitable website
- If no internet connection is available, nothing is displayed.
For safety, the program reads the QR code back in as an image, scanned and checked. This prevents an incorrect QR code from being displayed.
Save and open the wallet
An encrypted wallet with any number of keys can be saved. A strong password must be entered for this. To increase security, encryption is carried out in succession using AES and Twofish. In addition, the encryption contains a certain brute force protection, which extends the runtime with the help of a scrypt hash.
Create a paper wallet.
The surface of the program can be printed out or saved as an image.
If you find bugs, ideas for improvements, or just have questions, I am happy about every mail: Maxwell-KSP@gmx.de
If you like the Coin Address Generator, I would be very happy to receive a donation:
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS «AS IS» AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
About
Generate Bitcoin private key and Bitcoin address
Источник
Как создать адрес биткоин-кошелька с помощью закрытого ключа
Небольшая статья с примерами о том, каким образом можно получить открытый ключ, имея закрытый.
В предыдущей статье мы рассматривали различные методы генерации закрытого ключа. Какой бы метод вы ни выбрали, в конце вы получите 32 байта данных. Вот ключ, который мы получили в конце той статьи:
60cf347dbc59d31c1358c8e5cf5e45b822ab85b79cb32a9f3d98184779a9efc2
В этой статье мы будем использовать этот закрытый ключ для получения как открытого ключа, так и адреса для биткоин-кошелька.
Наша задача – применить серию преобразований к закрытому ключу, чтобы получить открытый ключ, а затем и адрес кошелька. Большинство этих преобразований называются хэш-функциями. Эти хэш-функции являются односторонними преобразованиями, которые нельзя отменить. Мы не будем вдаваться в механизм самих функций — по этому вопросу есть много замечательных статей. Вместо этого мы рассмотрим, как использование этих функций в правильном порядке может помочь вам сгенерировать адрес биткоин-кошелька, который вы впоследствии сможете использовать.
Криптография с использованием эллиптической кривой
Первое, что нам нужно сделать, это применить алгоритм цифровой подписи ECDSA или Elliptic Curve к нашему закрытому ключу. Эллиптической кривой является кривая, определенная уравнением y² = x³ + ax + b с выбранной a и b. Существует целое семейство таких кривых, которые широко известны и широко используются. Для биткоина используется кривая secp256k1/. Если вы хотите узнать больше о криптографии на основе эллиптических кривых, почитайте эту статью.
Применяя ECDSA к закрытому ключу, мы получаем 64-байтовое целое число. Оно состоит из двух 32-байтовых целых чисел, которые представляют соединенные вместе точки X и Y эллиптической кривой.
Для нашего примера мы получили:
На языке Python это будет выглядеть так:
Примечание: как видно из кода, прежде чем я использовал метод на базе модуля ECDSA, я расшифровал закрытый ключ, используя кодеки. Это больше относится к Python и меньше к самому алгоритму, но я объясню, что мы здесь делаем во избежание возможной путаницы.
В Python есть как минимум два класса, которые могут хранить закрытый и открытый ключи: “str” и “bytes”. Первый – это строка, а второй – массив байтов. Криптографические методы в Python работают с классом “bytes”, принимая его в качестве входных данных и возвращая как результат.
Теперь, есть маленькая загвоздка: строка, скажем, 4f3c не равна массиву байтов 4f3c, она равна массиву байтов с двумя элементами, O 031e7bcc70c72770dbb72fea022e8a6d07f814d2ebe4de9ae3f7af75bf706902a7
Этот ключ содержит ту же информацию, но он почти в два раза короче, чем несжатый ключ. Клево!
Раньше программное обеспечение кошельков использовало длинные, полные версии открытых ключей, но теперь большинство из них перешло на сжатые ключи.
Шифрование открытого ключа
Теперь нам нужно сгенерировать адрес кошелька. Какой бы метод генерирования открытого ключа вы ни выбрали, он проходит ту же процедуру. Очевидно, что адреса будут отличаться. В этой статье мы рассмотрим сжатую версию.
Здесь нам нужно применить SHA-256 к открытому ключу, а затем применить RIPEMD-160 к результату. Порядок очень важен.
SHA-256 и RIPEMD-160 являются двумя хэш-функциями, и опять же, мы не будем вдаваться в детали того, как они работают.
Важно то, что теперь у нас есть 160-битное целое число, которое будет использоваться для дальнейших модификаций. Назовем это зашифрованным открытым ключом. Для нашего примера, зашифрованный открытый ключ – это 453233600a96384bb8d73d400984117ac84d7e8b
Зашифрованный открытый ключ = RIPEMD-160 (SHA-256 (Открытый ключ))
Вот как мы шифруем открытый ключ в Python:
Добавление сетевого байта
Биткоин имеет две сети, основную и тестовую. Основной сетью является сеть, которую все люди используют для перевода монет. Тестовая сеть была создана, как вы уже догадались, для тестирования новых функций и программного обеспечения.
Мы хотим создать адрес для использования его в основной сети, поэтому нам нужно добавить 0x00 к зашифрованному открытому ключу. Результат 00453233600a96384bb8d73d400984117ac84d7e8b . Для тестовой сети это будет 0x6f .
Контрольная сумма
Теперь нам нужно рассчитать контрольную сумму для нашего ключа в основной сети. Идея контрольной суммы состоит в том, чтобы убедиться, что данные (в нашем случае, ключ) не были повреждены во время передачи. Программное обеспечение кошелька должно ориентироваться на контрольную сумму и отмечать адрес как недопустимый, если контрольная сумма не соответствует заявленной.
Чтобы вычислить контрольную сумму ключа, нам нужно применить SHA-256 дважды, а затем взять первые 4 байта результата. В нашем примере двойной SHA-256 — это 512f43c48517a75e58a7ec4c554ecd1a8f9603c891b46325006abf39c5c6b995 , и поэтому контрольная сумма 512f43c4 (обратите внимание, что 4 байта составляют 8 шестнадцатеричных цифр).
С = SHA-256 (SHA-256 (зашифрованный открытый ключ основной сети))
Контрольная сумма = первые 4 байта С
Для расчета контрольной суммы адреса используется следующий код:
Получение адреса
Наконец, чтобы получить адрес, мы просто объединяем ключ основной сети и контрольную сумму. В нашем случае это выглядит так: 00453233600a96384bb8d73d400984117ac84d7e8b512f43c4
Вот и все! Это адрес кошелька для закрытого ключа, приведенного в начале статьи.
Но вы можете заметить, что что-то не так. Вы, вероятно, уже встречали биткоин-адреса, и они не выглядели так. Ну, причина в том, что они кодируются с помощью Base58 (вариант кодирования цифрового кода в виде буквенно-цифрового текста на основе латинского алфавита. Алфавит кодирования содержит 58 символов). Это немного странно.
Вот алгоритм для преобразования шестнадцатеричного адреса в адрес Base58:
Мы получаем 17JsmEygbbEUEpvt4PFtYaTeSqfb9ki1F1 , сжатый адрес биткоин-кошелька.
Шестнадцатеричный адрес = зашифрованный открытый ключ основной сети + адрес контрольной суммы = Base58 (Шестнадцатеричный адрес)
Вывод
Процесс генерации ключей кошелька можно разделить на четыре этапа:
- создание открытого ключа с помощью ECDSA
- шифрование ключа с помощью SHA-256 и RIPEMD-160
- расчет контрольной суммы с помощью двойной SHA-256
- кодирование ключа с помощью Base58.
В зависимости от формы открытого ключа (полный или сжатый), мы получаем разные адреса, но оба совершенно допустимы.
Вот полный алгоритм для несжатого открытого ключа:
Эллиптический открытый ключ = ECDSA (закрытый ключ)
Открытый ключ = 0х04 + эллиптический открытый ключ
Зашифрованный открытый ключ = RIPEMD-160 (SHA-256 (открытый ключ))
Зашифрованный открытый ключ основной сети = 0х00 + Зашифрованный открытый ключ
С = SHA-256 (SHA-256 (Зашифрованный открытый ключ основной сети))
Контрольная сумма = первые 4 байта С
Шестнадцатеричный адрес = Зашифрованный открытый ключ основной сети + Контрольная сумма
Адрес = Base58 (Шестнадцатеричный адрес)
Если вы хотите «поиграть» с кодом, я опубликовал его на GitHub.
Я делаю обзор о криптовалютах на Medium. Первая часть – подробное описание блокчейна.
Источник
Hex to bitcoin address
Tool for converting Bitcoin keys and addresses
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
bitcoin-tool is a simple tool written in C to convert Bitcoin keys to addresses, and various other conversions of keys.
Disclaimer: THIS CODE IS EXPERIMENTAL, IT IS PROBABLY BUGGY. PLEASE DO NOT TRUST YOUR BITCOINS WITH IT. IT IS EASY TO MAKE AN IRREVERSIBLE MISTAKE AND SEND YOUR BITCOINS TO A ADDRESS WITH NO WAY OF GETTING THEM BACK.
Run make test to compile and run all tests.
- A C compiler
- OpenSSL headers and libraries (with elliptic curve support)
- GNU make : Packages: FreeBSD gmake
- GNU bash (for running tests)
- xxd (for running tests) : Packages: Linux vim , FreeBSD vim or vim-lite
Gentoo by default enables the bindist flag on the openssl package, which disables elliptic curve support, presumably because of software patent concerns. Since the openssh package also has bindist USE-flag set, the USE-flag must be disabled in both, then re-emerged to get an OpenSSL library with elliptic curve support.
Use gmake to process the Makefile.
- FreeBSD 10.4 amd64, clang 3.4.1
- FreeBSD 11.1 amd64, clang 4.0.0
Tested on Windows 10 64-bit edition using Cygwin (64-bit) with x86_64_w64_mingw32-gcc compiler.
Requires Cygwin packages: bash , make , mingw64-x86_64-gcc-core , openssl-devel
Use make CC=other_cc to specify a different compiler if needed.
I created this because I couldn’t find an offline tool or library able to create addresses from Bitcoin private keys, and as a learning exercise in Bitcoin address formats and ECDSA.
Some day I’d like to replace the dependancy on OpenSSL with my own implementation of ECDSA (for portability).
The option names are a little verbose but I wanted to make it clear exactly what each one is referring to, especially when it is possible to make a costly mistake.
I’ve tried to add as much sanity checking as possible, to remove the scope for errors and misinterpretation of data. This sometimes boreders on the pedantic and annoying. For example, if the file for —input-file contains more data than is expected, then it’ll refuse to process it at all.
The mini-private-key input-type requires —input to be a 30 character ASCII string in valid mini private key format and —input-format to be raw .
If raw keys are input and an address output is required, then the key type prefix must be specified via —network
Manual address / key generation
Let’s manually generate a Bitcoin address and private key for the purpose of an offline wallet (cold storage).
Create private key:
Inspect private key:
Convert private key to WIF (Wallet Import Format). Since it is a raw key, the network type must be explicitally set (to bitcoin in this case) because it cannot be determined from the raw key :
Specifying —public-key-compression is mandatory because the WIF output is different depending on which public key compression type you choose, and there is no way to guess from a raw private key.
Same again but compressed public key :
Note that the WIF private key is longer with public key compression on, because an extra byte flag is stored to indicate that the public key should be compressed (the private key is exactly the same).
Show address for uncompressed WIF private key:
Show address for compressed WIF private key:
This demonstrates why it is necessary to be careful when converting raw private keys to addresses; the same private key will (almost definitely) result in two seperate addresses, one for each intermediate form of the public key.
Convert the WIF private key to a QR code so we can print it and import it easily later:
Now you can receive Bitcoins using the address above, but you will need to import the private key into your wallet at a later time in order to spend them ( bitcoind importprivkey , for the official client), or at least be able to sign transactions with that key (not necessarily online).
Generate address from random private key
This outputs an address you can send Bitcoins to, if you want to loose them forever (because the private key is never output!).
Hash a text phrase with SHA256, which is then used as the private key to generate an address from.
Never use this example for an actual wallet, it will be stolen almost immediately! (I did a test with another dictionary word and it took all of 4 seconds for someone to steal it!)
This shows the —output-type all option, which spews out lots of unnecessary garbage which I can’t imagine would ever be useful, but it does so because it can. So There.
You can read multiple lines of input from a text file and process individually with the —batch option. This requires the —input-file option to be set. This will be faster than spawning a new instance of bitcoin-tool for each line of a line — from a shell script, for example.
Generate 1000 random private keys in hex format keys=1000 ; openssl rand $[32*keys] | xxd -p -c32 > hexkeys
Convert all the private keys to addresses
Источник