• Уважаемые посетители сайта esp8266.ru!
    Мы отказались от размещения рекламы на страницах форума для большего комфорта пользователей.
    Вы можете оказать посильную поддержку администрации форума. Данные средства пойдут на оплату услуг облачных провайдеров для сайта esp8266.ru
  • Система автоматизации с открытым исходным кодом на базе esp8266/esp32 микроконтроллеров и приложения IoT Manager. Наша группа в Telegram

Нужна помощь https

Alexey888

New member
Добрый день. Пытаюсь настроить https (arduino ide). Нашел пример скетча httpsrequest, залил, всё работает. Взял хостинг с ssl, щас думаю за минуту скетч подправлю (данные поменяю на свои) и всё. Но увы.. радость была не долгой.. не заработало.
Строки из примера:
Код:
/*
*  HTTP over TLS (HTTPS) example sketch
*
*  This example demonstrates how to use
*  WiFiClientSecure class to access HTTPS API.
*  We fetch and display the status of
*  esp8266/Arduino project continuous integration
*  build.
*
*  Created by Ivan Grokhotkov, 2015.
*  This example is in public domain.
*/

#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>

const char* ssid = "ss";
const char* password = "pwd";

const char* host = "api.github.com";
const int httpsPort = 443;

// Use web browser to view and copy
// SHA1 fingerprint of the certificate
const char* fingerprint = "CF 05 98 89 CA FF 8E D8 5E 5C E0 C2 E4 F7 E6 C3 C7 50 DD 5C";

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.print("connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  // Use WiFiClientSecure class to create TLS connection
  WiFiClientSecure client;
  Serial.print("connecting to ");
  Serial.println(host);
  if (!client.connect(host, httpsPort)) {
    Serial.println("connection failed");
    return;
  }

  if (client.verify(fingerprint, host)) {
    Serial.println("certificate matches");
  } else {
    Serial.println("certificate doesn't match");
  }

  String url = "/repos/esp8266/Arduino/commits/master/status";
  Serial.print("requesting URL: ");
  Serial.println(url);

  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "User-Agent: BuildFailureDetectorESP8266\r\n" +
               "Connection: close\r\n\r\n");

  Serial.println("request sent");
  while (client.connected()) {
    String line = client.readStringUntil('\n');
    if (line == "\r") {
      Serial.println("headers received");
      break;
    }
  }
  String line = client.readStringUntil('\n');
  if (line.startsWith("{\"state\":\"success\"")) {
    Serial.println("esp8266/Arduino CI successfull!");
  } else {
    Serial.println("esp8266/Arduino CI has failed");
  }
  Serial.println("reply was:");
  Serial.println("==========");
  Serial.println(line);
  Serial.println("==========");
  Serial.println("closing connection");
}

void loop() {
}
Для тестов, меняю на яндекс:
Код:
/*
*  HTTP over TLS (HTTPS) example sketch
*
*  This example demonstrates how to use
*  WiFiClientSecure class to access HTTPS API.
*  We fetch and display the status of
*  esp8266/Arduino project continuous integration
*  build.
*
*  Created by Ivan Grokhotkov, 2015.
*  This example is in public domain.
*/

#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>

const char* ssid = "ss";
const char* password = "pwd";

const char* host = "yandex.ru";
const int httpsPort = 443;

// Use web browser to view and copy
// SHA1 fingerprint of the certificate
const char* fingerprint = "‎8f 16 94 46 f3 6b 83 4d 39 39 52 a9 ef 7f 31 4b bd 1b f6 49";

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.print("connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  // Use WiFiClientSecure class to create TLS connection
  WiFiClientSecure client;
  Serial.print("connecting to ");
  Serial.println(host);
  if (!client.connect(host, httpsPort)) {
    Serial.println("connection failed");
    return;
  }

  if (client.verify(fingerprint, host)) {
    Serial.println("certificate matches");
  } else {
    Serial.println("certificate doesn't match");
  }

  String url = "/repos/esp8266/Arduino/commits/master/status"; // это мне пока не важно, проблема выше
  Serial.print("requesting URL: ");
  Serial.println(url);

  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "User-Agent: BuildFailureDetectorESP8266\r\n" +
               "Connection: close\r\n\r\n");

  Serial.println("request sent");
  while (client.connected()) {
    String line = client.readStringUntil('\n');
    if (line == "\r") {
      Serial.println("headers received");
      break;
    }
  }
  String line = client.readStringUntil('\n');
  if (line.startsWith("{\"state\":\"success\"")) {
    Serial.println("esp8266/Arduino CI successfull!");
  } else {
    Serial.println("esp8266/Arduino CI has failed");
  }
  Serial.println("reply was:");
  Serial.println("==========");
  Serial.println(line);
  Serial.println("==========");
  Serial.println("closing connection");
}

