API interface encryption method, using AES

In order to prevent the disclosure of plaintext submitted to the interface, you can encrypt the data submitted to the interface, and you can use the AES encryption algorithm.

Encryption method:

All submitted data is encrypted using AES encryption algorithm + Base64 (base64UrlEncode) algorithm:

1.AES encryption parameters:

Encryption mode: AES-128-ECB (more secure AES-128-CBC available)

Vector IV: null (required for AES-128-CBC)

Key Key: “123456789” (Do not leak)

Fill: PKCS7 (PKCS7 results the same as PKCS5)

2.Encryption steps:

  • AES encryption of data.
  • Base64 (base64UrlEncode) encryption of AES-encrypted data.

3.Encryption example:

1) Raw data: “hello world”

2) AES encrypted data: “bH� �G:9�i_x0005_��”

3) base64UrlEncode encrypted data: “ducL9jnRX1De2o15_xw6xg”

PHP code:

<?php
//$key previously generated safely, ie: openssl_random_pseudo_bytes
$key='123456789';
 
   /**
     * base64UrlEncode   https://jwt.io/ base64UrlEncode encoding implementation
     * @param string $input The string that needs to be encoded
     * @return string
     */
     function base64UrlEncode($input)
    {
        return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
    }

    /**
     * base64UrlEncode  https://jwt.io/ base64UrlEncode decoding implementation
     * @param string $input The string that needs to be decoded
     * @return bool|string
     */
     function base64UrlDecode($input)
    {
        $remainder = strlen($input) % 4;
        if ($remainder) {
            $addlen = 4 - $remainder;
            $input .= str_repeat('=', $addlen);
        }
        return base64_decode(strtr($input, '-_', '+/'));
    }
$plaintext="hello world";
 //$cipher = "aes-128-cbc";
 $cipher = "aes-128-ecb";

if (in_array($cipher, openssl_get_cipher_methods()))
{
     
     
    // $iv='1111111111111111';
    $iv='';
    $ciphertext = openssl_encrypt($plaintext, $cipher, $key, OPENSSL_RAW_DATA, $iv);//If you remove the OPENSSL_RAW_DATA parameter, the base64 encoded one is directly output, and no more base64 encoded is required
    $ciphertext =base64UrlEncode($ciphertext);
    //store $cipher, $iv, and $tag for decryption later
    $original_plaintext = openssl_decrypt(base64UrlDecode($ciphertext), $cipher, $key, OPENSSL_RAW_DATA, $iv);


    var_dump( $original_plaintext);
    var_dump( $ciphertext);
}

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *