Reputation: 43
I have to decrypt the encrypted SEK using APP key and encode JSON data using decrypted SEK to post for E-invoice Generation and sample code for Java and C# and I have converted in PHP but unfortunately failed to get desired output in PHP OpenSSL is not supported from my point as I am trying from last week
Sample JAVA & C# Code For Encryption and decryption
https://einv-apisandbox.nic.in/sample-code-in-java.html https://einv-apisandbox.nic.in/sample-code-in-c-sharp-dot-net.html
The goal is to decrypt and encrypt data using OpenSSL in PHP
my implementation as of now -
public function encrypt1($data, $secret_key)
{
return base64_encode(openssl_encrypt(base64_decode($data), $method='AES-256-ECB', base64_decode($secret_key), OPENSSL_RAW_DATA));
}
public function decrypt1($data,$secret_key)
{
return base64_encode(openssl_decrypt(base64_decode($data), $method='AES-256-ECB', $secret_key, OPENSSL_RAW_DATA));
}
Upvotes: 2
Views: 798
Reputation: 49390
The decryption of the session key (SEK) with the AppKey is possible in PHP as follows:
function decryptBySymmetricKey($encSekB64, $appKey) {
$sek = openssl_decrypt($encSekB64, "aes-256-ecb", $appKey, 0); // the SEK
$sekB64 = base64_encode($sek); // the Base64 encoded SEK
return $sekB64;
}
The encryption of data with the SEK is possible in PHP as follows:
function encryptBySymmetricKey($dataB64, $sekB64){
$data = base64_decode($dataB64); // the data to encrypt
$sek = base64_decode($sekB64); // the SEK
$encDataB64 = openssl_encrypt($data, "aes-256-ecb", $sek, 0); // the Base64 encoded ciphertext
return $encDataB64;
}
Both functions can be tested with the following data:
$appKey = 'fao1PoKaLgd11xMrWTiL2cggAfx9QMwM'; // the 32 bytes AppKey
$encSekB64 = 'oRvKfBtmgNTSuk/oXUhiLOjXi45jiWA2oKNxhhQM3UH2o/32YWGLbUjK1/dohPe3'; // the Base64 encoded encrypted SEK
$dataB64 = 'VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZw=='; // the base64 encoded data
$sekB64 = decryptBySymmetricKey($encSekB64, $appKey); // the Base64 encoded SEK
$encDataB64 = encryptBySymmetricKey($dataB64, $sekB64); // the Base64 encoded ciphertext
echo $sekB64 . "\n"; // zVoede7m2nnvMHcWYIfKhrvsilSFEZYiltJmxVQQnAQ=
echo $encDataB64; // JS+hxYf64FMHThrhoIejqk3VjGwFw+GTYzUyVKc6GEOLKERVuvaNY91zPdo829r0
Comparison with C# reference code:
The linked C# methods DecryptBySymmetricKey
and EncryptBySymmetricKey
return with
byte[] appKey = Encoding.UTF8.GetBytes("fao1PoKaLgd11xMrWTiL2cggAfx9QMwM");
string encSekB64 = "oRvKfBtmgNTSuk/oXUhiLOjXi45jiWA2oKNxhhQM3UH2o/32YWGLbUjK1/dohPe3";
string dataB64 = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZw==";
string sekB64 = DecryptBySymmetricKey(encSekB64, appKey);
string encDataB64 = EncryptBySymmetricKey(dataB64, sekB64);
Console.WriteLine(sekB64); // zVoede7m2nnvMHcWYIfKhrvsilSFEZYiltJmxVQQnAQ=
Console.WriteLine(encDataB64); // JS+hxYf64FMHThrhoIejqk3VjGwFw+GTYzUyVKc6GEOLKERVuvaNY91zPdo829r0
the same values.
Upvotes: 2