I swear this is really the last article about ECDH’s Wen Er! (API Security Enhancement Part 4)

  api, ecdh, php, Safety

First of all, some time ago I was criticized by people (gang) in the public number. the general meaning is: you don’t always think that the ECDH is oval and prime. you just say how to use it in the actual project. we don’t want to listen to that. we all know and are proficient in it, and you are still a eunuch. see if you are a eunuch. the ECDH is obviously not finished in the last article. the result is not yet finished. you say whether you are a eunuch or not and you say it yourself.

Secondly, in fact, the content of this article has nothing to do with ECDH. The whole article is DH (two letters of EC are missing). However, the actual application of business logic in the project is written in the same way. You can now temporarily think DH is the “two-letter missing version” of ECDH. What is the main reason for using DH? Because of the limited time, I have given priority to writing the common language library files of DH, which are currently available. There is not a hair of ECDH, so I can only use DH for demonstration.

Finally, I would like to emphasize once again that, as a serious article, I need to popularize science once again about what DH means.

Many people think DH is short for Daemon Hunter, but it is not. Daemon Hunter, whose real name is Illidan, is blind and dei, brother of Fabio. He has a crush on Tyrande, a white tiger, but Tyrande is married to an old deer, which is probably the case.

DH is short for Diffie-Hellman here. I have posted the photos of the two big brothers before and now I have to post them again:

The above figure tells us that hair length has nothing to do with occupation. The short videos on douyin that think they get to the programmer’s stem are really LOWB’s mess.

Before the official start, I’d like to explain what DH was originally used for or what problems it was used to solve. Following the previous story (click here) said:

  • Your boss said that the project is very cow-force, the data should be encrypted, using cow-force encryption algorithm
  • You use RSA asymmetric encryption to develop and test the operation like a tiger
  • Then, on the line: the CPU blew up and scored 1-5
  • Then you ask your boss to approve the upgrade of the server. The boss gives you 300 yuan and makes you feel free to spend it boldly.
  • You first took RSA offline, then secretly replaced it with AES symmetric encryption, and the CPU did not explode
  • Then three hundred dollars were secretly put into his pocket.
  • However, if you write the symmetric key of AES to the client, it will be reversed. If distributed through the server, it sounds even more ridiculous.
  • Wanted to think, you take three hundred dollars to set up a game, you take the money, I take Chen Xu, laozhao with pillars, plus big tiger, just six people
  • At the office, I have disclosed a scheme to you: AES symmetric key is negotiated through asymmetric means. DH is a magic algorithm that allows your server and clien t to calculate a symmetric key by heart without transmitting the symmetric key. It can also prevent the key from circulating on the network, and you can change it at will. The expiration time is set at 1 minute, which is extremely vicious.

We introduced DH to solve the above problems. However, DH or ECDH cannot solve the problem of man-in-the-middle attacks, and this should be understood.

Therefore, before the official start, I must first use Amway, the big clients in northeast China and the DH library featuring Giant Moth and Arnie. github link is this. I will use these DH libraries for demo below.

https://github.com/ti-dh
(The discerning people have already seen that I have come to cheat star)

At present, this library provides PHP extensions and Java versions implemented in pure PHP and C. List a table:

图片描述

First, let’s talk about the overall process of negotiation between the server and the client, which is very, very simple:

In the whole negotiation process, only the second step and the third step will have data interaction. The second step is that API issues P, G and server-num to the client. The third step is that the client submits client-num data to the API; In the last step, the key for symmetric encryption and decryption has been calculated and used in the production environment.

Next, I will demonstrate how to use this ghost in the best language in the world. What demonstration shall we use at the client? The client still uses the best language in the world to demonstrate. First of all, you integrate the library files in github into your API. The code is as follows:

API demo code:

<?php
class DhController extends BaseController{

  private $dh = null;

  // 将DH库初始化进来呀...
  public function init() {
    $this->dh = new Dh();
  }

  // 这就是上图中的第二步:客户端访问这个API获取g p 和 server-num
  public function getdhbasedataAction() {
    $ret = $this->dh->getdhbasedata();
    echo json_encode( $ret );
  }

  // 这就是上图中的第三步:客户端通过这个api提交client-num参数
  public function postdhclientdataAction() {
    if ( $this->getRequest()->isPost() ) {
      if ( empty( $_POST['client_number'] ) || !is_numeric( $_POST['client_number'] ) ) {
        exit( json_encode( array(
          'code'    => -1,
          'message' => 'wrong parameters',
        ) ) );
      }
      $ret = $this->dh->postdhclientdata( $_POST );
      echo json_encode( array(
        'key' => $ret,
      ) );
    }
  }

}

Client demo code:

<?php
require __DIR__ . '/vendor/autoload.php';
use \Curl\Curl;
$curl = new Curl();
// 初始化客户端数据,随机一个即可~
$client_number = mt_rand( 100000, 999999 );
// 1、第一步,获取服务器的p、g和server_number
$ret = $curl->get( 'https://xxxx.ooo/dh/getdhbasedata' );
$ret = json_decode( $ret, true );
$p = $ret['p'];
$g = $ret['g'];
$server_number = $ret['server_number'];
// 2、第二步,根据服务器获取到的数据计算出client-number
$process_client_number = gmp_powm( $g, $client_number, $p );
// 3、第三步,将计算过后的client-number发送给服务器
// 那个demo里已经有完美的演示了,多看代码
$ret = $curl->post( 'https://xxxx.ooo/dh/postdhclientdata', array(
  'client_number' => gmp_strval( $process_client_number ),
) );
$ret = json_decode( $ret, true );
// 4、第四步,根据server-number,client-number和p 计算出公共密钥K
$key = gmp_powm( $server_number, $client_number, $p );
echo PHP_EOL."DH非对称密钥产生交换:".PHP_EOL;
echo 'client计算出的public key : '.$key.PHP_EOL;
echo 'server计算出的public key : '.$ret['key'].PHP_EOL.PHP_EOL;

The client file is saved to client.php, and then PHP client.php executes it. As a result, you can feel it:

Is it the same? ! The calculations are all the same, is there? ! !

In the above picture, the number of nausea and vomiting is the symmetric encryption and decryption key calculated by API and client respectively. Please note that the server must not return this data to the client during actual use. demo is only doing this for demonstration and needs to use its own brain.

However, things are often not said to be as simple as that. If it is used in a production environment, it is still necessary to continue to improve some details.

  • The first question is whether the key calculated by the two clients will be the same if some babies who think more will be different. The possibility is very, very small.
  • The second problem is that the users who log on to the client usually have their own token or uid, etc. API can store the key in redis in the format of “token:key” after negotiating a key with a client, and then give a valid time such as 30 minutes. The client also saves the key into the mobile phone memory and sets a 30-minute validity period. Each time before encrypting and decrypting with key, verify whether it has expired. if it has expired, go through the previous negotiation process again.

I swear, this is the last article on DH or ECDH. I will never write anything related to these two English abbreviations again. What I said is true. I promise to do what I said.

Welcome to the public, please give me your name and challenge me:

图片描述