I am trying to convert VB.NET Encrypt/Decrypt to PHP. The issue is we can not update the PHP version and the server supports only PHP5.3
VB.NET Sample Output Link
http://www.tattoogenda.com/LoginTest.aspx
VB.NET Output is: Ao5ZnFYo344iWqv/Jr9euw==
PHP OutPut is: NzmRRxTaXgWFIPx/SqODog==
VB.NET Code as below:
Public Shared Function Encrypt(clearText As String) As String
Dim EncryptionKey As String = "MAKV2SPBNI99212"
Dim clearBytes As Byte() = Encoding.Unicode.GetBytes(clearText)
Using encryptor As Aes = Aes.Create()
Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D,
&H65, &H64, &H76, &H65, &H64, &H65,
&H76})
encryptor.Key = pdb.GetBytes(32)
encryptor.IV = pdb.GetBytes(16)
Using ms As New MemoryStream()
Using cs As New CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)
cs.Write(clearBytes, 0, clearBytes.Length)
cs.Close()
End Using
clearText = Convert.ToBase64String(ms.ToArray())
End Using
End Using
Return clearText
End Function
Public Shared Function Decrypt(cipherText As String) As String
Dim EncryptionKey As String = "MAKV2SPBNI99212"
Dim cipherBytes As Byte() = Convert.FromBase64String(cipherText)
Using encryptor As Aes = Aes.Create()
Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D,
&H65, &H64, &H76, &H65, &H64, &H65,
&H76})
encryptor.Key = pdb.GetBytes(32)
encryptor.IV = pdb.GetBytes(16)
Using ms As New MemoryStream()
Using cs As New CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)
cs.Write(cipherBytes, 0, cipherBytes.Length)
cs.Close()
End Using
cipherText = Encoding.Unicode.GetString(ms.ToArray())
End Using
End Using
Return cipherText
End Function
PHP Test link Output:
http://www.tattoogenda.com/app-api/logintest.php
PHP Code:
<?php
include_once('PBKDF2.php');
use PBKDF2\PBKDF2;
function encrypt_decrypt($action, $string) {
$output = false;
$encrypt_method = "AES-256-CBC";
//$encrypt_method = "AES-128-CBC";
$secret_key = 'MAKV2SPBNI99212';
$secret_iv=chr(0x49).chr(0x76).chr(0x61).chr(0x6e).chr(0x20).chr(0x4d).chr(0x65).chr(0x64).chr(0x76).chr(0x65).chr(0x64).chr(0x65).chr(0x76);
$generated_key = PBKDF2::deriveKey("sha256", $secret_key, $secret_iv, 20000, 128, true, false);
$key = substr($generated_key, 0, 32);;
//$key = substr(hash('sha1', $secret_key), 0, 32);;
echo "key: ".$key."<br>";
$iv = substr($generated_key, 0, 16);
//$iv = substr(hash('sha1', $secret_iv), 0, 16);
echo "iv key: ".$iv."<br>";
if( $action == 'encrypt' ) {
$output = openssl_encrypt($string, $encrypt_method, $key, $options=OPENSSL_RAW_DATA,$iv );
$output = base64_encode($output);
}
else if( $action == 'decrypt' ){
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, $options=OPENSSL_RAW_DATA, $iv);
}
return $output;
}
$plain_txt = "1234";
echo "Plain Text = $plain_txt\n"."<br/>";
$plain_txt = mb_convert_encoding($plain_txt, "UTF-8" , "UTF-16LE");
echo "Encoded Plain Text = $plain_txt\n"."<br/>";
$encrypted_txt = encrypt_decrypt('encrypt', $plain_txt);
echo "Encrypted Text = $encrypted_txt\n"."<br/>";
$decrypted_txt = encrypt_decrypt('decrypt', $encrypted_txt);
echo "Decrypted Text = $decrypted_txt\n"."<br/>";
if( $plain_txt === $decrypted_txt ) echo "SUCCESS"."<br/>";
else echo "FAILED"."<br/>";
echo "\n"."<br/>";
?>
The VB code uses a 32 bytes key so in the PHP code AES-256-CBC is correct. Also Rfc2898DeriveBytes() applies an iteration count of 1000 by default (and SHA1 as digest), which must therefore also be used in the PHP code. Since the VB code derives both, the 32 bytes key and the IV, 32 + 16 must be specified as size in the PHP code:
$generated_key = PBKDF2::deriveKey("sha1", $secret_key, $secret_iv, 1000, 32+16, true, false);
Of the returned result, the first 32 bytes are the key, the following 16 bytes are the IV:
$key = substr($generated_key, 0, 32);
$iv = substr($generated_key, 32, 16);
$key and $iv are to be used directly in openssl_encrypt()/decrypt(), i.e. the explicit hashing with SHA1 is to be removed for key and IV.
The passed plaintext must be UTF-16LE encoded before encryption (either inside or outside of encrypt_decrypt()), e.g. with
$string = mb_convert_encoding($string, 'utf-16le', 'utf-8');
Note that the start encoding is the third parameter and the destination encoding is the second parameter.
An encryption of Hello Asif returns 1N1U0Oy81PGOm/Yqdp9sT5iyPgPFxsc8Q8mADNa8BzQ= in accordance with the VB code.
For decryption, the procedure is analogous.
Note that for security reasons the salt (denoted here as $secret_iv) should be randomly generated for each key derivation. The salt is not secret and can be sent along with the ciphertext (usually concatenated). Also, an iteration count of 1000 is generally too small for PBKDF2.
<?php
$text = "hello";
$enc = MCRYPT_RIJNDAEL_128;
$mode = MCRYPT_MODE_CBC;
$iv = mcrypt_create_iv(mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM);
$keys = array();
// smaller than 128 bit key gets padded to 128 bit
$keys[] = pack('H*', "00112233445566778899aabbccddee");
$keys[] = pack('H*', "00112233445566778899aabbccddee00");
// larger than 128 bit key gets padded to 192 bit
$keys[] = pack('H*', "00112233445566778899aabbccddeeff00");
$keys[] = pack('H*', "00112233445566778899aabbccddeeff0000000000000000");
// larger than 192 bit key gets padded to 256 bit
$keys[] = pack('H*', "00112233445566778899aabbccddeeff001122334455667700");
$keys[] = pack('H*', "00112233445566778899aabbccddeeff00112233445566770000000000000000");
// larger than 256 bit key will be truncated (with a warning)
$keys[] = pack('H*', "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff00");
foreach ($keys as $key)
{ echo base64encode(mcrypt_encrypt($enc, $key, $text, $mode, $iv))."\n";
}
Related
I'm trying to write logic with Elixir and PHP to encrypt and decrypt text. My goal is to decrypt data which is encrypted in Elixir and vice versa. Both algorithms works fine, but the only problem I'm encountering is separating Initialization Vector from cipher text and conversion of binary to string in PHP and also decrypted text in Elixir.
Elixir Implementation:
defmodule Crypto.AES do
#block_size 16
#secret_key "something secret here"
def encrypt(text) do
secret_key_hash = make_hash(#secret_key, 32)
IO.inspect secret_key_hash
# create random Initialisation Vector
iv = :crypto.strong_rand_bytes(#block_size)
text = pad_pkcs7(text, #block_size)
encrypted_text = :crypto.crypto_one_time(:aes_256_cbc, secret_key_hash, iv, text, true )
encrypted_text = ( iv <> <<"::">> <> encrypted_text )
Base.encode64(encrypted_text)
end
def decrypt(ciphertext) do
secret_key_hash = make_hash(#secret_key, 32)
{:ok, ciphertext} = Base.decode64(ciphertext)
<<iv::binary-16, rp::binary-2, ciphertext::binary>> = ciphertext
decrypted_text = :crypto.crypto_one_time(:aes_256_cbc, secret_key_hash, iv, ciphertext, false)
unpad_pkcs7(decrypted_text)
end
#doc """
Pad the `message` by extending it to the nearest `blocksize` boundary,
appending the number of bytes of padding to the end of the block.
If the original `message` is a multiple of `blocksize`, an additional block
of bytes with value `blocksize` is added.
"""
def pad_pkcs7(message, blocksize) do
pad = blocksize - rem(byte_size(message), blocksize)
message <> to_string(List.duplicate(pad, pad))
end
#doc """
Remove the PKCS#7 padding from the end of `data`.
"""
def unpad_pkcs7(data) do
<<pad>> = binary_part(data, byte_size(data), -1)
binary_part(data, 0, byte_size(data) - pad)
end
def make_hash(text, length) do
:crypto.hash(:sha512, text)
|> Base.encode16
|> String.downcase
|> String.slice(0, length)
end
end
PHP Implementation:
<?php
$ENCRYPTION_KEY = 'something secret here';
$ENCRYPTION_ALGORITHM = 'AES-256-CBC';
function encrypt($plain_text) {
global $ENCRYPTION_KEY;
global $ENCRYPTION_ALGORITHM;
$EncryptionKey = make_hash($ENCRYPTION_KEY, 32);
// create random Initialisation Vector
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($ENCRYPTION_ALGORITHM));
$encrypted_text = openssl_encrypt(
$plain_text,
$ENCRYPTION_ALGORITHM,
$EncryptionKey,
0,
$iv
);
return base64_encode($encrypted_text . '::' . $iv);
}
function decrypt($ciphertext) {
global $ENCRYPTION_KEY;
global $ENCRYPTION_ALGORITHM;
$EncryptionKey = make_hash($ENCRYPTION_KEY, 32);
$split = explode('::', base64_decode($ciphertext), 2);
list($iv, $encrypted_text) = array_pad($split, 2, null);
$plain_text = openssl_decrypt(
$encrypted_text,
$ENCRYPTION_ALGORITHM,
$EncryptionKey,
0,
$iv
);
return $plain_text;
}
function make_hash($text, $length) {
$hash_key = hash("sha512", $text, false);
return substr($hash_key,0,$length);
}
$ct = encrypt("hello");
// echo $ct."\n";
echo decrypt("Sr4nMnMdDHhUQcnW6RwZ2Do6rhBh/ytW1W/x7Xx2/Xrv3A==")."\n";
?>
Please suggest some possible solutions. Thanks
The two codes are incompatible for two reasons:
The PHP code returns the ciphertext Base64 encoded by default during encryption. This must be disabled because the Base64 encoding is performed explicitly after the concatenation of IV and ciphertext. Disabling is possible by passing OPENSSL_RAW_DATA as 4th parameter in openssl_encrypt(). The same applies for decryption:
$encrypted_text = openssl_encrypt(
$plain_text,
$ENCRYPTION_ALGORITHM,
$EncryptionKey,
OPENSSL_RAW_DATA, // Fix: Don't Base64 encode the ciphertext
$iv
);
...
$plain_text = openssl_decrypt(
$encrted_text,
$ENCRYPTION_ALGORITHM,
$EncryptionKey,
OPENSSL_RAW_DATA, // Fix: Don't Base64 decode the ciphertext
$iv
);
As already noted in the comment, both codes assume a different order of IV and ciphertext when separating during decryption. Menwhile you have adapted the separation during decryption in the PHP code to that of the Elixir code.
But also for encryption, both codes use a different order of IV and ciphertext. The modification of the PHP code concerning the encryption is still missing:
...
return base64_encode($iv . '::' . $encrypted_text); // Reverse order
With these changes, the two codes are functionally identical and a ciphertext generated with the PHP code can be decrypted with the Elixir code and vice versa.
A note regarding concatenation: Both the IV and ciphertext can contain the separator :: with a certain probability, which can cause problems. It would be better to concatenate the data without a separator and use the known length of the IV for the separation.
Also, using a hash function for key derivation is insecure, better apply a reliable key derivation function like PBKDF2. Furthermore, taking the hex encoded key instead of the binary data reduces security.
With suggestions (except PBKDF2, will add later) from #Topaco, here's complete solution.
Elixir - git-link
defmodule Crypto.AES do
#block_size 16
#secret_key "put something secret here"
def encrypt(plain_text) do
secret_key_hash = make_hash(#secret_key, 32)
# create Initialisation Vector
iv = :crypto.strong_rand_bytes(#block_size)
padded_text = pad_pkcs7(plain_text, #block_size)
encrypted_text = :crypto.crypto_one_time(:aes_256_cbc, secret_key_hash, iv, padded_text, true )
# concatenate IV for decryption
encrypted_text = ( iv <> encrypted_text )
Base.encode64(encrypted_text)
end
def decrypt(ciphertext) do
secret_key_hash = make_hash(#secret_key, 32)
{:ok, ciphertext} = Base.decode64(ciphertext)
<<iv::binary-16, ciphertext::binary>> = ciphertext
decrypted_text = :crypto.crypto_one_time(:aes_256_cbc, secret_key_hash, iv, ciphertext, false)
unpad_pkcs7(decrypted_text)
end
defp pad_pkcs7(message, blocksize) do
pad = blocksize - rem(byte_size(message), blocksize)
message <> to_string(List.duplicate(pad, pad))
end
defp unpad_pkcs7(data) do
<<pad>> = binary_part(data, byte_size(data), -1)
binary_part(data, 0, byte_size(data) - pad)
end
defp make_hash(text, length) do
:crypto.hash(:sha512, text)
|> Base.encode16
|> String.downcase
|> String.slice(0, length)
end
end
PHP - gist-link
<?php
$ENCRYPTION_KEY = "put something secret here";
$ENCRYPTION_ALGORITHM = 'AES-256-CBC';
function encrypt($plain_text) {
global $ENCRYPTION_KEY;
global $ENCRYPTION_ALGORITHM;
$EncryptionKey = make_hash($ENCRYPTION_KEY, 32);
// create random Initialization Vector
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($ENCRYPTION_ALGORITHM));
$encrypted_text = openssl_encrypt(
$plain_text,
$ENCRYPTION_ALGORITHM,
$EncryptionKey,
OPENSSL_RAW_DATA,
$iv
);
# concatenate the IV for decryption
return base64_encode($iv . $encrypted_text);
}
function decrypt($ciphertext) {
global $ENCRYPTION_KEY;
global $ENCRYPTION_ALGORITHM;
$EncryptionKey = make_hash($ENCRYPTION_KEY, 32);
$ciphertext = base64_decode($ciphertext);
// get Initialization Vector part (16 bytes long)
$iv = substr($ciphertext, 0, 16);
// rest is actual cipher text
$ciphertext = substr($ciphertext, 16);
$decrypted_text = openssl_decrypt(
$ciphertext,
$ENCRYPTION_ALGORITHM,
$EncryptionKey,
OPENSSL_RAW_DATA,
$iv
);
return $decrypted_text;
}
function make_hash($text, $length) {
$hash_key = hash("sha512", $text, false);
return substr($hash_key,0,$length);
}
// $ct = encrypt("code");
// $dt = decrypt($ct);
// echo $ct."\n";
// echo $dt."\n";
?>
I have an encrypted string and its key, which is created with SQL Server using "EncryptByPassPhrase", how can i decrypt it in PHP?
I have read the documentation of "EncryptByPassPhrase" which states that this is Triple DES encryption of 128 Length. I tried 3DES decryption of PHP but it is not returning the expected output.
Encryption in MS SQL is done with
declare #encrypt varbinary(200)
select #encrypt = EncryptByPassPhrase('key', 'taskseq=10000&amt=200.5' )
select #encrypt
I am decrypting it in PHP as following:
function decryptECB($encrypted, $key) {
$iv_size = mcrypt_get_iv_size(MCRYPT_3DES, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
// decrypting
$stringText = mcrypt_decrypt(MCRYPT_3DES, $key, $encrypted,
MCRYPT_MODE_ECB, $iv);
return $stringText;
}
I took the liberty of translating this Stack Overflow answer into PHP.
This is the result:
<?php
// SQL Server's DecryptByPassphrase translated into PHP.
function decrypt(string $data, string $password): ?string {
// SQL Server <2017 uses SHA1 for the key and the DES-EDE-CBC crypto algorithm
// whereas SQL Server >= 2017 uses SHA256 and AES-256-CBC.
// Version 1 is the SHA1 + DES-EDE-CBC version, Version 2 is the AES-256-CBC version.
// Version is stored in the first four bytes as a little endian int32.
$version_bytes = substr($data, 0, 4);
$version = unpack('V', $version_bytes)[1];
// Password must be converted to the UTF-16LE encoding.
$passwordUtf16 = mb_convert_encoding($password, 'UTF-16LE');
if ($version === 1) {
// Key is hashed using SHA1, The first 16 bytes of the hash are used.
$key = substr(hash('sha1', $passwordUtf16, true), 0, 16);
$method = 'des-ede-cbc';
$options = OPENSSL_RAW_DATA;
$iv = substr($data, 4, 8); // initialization vector of 8 bytes
$encrypted_data = substr($data, 12); // actual encrypted data
} else if ($version === 2) {
// Key is hashed using sha256. Key length is always 32 bytes.
$key = hash('sha256', $passwordUtf16, true);
$method = 'aes-256-cbc';
$options = OPENSSL_RAW_DATA;
$iv = substr($data, 4, 16); // iv of 16 bytes
$encrypted_data = substr($data, 20);
} else {
throw new \InvalidArgumentException('Invalid version');
}
$decrypted = openssl_decrypt($encrypted_data, $method, $key, $options, $iv);
if ($decrypted === false) {
return null;
}
// First 8 bytes contain the magic number 0xbaadf00d and the length
// of the decrypted data
$decrypted = substr($decrypted, 8);
// UTF-16 encoding should be converted to UTF-8. Note that
// there might be a better way to accomplish this.
$isUtf16 = strpos($decrypted, 0) !== false;
if ($isUtf16) {
return mb_convert_encoding($decrypted, 'UTF-8', 'UTF-16LE');
}
return $decrypted;
}
// A version 1 encrypted string. Taken directly from the Stack Overflow answer linked above
$s = '010000007854E155CEE338D5E34808BA95367D506B97C63FB5114DD4CE687FE457C1B5D5';
$password = 'banana';
$bin = hex2bin($s);
$d = decrypt($bin, $password);
var_dump($d); // string(6) "turkey"
// A version 2 encrypted string. Taken directly from the Stack Overflow answer linked above
$s = '02000000266AD4F387FA9474E825B013B0232E73A398A5F72B79BC90D63BD1E45AE3AA5518828D187125BECC285D55FA7CAFED61';
$password = 'Radames';
$bin = hex2bin($s);
$d = decrypt($bin, $password);
var_dump($d); // string(16) "LetTheSunShining"
Sidenote: mcrypt is deprecated as it has been abandoned for over a decade.
EncryptByPassPhrase() uses a proprietary format that don't seem to have readily available documentation. Best bet for decrypt is DecryptByPassPhrase().
The purpose of this proprietary format is to be used in the database layer of your application - not cross application / network / languages.
If you are dead set of using this format (which i would recommend not to), you would need to obtain the specification of this format, including what kind of key deviation functions are used to turn passwords into actual encryption keys etc.
When you have this specification, you would then have to implement this on your own.
Use the below in query
DECRYPTBYPASSPHRASE('key', [field] )
Reference
I have problem decrypting data in pgcrypto that was previously encrypted in PHP app.
I tried 3 types of encryption:
1) mcrypt - RIJNDAEL 128 CBC
2) mcrypt - RIJNDAEL 256 CBC
3) openssl_encrypt - aes-256-cbc
everything is encrypted decrypted fine in PHP, but in pgcrypto I can decrypt using same key and iv only 1) mcrypt - RIJNDAEL 128 CBC
Here is example code for PHP part:
<?php
function d ($data, $key, $mode) {
$data = #base64_decode($data);
$pad = $mode == MCRYPT_RIJNDAEL_256 ? 32 : 16;
$iv = mb_substr($data, 0, $pad, "8bit");
$data = mb_substr($data, $pad, mb_strlen($data, "8bit"), "8bit");
if ($data === null || $data === "") {
return $data;
}
if ($mode == MCRYPT_RIJNDAEL_128 OR $mode == MCRYPT_RIJNDAEL_256) {
$data = mcrypt_decrypt($mode, $key, $data, MCRYPT_MODE_CBC, $iv);
} else {
$data = openssl_decrypt($data, "aes-256-cbc", $key, 0, $iv);
}
if ($data === false) {
throw new Exception("Unable to decrypt data");
}
$padding = ord($data[mb_strlen($data, "8bit") - 1]);
$data = mb_substr($data, 0, mb_strlen($data, "8bit") - $padding, "8bit");
return $data;
}
function e ($data, $key, $mode) {
$pad = $mode == MCRYPT_RIJNDAEL_256 ? 32 : 16;
$iv = openssl_random_pseudo_bytes($pad);
$padding = 16 - (strlen($data) % $pad);
$data .= str_repeat(chr($padding), $padding);
if ($mode == MCRYPT_RIJNDAEL_128 OR $mode == MCRYPT_RIJNDAEL_256) {
$data = mcrypt_encrypt($mode, $key, $data, MCRYPT_MODE_CBC, $iv);
} else {
$data = openssl_encrypt($data, "aes-256-cbc", $key, 0, $iv );
}
if ($data === false) {
throw new Exception("Unable to encrypt data");
}
return base64_encode($iv . $data);
}
$mode1 = MCRYPT_RIJNDAEL_128;
$key1 = "67pma7BQL01cqb6Nlil2T1436lLXv8Ln";
$key2 = "85f2669023b98a62d1312af75994ddf1";
$mode2 = MCRYPT_RIJNDAEL_256;
$key3 = "85f2669023b98a62d1312af75994ddf1";
$mode3 = "aes-256-cbc";
$data = "test";
$e1 = e($data, $key1, $mode1);
$e2 = e($data, $key2, $mode2);
$e3 = e($data, $key3, $mode3);
$d1 = d($e1, $key1, $mode1); //
$d2 = d($e2, $key2, $mode2); //
$d3 = d($e3, $key3, $mode3); //
//for ($i=1; $i < 4; $i++) {
// ${"e" . $i} = e($data, ${"key" . $i}, ${"mode" . $i});
//
// ${"d" . $i} = d(${"e" . $i}, ${"key" . $i}, ${"mode" . $i});
//}
Results and data used to code:
1) mcrypt - RIJNDAEL 128 CBC
key = "67pma7BQL01cqb6Nlil2T1436lLXv8Ln"
init vector base64 = "q5gXIfW6maT4zx4tgJQImg=="
encrypted string base64 =
"q5gXIfW6maT4zx4tgJQImtwJgEVK66mTcRPdilkEiHY="
decrypted string base64 = "dGVzdA=="
2) mcrypt - RIJNDAEL 256 CBC
key = "85f2669023b98a62d1312af75994ddf1"
init vector base64 = "2EmtyH++cQA5X5mmtY+vpl5FkVwELS9ExrYnFjGGco0="
encrypted string base64 = "2EmtyH++cQA5X5mmtY+vpl5FkVwELS9ExrYnFjGGco3B29CC5DpfWs1YAfh8WuY9f0/6OPC1B4sidSV5TojJ1g=="
decrypted string base64 =
"dGVzdAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAA="
3) openssl_encrypt - aes-256-cbc
key = "85f2669023b98a62d1312af75994ddf1"
init vector base64 = "tOi+xXZf6MyPDpQzPZAI6Q=="
encrypted string base64 = "tOi+xXZf6MyPDpQzPZAI6XJQYmwyNUVzKzdaVnNickc5dEg5MUd1anpBYlpLeW9SQjhpZ29yQzRpWFk9"
decrypted string base64= "dGVzdA=="
Here how I am trying to decrypt this data in Postgres using same Keys and IV.
SELECT
-- mcrypt aes 128
decrypt_iv(
decode('q5gXIfW6maT4zx4tgJQImtwJgEVK66mTcRPdilkEiHY=', 'base64'),
'67pma7BQL01cqb6Nlil2T1436lLXv8Ln',
decode('q5gXIfW6maT4zx4tgJQImg==', 'base64'),
'aes-cbc'
),
-- mcrypt aes 256
decrypt_iv(
decode('2EmtyH++cQA5X5mmtY+vpl5FkVwELS9ExrYnFjGGco3B29CC5DpfWs1YAfh8WuY9f0/6OPC1B4sidSV5TojJ1g==', 'base64'),
'85f2669023b98a62d1312af75994ddf1',
decode('2EmtyH++cQA5X5mmtY+vpl5FkVwELS9ExrYnFjGGco0=', 'base64'),
'aes-cbc'
),
-- -- openssl aes 256
-- decrypt_iv(
-- decode('tOi+xXZf6MyPDpQzPZAI6XJQYmwyNUVzKzdaVnNickc5dEg5MUd1anpBYlpLeW9SQjhpZ29yQzRpWFk9', 'base64'),
-- '85f2669023b98a62d1312af75994ddf1',
-- decode('tOi+xXZf6MyPDpQzPZAI6Q==', 'base64'),
-- 'aes-cbc'
-- ),
-- pgcrypto same values as mcrypt aes 128 encrypt then decrypt
decrypt_iv(
encrypt_iv(
'test',
'67pma7BQL01cqb6Nlil2T1436lLXv8Ln',
decode('q5gXIfW6maT4zx4tgJQImg==', 'base64'),
'aes-cbc'),
'67pma7BQL01cqb6Nlil2T1436lLXv8Ln',
decode('q5gXIfW6maT4zx4tgJQImg==', 'base64'),
'aes-cbc'
)
As you see all 3 decrypted OK in PHP.
In Postgres only first (mcrypt aes128cbc) decrypted OK - first 16 bytes still are IV, but I could remove them and convert to text.
Two others (mcrypte AES256CBC and openssl256cbc) are not even looking like they were decrypted.
I commented block with openssl256cbc since it gives me "[39000] ERROR: decrypt_iv error: Data not a multiple of block size" error.
Any help will be appreciated.
MCRYPT_RIJNDAEL_256 isn't AES-256. It's the Rijndael cipher with a block size of 256 (hence the error). AES is a subset of the Rijndael cipher using block size of 128 bits and key sizes of 128, 192 and 256 bits. This is also reflected in the IV size.
To create an AES-256 encrypted ciphertext you can use MCRYPT_RIJNDAEL_128 with the correct key size (256 bits is 32 bytes). The _128 postfix indicates the block size to be used; you can still use it with any valid key size of 128, 192 or 256 bit.
Beware that mcrypt - especially the underlying C-library - is not maintained anymore. You're better off using the openssl or later crypto libraries.
The mcrypt and OpenSSL wrappers will also happily allow invalid key sizes, only warning you - if you're lucky. That's of course not compatible with about any well defined AES library.
I am looking for two fitting code snippets to encode some text with python, which is to be decoded in php. I am looking for something "easy" and compatible, and I have not much encryption experience myself.
If someone could give a working example that would be great!
python encrypt
from Crypto.Cipher import AES
import base64
import os
# the block size for the cipher object; must be 16, 24, or 32 for AES
BLOCK_SIZE = 32
BLOCK_SZ = 14
# the character used for padding--with a block cipher such as AES, the value
# you encrypt must be a multiple of BLOCK_SIZE in length. This character is
# used to ensure that your value is always a multiple of BLOCK_SIZE
PADDING = '{'
# one-liner to sufficiently pad the text to be encrypted
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
# one-liners to encrypt/encode and decrypt/decode a string
# encrypt with AES, encode with base64
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
secret = "332SECRETabc1234"
iv = "HELLOWORLD123456"
cipher=AES.new(key=secret,mode=AES.MODE_CBC,IV=iv)
my_text_to_encode = "password"
encoded = EncodeAES(cipher, my_text_to_encode)
print 'Encrypted string:', encoded
php decrypt (note the encoded text is just copy/pasted from python print above)
<?php
$enc = "x3OZjCAL944N/awRHSrmRBy9P4VLTptbkFdEl2Ao8gk=";
$secret = "332SECRETabc1234"; // same secret as python
$iv="HELLOWORLD123456"; // same iv as python
$padding = "{"; //same padding as python
function decrypt_data($data, $iv, $key) {
$cypher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
if(is_null($iv)) {
$ivlen = mcrypt_enc_get_iv_size($cypher);
$iv = substr($data, 0, $ivlen);
$data = substr($data, $ivlen);
}
// initialize encryption handle
if (mcrypt_generic_init($cypher, $key, $iv) != -1) {
// decrypt
$decrypted = mdecrypt_generic($cypher, $data);
// clean up
mcrypt_generic_deinit($cypher);
mcrypt_module_close($cypher);
return $decrypted;
}
return false;
}
$res = decrypt_data(base64_decode($enc), $iv, $secret);
print rtrim($res,$padding);
?>
You can use python-mcrypt for python. In php you have a corresponding decrypting function to mcrypt. I hope thedocumentation in php is clear enough to show how to decrypt for mcrypt. Good luck.
I need to communicate with a asp platform that uses the aspEncrypt from persits.
Can anyone provide an example how to decode a string with PHP and mcrypt that was created via the aspEncrypt routines.
An example page of aspEncrypt is available at this link:
http://support.persits.com/encrypt/demo_text.asp
So if I use the text "Test" and the key "test" it provides an base64 encoded string. I need a php example that convert this encoded string back to the text "Test" with usage of key "test".
This is how i finally solved it:
Expectation:
Key is known
IV is known (in my case, first 32 characters of encoded data)
Encrypted Text is known
In my special case all received data hex encoded.
This means IV and encrypted text.
function decrypt($sString, $sIv, $sKey, $iCipherAlg) {
$sDecrypted = mcrypt_decrypt($iCipherAlg, $sKey, $sString, MCRYPT_MODE_CBC, $sIv);
return trim($sDecrypted);
}
function hex2bin($sData) {
$iLen = strlen($sData);
$sNewData = '';
for($iCount=0;$iCount<$iLen;$iCount+=2) {
$sNewData .= pack("C",hexdec(substr($sData,$iCount,2)));
}
return $sNewData;
}
$sKey = 'this is my key';
// first 32 chars are IV
$sIv = hex2bin(substr($sEncodedData, 0, 32));
$sEncodedData = substr($sEncodedData, 32);
$sEncodedRaw = hex2bin($sEncodedData);
$sDecrypted = decrypt($sEncodedRaw, $sIv, $sKey, MCRYPT_RIJNDAEL_128);
A corresponding encryption works like that:
$sIv = mcrypt_create_iv(mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
$sKey = 'this is my key';
$sContent = 'a lot of content';
$sEncrypted = bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $sKey, $sContent, MCRYPT_MODE_CBC, $sIv));
$sFullEncodedText = bin2hex($sIv) . $sEncrypted;
I encountered an old VBScript project which was encrypting strings with AspEncrypt like this:
Function EncryptString(data, base64Iv)
Set CM = Server.CreateObject("Persits.CryptoManager")
Set Context = CM.OpenContextEx("Microsoft Enhanced RSA and AES Cryptographic Provider", "", True)
Set Key = Context.GenerateKeyFromPassword("secret encryption password", calgSHA512, calgAES256)
Set IVblob = CM.CreateBlob
IVblob.Base64 = base64Iv
Key.SetIV IVblob
Set Blob = Key.EncryptText(data)
EncryptString = Blob.Base64 & ":" & base64Iv
End Function
Based on the arguments to GenerateKeyFromPassword, a binary key is created by hashing the password with SHA-512, and data is encrypted with the aes-256-cbc algorithm. The random Base64-encoded initialization vector is appended to the encrypted value after a colon.
This can be replicated in PHP using the OpenSSL extension:
class Aes256Cbc
{
private string $algo = 'aes-256-cbc';
private string $key;
private int $ivLen;
public function __construct(string $password)
{
$this->key = hash('sha512', $password, true);
$this->ivLen = openssl_cipher_iv_length($this->algo);
}
public function encrypt(string $data): string
{
$iv = random_bytes($this->ivLen);
$ciphertext = openssl_encrypt($data, $this->algo, $this->key, OPENSSL_RAW_DATA, $iv);
return base64_encode($ciphertext) . ':' . base64_encode($iv);
}
public function decrypt(string $encrypted): string
{
[$ctPart, $ivPart] = explode(':', $encrypted);
$iv = base64_decode($ivPart);
$ciphertext = base64_decode($ctPart);
return openssl_decrypt($ciphertext, $this->algo, $this->key, OPENSSL_RAW_DATA, $iv);
}
}
Example usage:
$aes = new Aes256Cbc("secret encryption password");
$decrypted = $aes->decrypt($someValue);
Note: if AspEncrypt was used without setting an initialization vector, the IV will be sequence of null bytes. This fixed IV could be generated in the above PHP class as follows:
$iv = str_repeat("\0", $this->ivLen);
It depends on which cipher it uses, take a look at mcrypt as long as you know the cipher and key it should be easy to decrypt.
If you know the cipher and mode used by the encryption, the function mcrypt_decrypt can decrypt it.
http://uk3.php.net/manual/en/function.mcrypt-decrypt.php