Установка и API ключи. Для чего нужен api id Вконтакте блогу на WordPress

Для удобства многих игроков, разработчиками EVE были созданы api для возможности доступа/размещения информации об аккаунте, на других ресурсах. Многие серьезные корпорации требуют предоставление ключа перед принятием игрока к себе. В этой статье мы постараемся рассказать вам что такое Eve API key, как его получить и что с ним можно делать.

Что такое ключ API? Как я могу его использовать?

Ключ API является частным кодом, который идентифицирует ваш аккаунт и позволяет сторонним программам и веб-сайтам, получать доступ к информации о ваших персонажах и корпорациях. Используя эти данные, такие утилиты могут способствовать своевременному оповещению о важных для вас событиях, начиная от взаимодействия с игровым функционалом (продажи/календарные события/планы/состояние корабли и т.д.), заканчивая взаимодействием с другими игроками.

Это безопасно? Может ли кто-нибудь получить доступ к моей учетной записи без моего ведома?

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

Использование ключа API не дает людям доступ к вашей учетной записи. В этом заключается цель ключей API. Ключ API позволяет только просматривать (читать) данные персонажа и корпорации. Они не смогут войти в игру, изменить ваш пароль или другим способом взломать ваш аккаунт.

Это единственный безопасный способ дать программам и веб-сайтам доступ к вашим данным.

Я до сих пор не доверяю.

Если вы не уверены, что веб-сайт или программа, запрашиваемые ключ API, являются безопасными, пожалуйста, не предоставляйте ему ваш API ключ! Вы несете полную ответственность за любое использование информации, полученной с помощью функции API.

Я дал кому-то мой ключ API, и теперь я хочу, чтобы они не могли использовать его!

Если вы считаете, что кто-то злоупотребляет вашим ключом API, вы можете удалить его из списка разрешенных к доступу, или просто изменить код верификации. Пожалуйста, обратите внимание, что все программы и веб-сайты, которые используют старый API ключ, больше не будут иметь возможность получить доступ к данным, если вы не предоставите им новый ключ с обновленной информацией.

Вы можете просмотреть API активности на вашем счету с помощью журнала. API доступа Если вы считаете, что кто-то злоупотребляет одним из ваших ключей API, пожалуйста, измените код верификации или удалить ключ API из приведенного выше списка.

Как создать Eve API key?

  1. Для того чтобы создать ключ перейдите по ссылке: https://community.eveonline.com/support/api-key/update
  2. Вам необходимо будет авторизоваться. Обратите внимание на адрес прежде чем авторизовываться. Только такой адрес является адресом ОФФ сайта EVE.
  3. После авторизации у вас появиться окно с такой информацией:
  • Операции с кошельком
  • Операции с кошельком журнал
  • Рыночные ордера
  • Баланс счета

Связь (Communications)

  • Каналы чата
  • Тексты уведомлений
  • Уведомления
  • Почтовые сообщения
  • Списки рассылки
  • Почта
  • Контактная уведомления
  • Список контактов

Публичная информация (Public Information)

  • Информация о персонаже
  • Итоговая таблица
  • Награды
  • Лог убийств
  • Статистика войн

Наука и производство (Science and Industry)

  • Исследования
  • Промышленная деятельность

Личная информация (Private Information)

  • Закладки
  • Координаты
  • Контракты
  • Состояние счета
  • Информация о персонаже
  • Календарь предстоящих событий
  • Очередь изучающихся навыков.
  • Навыки изученные
  • Лист персонажа
  • Календарь событий
  • Список активов

Аналогично и для ключа типа — Корпорация . Далее нажимаете «submit» и ключ будет создан. Он сразу готов к использованию.

Где этот ключ используется?

Зачастую данная возможность реализована для Корпораций (клан сайты) и доп. приложении для мира EVE. Что упрощает момент обмена информацией с сокорповцами.

Внимательно ознакомьтесь с нашим мануалом по безопасной раскрутке твиттер-аккаунтов .

О ключах для доступа к API Твиттера

Некоторые функции наших программ потребуют для работы ключи доступа к API Твиттера. Создание и добавление ключей достаточно произвести один раз . Ключи доступа к API Твиттер вы может бесплатно получить в специальном разделе Твиттера.


Внимание! Если вы только что установили программу, то в ней уже имеется публичный API ключ, позволяющий полноценно работать. Однако если вы хотите работать через индивидуальный API ключ - следуйте дальнейшим инструкциям на этой странице.


Алгоритм получения ключей для доступа к API Твиттера


Шаг 1
Войдите в любой ваш твиттер-аккаунт. В настройках аккаунта выберите пункт "Телефон" и если он не задан - укажите его. Твиттер попросит отправить SMS. Сделайте это. После создания ключей, в пункте настроек «Телефон», вы сможете удалить телефон и привязать его к другому твиттер-аккаунту.

Шаг 2

Перейдите в раздел для разработчиков и кликните по кнопке "Create New App":