void loop() {
}
В результате получаю ответ:
connecting to yandex.ru
certificate doesn't match
В чем беда? мб кто работал с https
 

Alexey888

New member
Чутка разобрался, вот тестовый код с данными:
Код:
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>

const char* ssid = "pp";
const char* password = "pwd";

//const char* host = "github.com";
//const char* host = "google.ru";
//const char* host = "yandex.ru";
//const char* host = "mail.ru";
//const char* host = "alfabank.ru";
//const char* host = "ozon.ru";
const char* host = "vk.com";


const int httpsPort = 443;

// Use web browser to view and copy
// SHA1 fingerprint of the certificate
//const char* fingerprint = "d7 9f 07 61 10 b3 92 93 e3 49 ac 89 84 5b 03 80 c1 9e 2f 8b"; //github.com
//const char* fingerprint = "da bd 42 db 58 2e 1d e6 3e 4f 08 65 8d 90 ec 46 48 06 ae 1f"; //google.ru
//const char* fingerprint = "8f 16 94 46 f3 6b 83 4d 39 39 52 a9 ef 7f 31 4b bd 1b f6 49"; //yandex.ru
//const char* fingerprint = "68 2c 40 44 35 17 41 55 76 a2 94 9d 48 6d 95 1c d8 6d 28 88"; //mail.ru
//const char* fingerprint = "a3 9a 27 a1 59 6c 72 2d 50 b5 ab 59 21 8e 3b 2a bb 7c b2 b5"; //alfabank.ru
//const char* fingerprint = "e7 e7 6f 15 6e 43 a5 1b 9a ed 6c d5 04 fe ed 23 c0 80 4f 05"; //ozon.ru
const char* fingerprint = "fb 9b af 57 f4 46 7c bf 90 80 e5 7a 18 6e 15 a3 0f 11 dd 9f"; //vk.com

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.print("connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
WiFiClientSecure client;
void loop() {

  Serial.print("connecting to ");
  Serial.println(host);
  if (!client.connect(host, httpsPort)) {
    Serial.println("connection failed");
  }
  else
  {
    Serial.println("OK");
    if (client.verify(fingerprint, host)) {
      Serial.println("certificate matches");
    } else {
      Serial.println("certificate doesn't match");
    }
  }

  delay(5000);
}
В итоге получились такие результаты:
Код:
///////////////////////////////////////////////////
WiFi connected
IP address:
192.168.1.146
connecting to github.com
OK
certificate matches
connecting to github.com
OK
certificate matches
connecting to github.com
OK
certificate matches
///////////////////////////////////////////////////
WiFi connected
IP address:
192.168.1.146
connecting to google.ru
// зависает при конекте, пробовал несколько раз
PORT CLOSED
///////////////////////////////////////////////////
WiFi connected
IP address:
192.168.1.146
connecting to yandex.ru
OK
certificate doesn't match
connecting to yandex.ru
OK
certificate doesn't match
connecting to yandex.ru
OK
certificate doesn't match
///////////////////////////////////////////////////
WiFi connected
IP address:
192.168.1.146
connecting to mail.ru
OK
certificate matches
connecting to mail.ru
OK
certificate matches
connecting to mail.ru
OK
certificate matches
connecting to mail.ru
OK
certificate matches
///////////////////////////////////////////////////
WiFi connected
IP address:
192.168.1.146
connecting to alfabank.ru
OK
certificate matches
connecting to alfabank.ru
OK
certificate matches
connecting to alfabank.ru
OK
certificate matches
connecting to alfabank.ru
OK
certificate matches
///////////////////////////////////////////////////
WiFi connected
IP address:
192.168.1.146
connecting to ozon.ru
OK
certificate matches
connecting to ozon.ru
OK
certificate matches
connecting to ozon.ru
OK
certificate matches
///////////////////////////////////////////////////
WiFi connected
IP address:
192.168.1.146
connecting to vk.com
connection failed
connecting to vk.com
connection failed
connecting to vk.com
connection failed
///////////////////////////////////////////////////
К некоторых случаях всё проходит на ура, в некоторых не чекает сертификат, ну и в худшем совсем не идет конект.
Вопрос, от чего такая картина? что за бред...
Надеюсь кто-нибудь поможет и внесет ясность. Спасибо.
 

ave

New member
А кто подскажет где берутся эти цифры? Я так понял это сертификаты.

//const char* fingerprint = "d7 9f 07 61 10 b3 92 93 e3 49 ac 89 84 5b 03 80 c1 9e 2f 8b"; //github.com
//const char* fingerprint = "da bd 42 db 58 2e 1d e6 3e 4f 08 65 8d 90 ec 46 48 06 ae 1f"; //google.ru
//const char* fingerprint = "8f 16 94 46 f3 6b 83 4d 39 39 52 a9 ef 7f 31 4b bd 1b f6 49"; //yandex.ru
//const char* fingerprint = "68 2c 40 44 35 17 41 55 76 a2 94 9d 48 6d 95 1c d8 6d 28 88"; //mail.ru
//const char* fingerprint = "a3 9a 27 a1 59 6c 72 2d 50 b5 ab 59 21 8e 3b 2a bb 7c b2 b5"; //alfabank.ru
//const char* fingerprint = "e7 e7 6f 15 6e 43 a5 1b 9a ed 6c d5 04 fe ed 23 c0 80 4f 05"; //ozon.ru
//const char* fingerprint = "fb 9b af 57 f4 46 7c bf 90 80 e5 7a 18 6e 15 a3 0f 11 dd 9f"; //vk.com

По этому примеру у меня выдает:

Connecting to: mail.ru
Connection Ok
Certificate Error
 
Последнее редактирование:

ave

New member
Сам разобрался. Эти цифры - это отпечаток сертификата, беруться из браузера на сайте.
 

pvvx

Активный участник сообщества
Сам разобрался. Эти цифры - это отпечаток сертификата, берутся из браузера на сайте.
Т.е. если обращаться на другой сайт HTTPS надо искать эти "отпечатки"?
Почему нельзя без этого:
Код:
#include <WiFi.h>
//char ssid[] = "yourNetwork"; //  your network SSID (name)
//char pass[] = "secretPassword";    // your network password (use for WPA, or use as key for WEP)
#include <myAP.h> // там прописаны pass и ssid и #define password pass для быстрой замены в разных примерах...
int keyIndex = 0;            // your network key Index number (needed only for WEP)

char server[] = "yandex.ru"; // "esp8266.ru"; // "github.com"; // "esp8266.ru";//  "yandex.ru"; //"www.google.com"; // "github.com";// name address for Google (using DNS)
//unsigned char test_client_key[] = "";   //For the usage of verifying client
//unsigned char test_client_cert[] = "";  //For the usage of verifying client
//unsigned char test_ca_cert[] = "";      //For the usage of verifying server

WiFiSSLClient client;

extern "C" void sys_info(void);

void setup() {
  // Connect to WPA/WPA2 network.
  while (WiFi.begin(ssid,pass) != WL_CONNECTED) {
    // wait 0.1 seconds for connection:
    delay(100);
  }
  Serial.println("Connected to wifi");
  if (client.connect(server, 443)) { //client.connect(server, 443, test_ca_cert, test_client_cert, test_client_key)
    Serial.println("connected to server");
    // Make a HTTP request:
    client.println("GET / HTTP/1.1"); // client.println("GET /search?q=realtek HTTP/1.0");
    client.print("Host: "); client.println(server); //    client.println("Host: www.google.com");
    client.println("Connection: close");
    client.println();
  }
  else
  Serial.println("connected to server failed");
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting from server.");
    client.stop();
    sys_info();
    Serial.println("End.");
    // do nothing forevermore:
    while (true);
  }
}
Код:
===== Enter Image 1.5 ====
Img2 Sign: RTKWin, InfaStart @ 0x1000604d
===== Enter Image 2 ====
CLK CPU         166666666 Hz
RAM heap        81504 bytes
TCM heap        64768 bytes
interface 0 is initialized
interface 1 is initialized

