Knowledge Share Helps you in some way
Aes ecb encrypt and decrypt gst php

Aes ecb encrypt and decrypt gst php

Friday, 8 January 2021 |

AES

AES (Advanced Encryption Standard) is a symmetric encryption algorithm widely used for securing sensitive data. It provides a robust level of security and is adopted as a standard encryption technique in various applications.

ECB Mode

ECB (Electronic Codebook) mode is one of the simplest block cipher modes of operation in AES. In ECB mode, each block of plaintext is encrypted independently using the same encryption key. While this mode is straightforward to implement, it has certain vulnerabilities, such as susceptibility to pattern recognition and lack of diffusion.

If you are using any third party API which communicate with developer.gst.gov.in to fill up your gstr1,gstr3b data. encryption & decryption plays role to read data and to access data and to submit data.Codeigniter Web Framework with REST Controller Library with php curl library will be use full. You can easily configure rest conroller and curl in codeiginter with checks of security. Class otp has a funciton call_curl , your $api_settings will be store in database , $ip_user, $gstin_no, $user_name, $api_type are the request parameter of webservice.

certificate_file_path is your file path of certificate file for production and for sandbox. PRODUCTION_OTPREQUEST , SANDBOX_OTPREQUEST are the constant which you can define in constant configuration file in codeiginiter. it will denote the url of production and sandbox.

									     
require_once APPPATH . 'core/REST_Controller.php';
require_once APPPATH . 'libraries/phpcurl/vendor/autoload.php';
use \Curl\Curl;
class Otp extends REST_Controller {
    public $today = '';
    public function __construct() {
        parent::__construct();
    }
    function call_curl($api_settings, $ip_user, $gstin_no, $user_name, $api_type) {
        require_once APPPATH . 'libraries/phpcurl/GstApiEnc.php';
        if ($api_type == 'sandbox') {
            $certificate_file_path = APPPATH . 'cert/sandbox/GSTN_G2A_SANDBOX_UAT_public.cer';
            define('OTPREQUEST', SANDBOX_OTPREQUEST);
        } else if ($api_type == 'production') {
            $certificate_file_path = APPPATH . 'cert/production/GSTN_G2B_Prod_Public.cer';
            define('OTPREQUEST', PRODUCTION_OTPREQUEST);
        } else {
            $certificate_file_path = "";
            define('OTPREQUEST', '');
        }

        $generated_key = GstApiEnc::keygen(32);
        $appKey = GstApiEnc::generateappKey(base64_decode($generated_key), $certificate_file_path);
        $transaction_id = str_replace(".", "", microtime(true)) . rand(000, 999);
        $state_cd = substr($gstin_no, 0, 2);
        $curl = new Curl();
        $curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
        $curl->setOpt(CURLOPT_RETURNTRANSFER, true);
        $curl->setDefaultJsonDecoder($assoc = true);
        $curl->setHeader('content-type', 'application/json');
        $curl->setHeader('ip-usr', $ip_user);
        $curl->setHeader('client-secret', $api_settings[0]['client_secret']);
        $curl->setHeader('txn', $transaction_id);
        $curl->setHeader('clientid', $api_settings[0]['client_id']);
        $curl->setHeader('state-cd', $state_cd);
        $curl->setHeader('username', $user_name);
        $curl->setHeader('gstin', $gstin_no);
        $curl->setHeader('ocp-apim-subscription-key', $api_settings[0]['ocp_apim_subscription_key']);
        $data_otpreq = array(
            'action' => 'OTPREQUEST',
            'app_key' => $appKey,
            'username' => $user_name,
        );

        $result_otpreq = $curl->post(OTPREQUEST, $data_otpreq);
        $response_type = is_string($result_otpreq) ? 1 : 0;
        if ($response_type === 0) {
            if ($result_otpreq['status_cd'] == 0 || $result_otpreq['status_cd'] == 401) {
                $result_otpreq['method'] = 'OTPREQUEST';
            } else {
                $result_otpreq['method'] = 'OTPREQUEST';
                $result_otpreq['generated_key'] = $generated_key;
                $result_otpreq['appKey'] = $appKey;
                $result_otpreq['txn'] = $transaction_id;
            }
        }else{
            $string = preg_replace('/\s+/', '', $result_otpreq);
            $result['status_cd'] = 0;
            $result['error']['messages']= strip_tags($string);
            $result_otpreq=$result;
        }
        $curl->close();
        return $result_otpreq;
    }
}
										
									

GstApiEnc class has couples of method which decrept and encrept with AES-256-ECB. you can further also used class for other method of gst.

									     
class GSTAPIENC {
    static function generateappKey ($appkey,$filepath){
        openssl_public_encrypt($appkey, $encrypted, file_get_contents($filepath));
        return base64_encode($encrypted);
    }
    static function encryptOTP($otp_code,$appkey) {
       return base64_encode(openssl_encrypt($otp_code, "AES-256-ECB", $appkey, OPENSSL_RAW_DATA));
    }
    static function encryptData($data, $key) {
        return base64_encode(openssl_encrypt($data, "AES-256-ECB", $key, OPENSSL_RAW_DATA));
    }
    static function mac256($ent, $key) {
        $res = hash_hmac('sha256', $ent, $key, true); 
        return $res;
    }
    static function decryptData($data, $key) {
        return openssl_decrypt(base64_decode($data), "AES-256-ECB", $key, OPENSSL_RAW_DATA);
    }
    static function decodeJsonResponse($out, $rek, $ek) {
        $apiEK = GSTAPIENC::decryptData($rek, $ek);
        return base64_decode(GSTAPIENC::decryptData($out, $apiEK));
    }
    static function keygen($length = 10) {
        $key = '';
        list($usec, $sec) = explode(' ', microtime());
        mt_srand((float) $sec + ((float) $usec * 100000));

        $inputs = array_merge(range('z', 'a'), range(0, 9), range('A', 'Z'));

        for ($i = 0; $i < $length; $i++) {
            $key .= $inputs{mt_rand(0, 61)};
        }
        return base64_encode($key);
    }
}										
									

Conclusion

AES ECB encryption and decryption in PHP provide a straightforward approach to securing data. However, it is crucial to understand the limitations of ECB mode and consider alternative modes such as CBC (Cipher Block Chaining) for better security, especially when encrypting sensitive information. By implementing AES encryption and decryption securely in your PHP applications, you can safeguard sensitive data against unauthorized access and ensure data privacy and integrity.

Codeigniter