Шаг 3

Заполните поля помеченные звездочкой (*).

Name - имя ключа. Здесь можно писать все что угодно, но имя не должно совпадать с другими именами в Твиттере. Например: "Ivan111"

Describtion - описание ключа. Достаточно написать 10 символов. Можно скопировать из предыдущего поля.

Поставьте галочку "Yes, I agree", введите капчу и нажмите на кнопку "Create your Twitter application".


Шаг 4

После завершения 3-го шага вы попадете на страницу своего ключа. Кликните по вкладке "API Keys" и увидите первую часть ключа:


Нажмите на кнопку "Create my access token", чтобы получить вторую часть ключа:


Все готово!


Вы создали один ключ. Ключ состоит из четырех блоков:
- API key
- API secret
- Access token
- Access token secret

Эти данные необходимо скопировать и вставить в нашу программу. Для этого в программе кликните по иконке "Настройки" и в открывшемся окне выберите вкладку "Настройки доступа к API Твиттера".


Внимание! Создав ключ, вы можете в настройках аккаунта удалить номер мобильного телефона и задать тот же номер в настройках другого аккаунта.

Внимание! После создания новых ключей, необходимо порядка часа для того, чтобы они гарантированно начали функционировать. Это время нужно Твиттеру чтобы обновить базу ключей. Поэтому выждите час после добавления новых ключей в программу, и только после этого начинайте работать.

Часто задаваемые вопросы


В. Что это за API Твиттера такое?
О. API это специальный набор команд, который Твиттер предоставляет разработчикам программ. В помощью этих команд программы могут запрашивать у Твиттера большие объемы данных.

В. Сколько ключей можно создать в одном моем твиттер-аккаунте?
О. Сколько хотите. Однако мы не рекомендуем в одном аккаунте создавать больше двух ключей. Это означает что если вы хотите добавить в программу четыре ключа, то вам понадобится два твиттер-аккаунта.

В. А что именно программа делает с ключами доступа к API? Безопасно ли это для моих аккаунтов?
О. Ключи нужны для сервисных функций. Например для поиска аккаунтов, для быстрого получения списка фолловеров и/или фолловингов заданного аккаунта, для получения сводной информации о группе найденных аккаунтов. Механизм получения сервисных данных через API полностью безопасен для ваших аккаунтов.

В. У меня 100 аккаунтов. Мне что нужно 100 ключей добавить в программу?
О. Нет. Программа заработает уже после добавления первого ключа. Количество ваших аккаунтов, добавленных в программу, никак не соотносится с количеством ключей доступа к API Твиттера.

В. Сколько ключей доступа к API Твиттера вы рекомендуете добавлять в программу?
О. Программа начнет работать после добавления даже одного ключа, но мы рекомендуем добавить 3-4 штуки. Несколько ключей позволят программе автоматически переключиться на другой ключ когда лимиты работы с одним ключом истекут.

В. Я все сделал как у вас написано, но вижу только API key и API secret, а два других не вижу. Что делать?
О. Нужно нажать кнопку "Create my access token" и остальные данные тут же появятся.

В. Ключи доступа к API Твиттера и лицензионные ключи, которые я получил после покупки программы это одно и тоже?
О. Это совершенно разные вещи. Ключи доступа к API Твиттера выдаются самим Твиттером бесплатно и нужны для полноценной работы наших программ. Лицензионные ключи вы покупаете у нас для того, чтобы программа могла у вас работать дольше своего пробного периода.

В. Я ввел ключи в программу, но в процессе работы она пишет что ключи неверные и их нужно сменить. Что делать?
О. Часто причиной такого поведения бывает ошибка при копировании ключей из браузера в программу. Если при копировании вы не ошиблись, проверьте, не включен ли в вашем браузере автоматический перевод страниц (обычно это делает плагин от Google). В процессе перевода меняется регистр букв в ключе, что недопустимо. Отключите плагин, либо укажите ему показать оригинал страницы.

To use the Geocoding API, you must get an API key which you can then add to your mobile app, website, or web server. The API key is used to track API requests associated with your project for usage and billing. To learn more about API keys, see the and the .

Reminder: To use the Geocoding API, you must get an API key and you must enable billing. You can enable billing when you get your API key (see the ) or as a separate process (see ). Note: Before moving your mobile app, website, or web server to production, it is recommended that you secure your API key by adding a restriction (see ).

Console

Quick guide

Step 1: Get an API key

Click the button below, to get an API key using the . You will be asked to (1) pick one or more products, (2) select or create a project, and (3) set up a billing account. Once your API key is created you will be prompted to restrict the key"s usage. (For more information, see .)

Get Started

Step 2: Add the API key to your request

When loading the Geocoding API, substitute YOUR_API_KEY in the code below with the API key you got from the previous step.

Https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key= YOUR_API_KEY

Detailed guide

Detailed guide for Premium Plan customers