Initializing WIFI ...
WIFI initialized
RTL8195A[Driver]: set ssid [********]
RTL8195A[Driver]: start auth to **:**:**:**:**:**
RTL8195A[Driver]: auth success, start assoc
RTL8195A[Driver]: association success(res=3)
RTL8195A[Driver]: set pairwise key to hw: alg:4(WEP40-1 WEP104-5 TKIP-2 AES-4)
RTL8195A[Driver]: set group key to hw: alg:4(WEP40-1 WEP104-5 TKIP-2 AES-4) keyid:1
Interface 0 IP address : 192.168.1.122Connected to wifi
connected to server
HTTP/1.1 200 Ok
Date: Thu, 17 Nov 2016 16:37:00 GMT
Content-Type: text/html; charset=UTF-8
....
<!--n7.wfront.yandex.net--></body></html>
disconnecting from server.
CLK CPU         166666666 Hz
RAM heap        50096 bytes
TCM heap        27928 bytes
End.
Снимок24.gif
 
Последнее редактирование:
  • Like
Реакции: ave

Алексей.

Active member
Что такое продление сертификата?
Это выпуск нового с прежним ключом и новым сроком годности?
Технически это возможно, но практически не встречал. Отпечаток всё равно должен быть другим.
 

Belerafon

New member
Что такое продление сертификата?
Это выпуск нового с прежним ключом и новым сроком годности?
Технически это возможно, но практически не встречал. Отпечаток всё равно должен быть другим.
Изменился после продления сертификата Let's Encrypt он на 3 месяца дается. т.е. все эти отпечатки фигня получается. Соответственная старая прошивка больше не получит доступ к серверу. Как обойти этот отпечаток?
 
Сверху Снизу