To use the Geocoding API, you must authenticate requests using either an API key or

Choosing an authentication method for your application

The authentication method you choose is based on your license:

  • Customers with the can use an API key or a client ID and digital signature.
  • Customers with a must use a client ID and digital signature.

Have the Premium Plan or a previous license?
To determine which license you have:
> In the Google Cloud Support Portal , click Maps: Usage Report on the left.
> Does the ID at the top of the report have the following format?
gme-[company ] & proj-[number ] ([type ])
If yes, you have the .
If no, you have a (Maps APIs for Work or Maps API for Business).

When deciding which authentication method to use, consider the following:

  • Authentication using an API key (Premium Plan license)
    By using an API key to authenticate your applications, you can:
    • Manage all of your APIs in the Google Cloud Platform Console .
    • Access real-time usage data and 30 days of historical usage data for your application in the Google Cloud Platform Console .
    • Google Cloud Support Portal .
  • Authentication using a client ID and digital signature (Premium Plan or previous license)
    By using your client ID and digital signature to authenticate your application, you can:
    • Add the channel parameter to requests so you can view more detailed usage reports.
    • View usage reports with more than 30 days of data in the Google Cloud Support Portal .
    • Use Maps Analytics tools for the Maps JavaScript API.

Authenticating your application using an API key

Note: For customers with the Premium Plan license.

Follow these steps to get an API key and add restrictions:

Authenticating your application using a client ID and digital signature

Note: For customers with the Premium Plan or previous license. #!/usr/bin/python # -*- coding: utf-8 -*- """ Signs a URL using a URL signing secret """ import hashlib import hmac import base64 import urlparse def sign_url(input_url=None, secret=None): """ Sign a request URL with a URL signing secret. Usage: from urlsigner import sign_url signed_url = sign_url(input_url=my_url, secret=SECRET) Args: input_url - The URL to sign secret - Your URL signing secret Returns: The signed request URL """ if not input_url or not secret: raise Exception("Both input_url and secret are required") url = urlparse.urlparse(input_url) # We only need to sign the path+query part of the string url_to_sign = url.path + "?" + url.query # Decode the private key into its binary format # We need to decode the URL-encoded private key decoded_key = base64.urlsafe_b64decode(secret) # Create a signature using the private key and the URL-encoded # string using HMAC SHA1. This signature will be binary. signature = hmac.new(decoded_key, url_to_sign, hashlib.sha1) # Encode the binary signature into base64 for use within a URL encoded_signature = base64.urlsafe_b64encode(signature.digest()) original_url = url.scheme + "://" + url.netloc + url.path + "?" + url.query # Return signed URL return original_url + "&signature=" + encoded_signature if __name__ == "__main__": input_url = raw_input("URL to Sign: ") secret = raw_input("URL signing secret: ") print "Signed URL: " + sign_url(input_url, secret)

Java

The example below uses the java.util.Base64 class available since JDK 1.8 - older versions may need to use Apache Commons or similar. (Download the code.)

Import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Base64; // JDK 1.8 only - older versions may need to use Apache Commons or similar. import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.net.URL; import java.io.BufferedReader; import java.io.InputStreamReader; public class UrlSigner { // Note: Generally, you should store your private key someplace safe // and read them into your code private static String keyString = "YOUR_PRIVATE_KEY"; // The URL shown in these examples is a static URL which should already // be URL-encoded. In practice, you will likely have code // which assembles your URL from user or web service input // and plugs those values into its parameters. private static String urlString = "YOUR_URL_TO_SIGN"; // This variable stores the binary key, which is computed from the string (Base64) key private static byte key; public static void main(String args) throws IOException, InvalidKeyException, NoSuchAlgorithmException, URISyntaxException { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); String inputUrl, inputKey = null; // For testing purposes, allow user input for the URL. // If no input is entered, use the static URL defined above. System.out.println("Enter the URL (must be URL-encoded) to sign: "); inputUrl = input.readLine(); if (inputUrl.equals("")) { inputUrl = urlString; } // Convert the string to a URL so we can parse it URL url = new URL(inputUrl); // For testing purposes, allow user input for the private key. // If no input is entered, use the static key defined above. System.out.println("Enter the Private key to sign the URL: "); inputKey = input.readLine(); if (inputKey.equals("")) { inputKey = keyString; } UrlSigner signer = new UrlSigner(inputKey); String request = signer.signRequest(url.getPath(),url.getQuery()); System.out.println("Signed URL:" + url.getProtocol() + "://" + url.getHost() + request); } public UrlSigner(String keyString) throws IOException { // Convert the key from "web safe" base 64 to binary keyString = keyString.replace("-", "+"); keyString = keyString.replace("_", "/"); System.out.println("Key: " + keyString); // Base64 is JDK 1.8 only - older versions may need to use Apache Commons or similar. this.key = Base64.getDecoder().decode(keyString); } public String signRequest(String path, String query) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, URISyntaxException { // Retrieve the proper URL components to sign String resource = path + "?" + query; // Get an HMAC-SHA1 signing key from the raw key bytes SecretKeySpec sha1Key = new SecretKeySpec(key, "HmacSHA1"); // Get an HMAC-SHA1 Mac instance and initialize it with the HMAC-SHA1 key Mac mac = Mac.getInstance("HmacSHA1"); mac.init(sha1Key); // compute the binary signature for the request byte sigBytes = mac.doFinal(resource.getBytes()); // base 64 encode the binary signature // Base64 is JDK 1.8 only - older versions may need to use Apache Commons or similar. String signature = Base64.getEncoder().encodeToString(sigBytes); // convert the signature to "web safe" base 64 signature = signature.replace("+", "-"); signature = signature.replace("/", "_"); return resource + "&signature=" + signature; } }

Node JS

The example below uses native Node modules to sign a URL. (Download the code.)

"use strict" const crypto = require("crypto"); const url = require("url"); /** * Convert from "web safe" base64 to true base64. * * @param {string} safeEncodedString The code you want to translate * from a web safe form. * @return {string} */ function removeWebSafe(safeEncodedString) { return safeEncodedString.replace(/-/g, "+").replace(/_/g, "/"); } /** * Convert from true base64 to "web safe" base64 * * @param {string} encodedString The code you want to translate to a * web safe form. * @return {string} */ function makeWebSafe(encodedString) { return encodedString.replace(/\+/g, "-").replace(/\//g, "_"); } /** * Takes a base64 code and decodes it. * * @param {string} code The encoded data. * @return {string} */ function decodeBase64Hash(code) { // "new Buffer(...)" is deprecated. Use Buffer.from if it exists. return Buffer.from ? Buffer.from(code, "base64") : new Buffer(code, "base64"); } /** * Takes a key and signs the data with it. * * @param {string} key Your unique secret key. * @param {string} data The url to sign. * @return {string} */ function encodeBase64Hash(key, data) { return crypto.createHmac("sha1", key).update(data).digest("base64"); } /** * Sign a URL using a secret key. * * @param {string} path The url you want to sign. * @param {string} secret Your unique secret key. * @return {string} */ function sign(path, secret) { const uri = url.parse(path); const safeSecret = decodeBase64Hash(removeWebSafe(secret)); const hashedSignature = makeWebSafe(encodeBase64Hash(safeSecret, uri.path)); return url.format(uri) + "&signature=" + hashedSignature; }

C#

The example below uses the default System.Security.Cryptography library to sign a URL request. Note that we need to convert the default Base64 encoding to implement a URL-safe version. (Download the code.)

Using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Web; namespace SignUrl { public struct GoogleSignedUrl { public static string Sign(string url, string keyString) { ASCIIEncoding encoding = new ASCIIEncoding(); // converting key to bytes will throw an exception, need to replace "-" and "_" characters first. string usablePrivateKey = keyString.Replace("-", "+").Replace("_", "/"); byte privateKeyBytes = Convert.FromBase64String(usablePrivateKey); Uri uri = new Uri(url); byte encodedPathAndQueryBytes = encoding.GetBytes(uri.LocalPath + uri.Query); // compute the hash HMACSHA1 algorithm = new HMACSHA1(privateKeyBytes); byte hash = algorithm.ComputeHash(encodedPathAndQueryBytes); // convert the bytes to string and make url-safe by replacing "+" and "/" characters string signature = Convert.ToBase64String(hash).Replace("+", "-").Replace("/", "_"); // Add the signature to the existing URI. return uri.Scheme+"://"+uri.Host+uri.LocalPath + uri.Query +"&signature=" + signature; } } class Program { static void Main() { // Note: Generally, you should store your private key someplace safe // and read them into your code const string keyString = "YOUR_PRIVATE_KEY"; // The URL shown in these examples is a static URL which should already // be URL-encoded. In practice, you will likely have code // which assembles your URL from user or web service input // and plugs those values into its parameters. const string urlString = "YOUR_URL_TO_SIGN"; string inputUrl = null; string inputKey = null; Console.WriteLine("Enter the URL (must be URL-encoded) to sign: "); inputUrl = Console.ReadLine(); if (inputUrl.Length == 0) { inputUrl = urlString; } Console.WriteLine("Enter the Private key to sign the URL: "); inputKey = Console.ReadLine(); if (inputKey.Length == 0) { inputKey = keyString; } Console.WriteLine(GoogleSignedUrl.Sign(inputUrl,inputKey)); } } }

For testing purposes, you can test the following URL and private key to see if it generates the correct signature. Note that this private key is purely for testing purposes and will not be validated by any Google services.

  • URL : https://maps.googleapis.com/maps/api/geocode/json?address=New+York&client= clientID
  • Private Key : vNIXE0xscrmjlyV-12Nj_BvUPaw=
  • URL Portion to Sign : /maps/api/geocode/json?address=New+York&client= clientID
  • Signature : chaRF2hTJKOScPr-RQCEhZbSzIE=
  • Full Signed URL : https://maps.googleapis.com/maps/api/geocode/json?address=New+York&client= clientID &signature=chaRF2hTJKOScPr-RQCEhZbSzIE=

Examples in additional languages

Examples that cover more languages are available in the url-signing project.

More about your private cryptographic key

Your private cryptographic URL-signing key will be issued with your client ID and is a "secret shared key" between you and Google. This signing key is yours alone and is unique to your client ID. For that reason, please keep your signing key secure. This key should not be passed within any requests, stored on any websites, or posted to any public forum. Anyone obtaining this signing key could spoof requests using your identity.

Note: This private cryptographic signing key is not the same as the API keys issued by the Google Cloud Platform Console.

If you"ve lost your private cryptographic key, log in to the Google Cloud Support Portal and click Maps: Manage Client ID to retrieve it.

Restricting an API key

Google Maps APIs are available via HTTP web services, for web browsers, and Android or iOS apps. APIs in any platform can use an unrestricted API key. You can optionally add a restriction (for example, IP addresses) to the API key. Once restricted, a key will only work on platforms that support that type of restriction.

Note: Before moving your app or website to production, it is recommended that you secure your API key by adding a restriction. To learn more, see the and Securing an API key .

To add restrictions to an API key, do the following:

Troubleshooting authentication issues

If your request is malformed or supplies an invalid signature, the Geocoding API returns an HTTP 403 (Forbidden) error.

To troubleshoot individual URLs, you can use the URL Signing Debugger . It allows you to quickly validate a URL and signature generated by your application.

Alternatively, Google Maps APIs Premium Plan customers can troubleshoot individual URLs by logging in to the Google Cloud Support Portal and selecting Resources > Google Maps APIs Premium Plan online tools > URL Signing Debugger for Web Service and Image APIs .

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 3.0 License , and code samples are licensed under the Apache 2.0 License . For details, see our . Java is a registered trademark of Oracle and/or its affiliates.

Обновлено Март 11, 2019

To use the Geocoding API, you must get an API key which you can then add to your mobile app, website, or web server. The API key is used to track API requests associated with your project for usage and billing. To learn more about API keys, see the and the .

Reminder: To use the Geocoding API, you must get an API key and you must enable billing. You can enable billing when you get your API key (see the ) or as a separate process (see ). Note: Before moving your mobile app, website, or web server to production, it is recommended that you secure your API key by adding a restriction (see ).

Console

Quick guide

Step 1: Get an API key

Click the button below, to get an API key using the . You will be asked to (1) pick one or more products, (2) select or create a project, and (3) set up a billing account. Once your API key is created you will be prompted to restrict the key"s usage. (For more information, see .)

Get Started

Step 2: Add the API key to your request

When loading the Geocoding API, substitute YOUR_API_KEY in the code below with the API key you got from the previous step.

Https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key= YOUR_API_KEY

Detailed guide

Detailed guide for Premium Plan customers

To use the Geocoding API, you must authenticate requests using either an API key or

Choosing an authentication method for your application

The authentication method you choose is based on your license:

  • Customers with the can use an API key or a client ID and digital signature.
  • Customers with a must use a client ID and digital signature.

Have the Premium Plan or a previous license?
To determine which license you have:
> In the Google Cloud Support Portal , click Maps: Usage Report on the left.
> Does the ID at the top of the report have the following format?
gme-[company ] & proj-[number ] ([type ])
If yes, you have the .
If no, you have a (Maps APIs for Work or Maps API for Business).

When deciding which authentication method to use, consider the following:

  • Authentication using an API key (Premium Plan license)
    By using an API key to authenticate your applications, you can:
    • Manage all of your APIs in the Google Cloud Platform Console .
    • Access real-time usage data and 30 days of historical usage data for your application in the Google Cloud Platform Console .
    • Google Cloud Support Portal .
  • Authentication using a client ID and digital signature (Premium Plan or previous license)
    By using your client ID and digital signature to authenticate your application, you can:
    • Add the channel parameter to requests so you can view more detailed usage reports.
    • View usage reports with more than 30 days of data in the Google Cloud Support Portal .
    • Use Maps Analytics tools for the Maps JavaScript API.

Authenticating your application using an API key

Note: For customers with the Premium Plan license.

Follow these steps to get an API key and add restrictions:

Authenticating your application using a client ID and digital signature

Note: For customers with the Premium Plan or previous license. #!/usr/bin/python # -*- coding: utf-8 -*- """ Signs a URL using a URL signing secret """ import hashlib import hmac import base64 import urlparse def sign_url(input_url=None, secret=None): """ Sign a request URL with a URL signing secret. Usage: from urlsigner import sign_url signed_url = sign_url(input_url=my_url, secret=SECRET) Args: input_url - The URL to sign secret - Your URL signing secret Returns: The signed request URL """ if not input_url or not secret: raise Exception("Both input_url and secret are required") url = urlparse.urlparse(input_url) # We only need to sign the path+query part of the string url_to_sign = url.path + "?" + url.query # Decode the private key into its binary format # We need to decode the URL-encoded private key decoded_key = base64.urlsafe_b64decode(secret) # Create a signature using the private key and the URL-encoded # string using HMAC SHA1. This signature will be binary. signature = hmac.new(decoded_key, url_to_sign, hashlib.sha1) # Encode the binary signature into base64 for use within a URL encoded_signature = base64.urlsafe_b64encode(signature.digest()) original_url = url.scheme + "://" + url.netloc + url.path + "?" + url.query # Return signed URL return original_url + "&signature=" + encoded_signature if __name__ == "__main__": input_url = raw_input("URL to Sign: ") secret = raw_input("URL signing secret: ") print "Signed URL: " + sign_url(input_url, secret)

Java

The example below uses the java.util.Base64 class available since JDK 1.8 - older versions may need to use Apache Commons or similar. (Download the code.)

Import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Base64; // JDK 1.8 only - older versions may need to use Apache Commons or similar. import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.net.URL; import java.io.BufferedReader; import java.io.InputStreamReader; public class UrlSigner { // Note: Generally, you should store your private key someplace safe // and read them into your code private static String keyString = "YOUR_PRIVATE_KEY"; // The URL shown in these examples is a static URL which should already // be URL-encoded. In practice, you will likely have code // which assembles your URL from user or web service input // and plugs those values into its parameters. private static String urlString = "YOUR_URL_TO_SIGN"; // This variable stores the binary key, which is computed from the string (Base64) key private static byte key; public static void main(String args) throws IOException, InvalidKeyException, NoSuchAlgorithmException, URISyntaxException { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); String inputUrl, inputKey = null; // For testing purposes, allow user input for the URL. // If no input is entered, use the static URL defined above. System.out.println("Enter the URL (must be URL-encoded) to sign: "); inputUrl = input.readLine(); if (inputUrl.equals("")) { inputUrl = urlString; } // Convert the string to a URL so we can parse it URL url = new URL(inputUrl); // For testing purposes, allow user input for the private key. // If no input is entered, use the static key defined above. System.out.println("Enter the Private key to sign the URL: "); inputKey = input.readLine(); if (inputKey.equals("")) { inputKey = keyString; } UrlSigner signer = new UrlSigner(inputKey); String request = signer.signRequest(url.getPath(),url.getQuery()); System.out.println("Signed URL:" + url.getProtocol() + "://" + url.getHost() + request); } public UrlSigner(String keyString) throws IOException { // Convert the key from "web safe" base 64 to binary keyString = keyString.replace("-", "+"); keyString = keyString.replace("_", "/"); System.out.println("Key: " + keyString); // Base64 is JDK 1.8 only - older versions may need to use Apache Commons or similar. this.key = Base64.getDecoder().decode(keyString); } public String signRequest(String path, String query) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, URISyntaxException { // Retrieve the proper URL components to sign String resource = path + "?" + query; // Get an HMAC-SHA1 signing key from the raw key bytes SecretKeySpec sha1Key = new SecretKeySpec(key, "HmacSHA1"); // Get an HMAC-SHA1 Mac instance and initialize it with the HMAC-SHA1 key Mac mac = Mac.getInstance("HmacSHA1"); mac.init(sha1Key); // compute the binary signature for the request byte sigBytes = mac.doFinal(resource.getBytes()); // base 64 encode the binary signature // Base64 is JDK 1.8 only - older versions may need to use Apache Commons or similar. String signature = Base64.getEncoder().encodeToString(sigBytes); // convert the signature to "web safe" base 64 signature = signature.replace("+", "-"); signature = signature.replace("/", "_"); return resource + "&signature=" + signature; } }

Node JS

The example below uses native Node modules to sign a URL. (Download the code.)

"use strict" const crypto = require("crypto"); const url = require("url"); /** * Convert from "web safe" base64 to true base64. * * @param {string} safeEncodedString The code you want to translate * from a web safe form. * @return {string} */ function removeWebSafe(safeEncodedString) { return safeEncodedString.replace(/-/g, "+").replace(/_/g, "/"); } /** * Convert from true base64 to "web safe" base64 * * @param {string} encodedString The code you want to translate to a * web safe form. * @return {string} */ function makeWebSafe(encodedString) { return encodedString.replace(/\+/g, "-").replace(/\//g, "_"); } /** * Takes a base64 code and decodes it. * * @param {string} code The encoded data. * @return {string} */ function decodeBase64Hash(code) { // "new Buffer(...)" is deprecated. Use Buffer.from if it exists. return Buffer.from ? Buffer.from(code, "base64") : new Buffer(code, "base64"); } /** * Takes a key and signs the data with it. * * @param {string} key Your unique secret key. * @param {string} data The url to sign. * @return {string} */ function encodeBase64Hash(key, data) { return crypto.createHmac("sha1", key).update(data).digest("base64"); } /** * Sign a URL using a secret key. * * @param {string} path The url you want to sign. * @param {string} secret Your unique secret key. * @return {string} */ function sign(path, secret) { const uri = url.parse(path); const safeSecret = decodeBase64Hash(removeWebSafe(secret)); const hashedSignature = makeWebSafe(encodeBase64Hash(safeSecret, uri.path)); return url.format(uri) + "&signature=" + hashedSignature; }

C#

The example below uses the default System.Security.Cryptography library to sign a URL request. Note that we need to convert the default Base64 encoding to implement a URL-safe version. (Download the code.)

Using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Web; namespace SignUrl { public struct GoogleSignedUrl { public static string Sign(string url, string keyString) { ASCIIEncoding encoding = new ASCIIEncoding(); // converting key to bytes will throw an exception, need to replace "-" and "_" characters first. string usablePrivateKey = keyString.Replace("-", "+").Replace("_", "/"); byte privateKeyBytes = Convert.FromBase64String(usablePrivateKey); Uri uri = new Uri(url); byte encodedPathAndQueryBytes = encoding.GetBytes(uri.LocalPath + uri.Query); // compute the hash HMACSHA1 algorithm = new HMACSHA1(privateKeyBytes); byte hash = algorithm.ComputeHash(encodedPathAndQueryBytes); // convert the bytes to string and make url-safe by replacing "+" and "/" characters string signature = Convert.ToBase64String(hash).Replace("+", "-").Replace("/", "_"); // Add the signature to the existing URI. return uri.Scheme+"://"+uri.Host+uri.LocalPath + uri.Query +"&signature=" + signature; } } class Program { static void Main() { // Note: Generally, you should store your private key someplace safe // and read them into your code const string keyString = "YOUR_PRIVATE_KEY"; // The URL shown in these examples is a static URL which should already // be URL-encoded. In practice, you will likely have code // which assembles your URL from user or web service input // and plugs those values into its parameters. const string urlString = "YOUR_URL_TO_SIGN"; string inputUrl = null; string inputKey = null; Console.WriteLine("Enter the URL (must be URL-encoded) to sign: "); inputUrl = Console.ReadLine(); if (inputUrl.Length == 0) { inputUrl = urlString; } Console.WriteLine("Enter the Private key to sign the URL: "); inputKey = Console.ReadLine(); if (inputKey.Length == 0) { inputKey = keyString; } Console.WriteLine(GoogleSignedUrl.Sign(inputUrl,inputKey)); } } }

For testing purposes, you can test the following URL and private key to see if it generates the correct signature. Note that this private key is purely for testing purposes and will not be validated by any Google services.

  • URL : https://maps.googleapis.com/maps/api/geocode/json?address=New+York&client= clientID
  • Private Key : vNIXE0xscrmjlyV-12Nj_BvUPaw=
  • URL Portion to Sign : /maps/api/geocode/json?address=New+York&client= clientID
  • Signature : chaRF2hTJKOScPr-RQCEhZbSzIE=
  • Full Signed URL : https://maps.googleapis.com/maps/api/geocode/json?address=New+York&client= clientID &signature=chaRF2hTJKOScPr-RQCEhZbSzIE=

Examples in additional languages

Examples that cover more languages are available in the url-signing project.

More about your private cryptographic key

Your private cryptographic URL-signing key will be issued with your client ID and is a "secret shared key" between you and Google. This signing key is yours alone and is unique to your client ID. For that reason, please keep your signing key secure. This key should not be passed within any requests, stored on any websites, or posted to any public forum. Anyone obtaining this signing key could spoof requests using your identity.

Note: This private cryptographic signing key is not the same as the API keys issued by the Google Cloud Platform Console.

If you"ve lost your private cryptographic key, log in to the Google Cloud Support Portal and click Maps: Manage Client ID to retrieve it.

Restricting an API key

Google Maps APIs are available via HTTP web services, for web browsers, and Android or iOS apps. APIs in any platform can use an unrestricted API key. You can optionally add a restriction (for example, IP addresses) to the API key. Once restricted, a key will only work on platforms that support that type of restriction.

Note: Before moving your app or website to production, it is recommended that you secure your API key by adding a restriction. To learn more, see the and Securing an API key .

To add restrictions to an API key, do the following:

Troubleshooting authentication issues

If your request is malformed or supplies an invalid signature, the Geocoding API returns an HTTP 403 (Forbidden) error.

To troubleshoot individual URLs, you can use the URL Signing Debugger . It allows you to quickly validate a URL and signature generated by your application.

Alternatively, Google Maps APIs Premium Plan customers can troubleshoot individual URLs by logging in to the Google Cloud Support Portal and selecting Resources > Google Maps APIs Premium Plan online tools > URL Signing Debugger for Web Service and Image APIs .

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 3.0 License , and code samples are licensed under the Apache 2.0 License . For details, see our . Java is a registered trademark of Oracle and/or its affiliates.

Установка и запуск MoonBot

1) Скачиваем архив с сайта.

2) Создаем пустую папку на ПК и отправляем в нее содержимое архива.
Внимание, рекомендации по установке и расположению папки с MoonBot:
а) не запускайте бота из архива;
б) не распаковывайте бота на рабочий стол, во временные и системные папки виндовс, такие как windows, temp, users и тд.;
в) не используйте в названиях папок в пути к боту русские буквы;
г) размещайте папку с ботом на не системном диске D, E и тд, при отсутствии других дисков кроме системного С распологайте паку с ботом в корневом каталоге С диска (C:\MoonBot).

3) Запускаем из папки файл MoonBot.exe. Запускать терминал рекомендуется от имени Администратора, это повысит приоритет работы приложения на вашем ПК и улучшит соединение с биржей. Для слабых ПК рекомендуется после запуска бота перейти в - Диспетчер задач - Подробности - ПКМ по MoonBot.exe - Задать приоритет - Реального времени.

4) Выбираем нужную биржу и вводим в бота API ключи от аккаунта биржи и ждем соединения. Порядок получения API ключей описан ниже. При последующих запусках ключи повторно вводить не нужно.

API ключи

Приложение Moon Bot (в дальнейшем "Бот") взаимодействует с биржей посредством API биржи, для получения доступа к API требуются ключи (API KEYS). При первом запуске Бота требуетсяввести API ключи. Ключи состоят из пары Key, Secret. Key - публичный ключ, он используется для регистрации Вашей копии Бота. Secret - приватный ключ, используется для подписи ордеров. Приватный ключ хранится на вашем компьютере локально в зашифрованном виде в файле BotConfig.bcfg, который Бот создает автоматически. Оба ключа нужно вводить в соответствующие поля в боте на вкладке Логин. В Интернет приватный ключ не передается! Для дополнительной защиты Ваших ключей следует установить пароль, этот пароль будет запрашиваться при каждом запуске Бота. Пароль так же используется только локально.

Получение API ключей на Bittrex

Ключи нужно создать в аккаунте Bittrex, раздел "Settings->API Keys":

У ключей должны быть права: READ INFO, TRADE LIMIT, TRADE MARKET. В целях безопасности права WITHDRAW нужно отключить!

Получение API ключей на Binance

Для регистрации ключей необходимо на сайте биржи зайти в раздел Центр пользователя - API Settings

Ввести любое имя для новых ключей, нажать Create New Key

Ввести код 2ФА авторизации. После получения API KEY и API SECRET рекомендуется сохранить их в отдельный файл (В целях безопасности Binance не даст возможности просмотреть API Secret в случае их утраты) Так же у вас есть возможность ограничить использование ключей заданными Ip адресами.

После запуска MoonBot в первую очередь выберете биржу и введите полученные API Key и API secret .

Чтобы ввести в Moon Bot новые ключи, нужно:

Выбрать Биржу Binance/Bittrex и нажать Применить.

Ввести ""API KEY"

Ввести ""API Secret"

Нажать "Зарегистрировать API ключи"

Если ключи введены верно, то Бот установит соединение с сервером биржи, в окне с настройками отобразится Ваш регистрационный номер, в главном окне в нижнем левом углу появится статус "Соединение ОК".

Если соединение установить не удалось, в окне с логом будет код ошибки. В этом случае перепроверьте API ключи; убедитесь, что в системе присутствуют библиотеки ssleay32.dll, libeay32.dll.*, проверить стабильность работы вашего Интернета, проверить не запрещает ли Антивирус доступ боту в интернет, в боте зайти в Настройки-Специальные и попробовать другие методы соединения.

При последующих запусках Бота повторно вводить ключи не нужно; соединение с биржей будет установлено автоматически.

Если Вы планируете запускать ботов для разных бирж одновременно; можно регистрировать ключи в том же боте, не копируя его, и переключаться между биржами с помощью выпадающего списка выбора биржи. Однако лучше скопировать бота, выбрать там другую биржу и зарегистрировать АПИ ключи от другой биржи.

* Бота можно хранить на флешке и запускать с других ПК.

* Free версию бота можно запускать только в 1 экземпляре.

* Владельцы PRO версии могут делать неограниченное число API ключей от того же аккаунта биржи с поддержкой PRO бесплатно. Для этого необходимо: 1) Скопировать PRO версию бота в отдельную папку 2) Запустить бота из этой папки и в разделе Настройки - Логин выбрать Зарегистрировать другие ключи, ввести новые ключи и нажать Зарегистрировать API ключи. После этого бот с новыми ключами тоже станет PRO.



Есть вопросы?

Сообщить об опечатке

Текст, который будет отправлен нашим редакторам: