Delphi DEC library (Rijndael) encryption - php

I am trying to use the DEC 3.0 library (Delphi Encryption Compedium Part I) to encrypt data in Delphi 7 and send it to a PHP script through POST, where I am decrypting it with mcrypt (RIJNDAEL_256, ECB mode).
Delphi part:
uses Windows, DECUtil, Cipher, Cipher1;
function EncryptMsgData(MsgData, Key: string): string;
var RCipher: TCipher_Rijndael;
begin
RCipher:= TCipher_Rijndael.Create(KeyStr, nil);
RCipher.Mode:= cmECB;
Result:= RCipher.CodeString(MsgData, paEncode, fmtMIME64);
RCipher.Free;
end;
PHP part:
function decryptMsgContent($msgContent, $sKey) {
return mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $sKey, base64_decode($msgContent), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND));
}
The problem is that the decryption from PHP doesn't work and the output is gibberish, differing from the actual data.
Of course, Delphi Key and PHP $Key is the same 24 characters string.
Now I know DEC 3.0 is old and outdated, and I'm not an expert in encryption and can't tell if the inplementation is actually Rijndael 256. Maybe someone can tell me how this implementation differs from PHP's mcrypt w/ RIJNDAEL_256. Maybe the keysize is different, or the block size, but can't tell this from the code. Here's an excerpt from Cipher1.pas:
const
{ don’t change this }
Rijndael_Blocks = 4;
Rijndael_Rounds = 14;
class procedure TCipher_Rijndael.GetContext(var ABufSize, AKeySize, AUserSize: Integer);
begin
ABufSize := Rijndael_Blocks * 4;
AKeySize := 32;
AUserSize := (Rijndael_Rounds + 1) * Rijndael_Blocks * SizeOf(Integer) * 2;
end;
Side question:
I know ECB mode isn't recommended and I'll use CBC as soon as I get ECB working. The question is, do I have to transmit the generated IV in Delphi to the PHP script also? Or knowing the key is sufficient, like for ECB?

You are calling the TCipher.Create(const Password: String; AProtection: TProtection); constructor, which will compute a hash of the password before passing it to the Init method, which performs the standard key schedule of the implemented algorithm. To override this key derivation, use:
function EncryptMsgData(MsgData, Key: string): string;
var RCipher: TCipher_Rijndael;
begin
RCipher:= TCipher_Rijndael.Create('', nil);
RCipher.Init(Pointer(Key)^,Length(Key),nil);
RCipher.Mode:= cmECB;
Result:= RCipher.CodeString(MsgData, paEncode, fmtMIME64);
RCipher.Free;
end;

OK, so to sum this up, there were 3 problems with my code:
Due to my poor understanding of mcrypt and ciphers in general, MCRYPT_RIJNDAEL_256 refers to 128 bits block and doesn't refer to the keysize. My correct choice should have been MCRYPT_RIJNDAEL_128, which is the AES standard and is also supported by DEC 3.0.
DEC has it's own default key derivation, so I needed to bypass it so I wouldn't have to implement it in PHP also. In actuality, I am using my own key derivation algorithm that was easy to reproduce in PHP (first 32 characters of sha1(key)).
DEC doesn't pad plaintext to a multiple of the block size of the cipher, as mcrypt expects, so I had to do it manually.
Providing working code below:
Delphi:
uses Windows, DECUtil, Cipher, Cipher1, CryptoAPI;
function EncryptMsgData(MsgData, Key: string): string;
var RCipher: TCipher_Rijndael;
KeyStr: string;
begin
Result:= '';
try
// key derivation; just making sure to feed the cipher a 24 chars key
HashStr(HASH_SHA1, Key, KeyStr);
KeyStr:= Copy(KeyStr, 1, 24);
RCipher:= TCipher_Rijndael.Create('', nil);
RCipher.Init(Pointer(KeyStr)^, Length(KeyStr), nil);
RCipher.Mode:= cmECB;
Result:= RCipher.CodeString(MsgData + StringOfChar(#0,16-(Length(MsgData) mod 16)), paEncode, fmtMIME64);
RCipher.Free;
except
end;
end;
PHP:
function decryptMsgContent($msgContent, $sKey) {
$sKey = substr(sha1(sKey), 0, 24);
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $sKey, base64_decode($msgContent), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND)));
}

A 256 bit key I found is 32 charachters, or 32 bytes. Not 24. This may be the issue.
[EDIT]
I combined everyone's ideas (ansistring, etc) into one single idea with a fix.
Also, you are using codestring( -- it should be Encodestring(
I pasted working Encrypt and Decrypt source below:
function EncryptMsgData(MsgData, Key: AnsiString): AnsiString;
var RCipher: TCipher_Rijndael;
begin
RCipher:= TCipher_Rijndael.Create('', nil);
RCipher.Init(Pointer(Key)^,Length(Key),nil);
RCipher.Mode:= cmCBC;
Result:= RCipher.EncodeString(MsgData);
RCipher.Free;
end;
function DecryptMsgData(MsgData, Key: AnsiString): AnsiString;
var RCipher: TCipher_Rijndael;
begin
RCipher:= TCipher_Rijndael.Create('',nil);
RCipher.Init(Pointer(Key)^,Length(Key),nil);
RCipher.Mode:= cmCBC;
Result:= RCipher.DecodeString(MsgData);
RCipher.Free;
end;
Use that with a 32 charachter key and you get proper encryption and decryption.
In order to store and use the encrypted data as a string you may want to use Base64Encode(
But do not forget to Base64Decode prior to decrypting.
This is the same technique needed for Blowfish. Sometimes the charachters actually are like a backspace, and perform the function rather than showing on screen. Base64Encode basically converts the charachters to something you can display in text.
Prior to transferring the encoded data across the internet or to another application in the same or another language, you MUST base64encode and decode in order to not loose data. Don't forget it in PHP too!

Related

openssl_decrypt fails. cipher expects an IV of precisely 16 bytes

I have a decryption function that just started failing for unknown reasons. The error is "openssl_decrypt(): IV passed is only 6 bytes long, cipher expects an IV of precisely 16 bytes". I have found multiple suggestions to "add base64 encoding", which I already had.
My function is
function decryptThis($data) {
$encryptionKey = "encryptionKey";
$encryption_key = base64_decode($encryptionKey);
list($encrypted_data, $iv) = array_pad(explode('::', base64_decode($data), 2),2,null);
return openssl_decrypt($encrypted_data, 'AES-128-CTR', $encryption_key, 0, $iv);
}
Previously a lot of the mcrypt and OpenSSL functions simply right padded the IV with zeros. However nowadays we try and keep to the specifications for the cipher / mode of operation. If you want to return to the previous situation then you'll have to right pad yourself.
It seems that the fix was a bit too generic or that the author was a bit overzealous as CTR really doesn't take an IV but a nonce. In that sense it would be perfectly reasonable to right-pad a nonce with zeros, as long as the key / nonce combination remains unique.
However, many CTR (counter mode) implementations assume that you provide an entire block consisting of the nonce + starting counter value.
Note that OpenSSL is a C library, so just providing an IV value of 6 bytes would result in a buffer overrun, possibly leading to broken - or worse: irreversible - encryption.

Convert .net aes256 encryption code into php

The code below is a simple .NET snippet, having test on the input it returns p+cTm2VODfvQnreAl02wUQ== as an output.
Dim aesEncryptObj As New System.Security.Cryptography.RijndaelManaged()
Dim encoder As System.Text.ASCIIEncoding = New System.Text.ASCIIEncoding()
Dim tempKey As Byte() = encoder.GetBytes("00000011111111111111111111111111")
aesEncryptObj.Key = tempKey
aesEncryptObj.BlockSize = 128
aesEncryptObj.Mode = System.Security.Cryptography.CipherMode.ECB
aesEncryptObj.Padding = System.Security.Cryptography.PaddingMode.PKCS7
aesEncryptObj.GenerateIV()
Dim EncryptedBytes As Byte()
Dim encryptor As System.Security.Cryptography.ICryptoTransform = aesEncryptObj.CreateEncryptor(aesEncryptObj.Key, aesEncryptObj.IV)
Using msEncrypt As New System.IO.MemoryStream()
Using csEncrypt As New System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write)
Using swEncrypt As New System.IO.StreamWriter(csEncrypt)
swEncrypt.Write(txtInput.Text)
End Using
EncryptedBytes = msEncrypt.ToArray()
End Using
End Using
txtOutput.Text = Convert.ToBase64String(EncryptedBytes)
Now, here is the PHP code:
const ENCRYPT_METHOD = 'aes-256-ecb';
$aesKey = pack('H*', '00000011111111111111111111111111');
$ivSize = openssl_cipher_iv_length(ENCRYPT_METHOD);
$plainText = "test";
$iv = openssl_random_pseudo_bytes($ivSize);
$cipherText = openssl_encrypt(
$plainText,
ENCRYPT_METHOD,
$aesKey,
OPENSSL_RAW_DATA,
$iv
);
$encryptedText = $iv . $cipherText;
echo base64_encode($encryptedText);
It returns 1W3UvYVNKWEoFrpPZPd+Qw== which differs from the .NET one. I've tried both aes-256-ecb and aes-128-ecb and the result is always different from the .NET's one.
As far as I know, openssl_encrypt do the PKCS7 padding by default, is that right? Can you see the reason why PHP is giving different result?
Your code isn't working because:
GetBytes in .NET returns you the byte values of that string. That is, you are going to get a byte array with a length of 32 (AES-256). However, pack in PHP with H* decodes a hex string, which is going to give you a key of length 16 (AES-128). This whole time you've been encrypting with not only two different keys, but two different key sizes.
Fixing the above will make your code work, but it will be far from actually secure and should not be used. If you want to make your code secure, you need to:
Stop using ECB mode. Use GCM mode if you can, CBC otherwise. You are most likely going to end up using CBC. If you do, you need to prepend the IV to your ciphertext so that the decrypting party can retrieve it and use it when decrypting. IVs don't need to be secret, they just need to be random, so your use of OpenSSL random bytes and the GenerateIV method is good.
Since you are likely going to be using CBC mode, you will need to apply an HMAC to ensure integrity. Otherwise anyone can modify your ciphertext and you won't know. When applying an HMAC, always encrypt-then-mac. Remember to include your IV before applying the HMAC.
Lastly, and I don't think you actually meant to do this, but never use the ASCII values of a string as a key. If you want to create a key from a passphrase, you should apply a KDF. PBKDF2 is probably the best suited and has implementations in both PHP and .NET.

AES encryption differences between php mcrypt and a Delphi component

I am using a Delphi component from chillkat which does AES encryption for me. It works like a charm and the server accepts my encrypted requests. So I tried to create a php pendant by using mcrypt. But the PHP mcypt result is different in comparison with the Delphi Chillcat result - even if all the parameters are the same. Therefore the server rejects the php requests.
All the encryption settings are the same:
Cipher Name: AES 128
Cipher mode: ECB
Padding scheme: Pad with NULL
Key length: 128
Key: 1234567890ABE1234567890ABE1234DB
String to encrypt: This is a really cool teststring
This is the little php script:
<?php
$key = '1234567890ABE1234567890ABE1234DB';
function string_encrypt($string, $key) {
$crypted_text = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $string, MCRYPT_MODE_ECB);
return $crypted_text;
}
function string_decrypt($encrypted_string, $key) {
$decrypted_text = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $encrypted_string, MCRYPT_MODE_ECB);
return trim($decrypted_text);
}
echo $test_str = 'This is a really cool teststring'; echo '<br />';
$enc_str = string_encrypt($test_str, $key);
echo bin2hex($enc_str); echo '<br />';
echo string_decrypt($enc_str, $key); echo '<br />';
?>
The php output is:
e355fbcd91ada4b835e1b030cc9741759219f59fe441ba62e628eca2e8289eb3
This is the Delphi Code:
function encrypt(s:PWideChar;mode,padding:integer;algo,cipher,keylength:string):string;
var
crypt: HCkCrypt2;
success: Boolean;
ivHex: PWideChar;
keyHex: PWideChar;
encStr: PWideChar;
decStr: PWideChar;
begin
crypt := CkCrypt2_Create();
// AES is also known as Rijndael.
CkCrypt2_putCryptAlgorithm('aes');
// "pki", "aes", "blowfish", "blowfish2", "des", "3des", "rc2", "arc4", "twofish", "pbes1" and "pbes2"
// CipherMode may be "ecb" or "cbc"
CkCrypt2_putCipherMode(crypt,'ecb');
// KeyLength may be 128, 192, 256
try
CkCrypt2_putKeyLength(crypt,128);
Except
showmessage('The encryption key you have used seems to be invalid');
end;
// The padding scheme determines the contents of the bytes
// that are added to pad the result to a multiple of the
// encryption algorithm's block size. AES has a block
// size of 16 bytes, so encrypted output is always
// a multiple of 16.
{
Possible values are:
0 = RFC 1423 padding scheme: Each padding byte is set to the number of padding bytes.
If the data is already a multiple of algorithm's block size bytes, an extra block is
appended each having a value equal to the block size. (for example, if the algorithm's
block size is 16, then 16 bytes having the value 0x10 are added.). (This is also known as
PKCS5 padding: PKCS #5 padding string consists of a sequence of bytes, each of which
is equal to the total number of padding bytes added. )
1 = FIPS81 (Federal Information Processing Standards 81) where the last byte contains
the number of padding bytes, including itself, and the other padding bytes are set to random values.
2 = Each padding byte is set to a random value. The decryptor must know
how many bytes are in the original unencrypted data.
3 = Pad with NULLs. (If already a multiple of the algorithm's block size,
no padding is added).
4 = Pad with SPACE chars(0x20). (If already a multiple of algorithm's block size, no padding is added).
}
CkCrypt2_putPaddingScheme(crypt,3);
// EncodingMode specifies the encoding of the output for
// encryption, and the input for decryption.
// It may be "hex", "url", "base64", or "quoted-printable".
CkCrypt2_putEncodingMode(crypt,'hex');
// An initialization vector is required if using CBC mode.
// ECB mode does not use an IV.
// The length of the IV is equal to the algorithm's block size.
// It is NOT equal to the length of the key.
ivHex := '';
CkCrypt2_SetEncodedIV(crypt,ivHex,'hex');
// The secret key must equal the size of the key. For
// 256-bit encryption, the binary secret key is 32 bytes.
// For 128-bit encryption, the binary secret key is 16 bytes.
keyHex := '1234567890ABE1234567890ABE1234DB';
CkCrypt2_SetEncodedKey(crypt,keyHex,'hex');
// Encrypt a string...
// The input string is 44 ANSI characters (i.e. 44 bytes), so
// the output should be 48 bytes (a multiple of 16).
// Because the output is a hex string, it should
// be 96 characters long (2 chars per byte).
//encryption
if mode = 0 then
begin
encStr := CkCrypt2__encryptStringENC(crypt,s);
result := encStr;
end
else
begin
result := CkCrypt2__decryptStringENC(crypt,s);
end;
CkCrypt2_Dispose(crypt);
End;
The chillkat Delphi component's output is:
780F849AB30690433409D4FB7B3357735296A6E76D3AA6B6D6C769BE99F32041
I thought both outputs should produce the same value, as all the input parameters are equal, right ?
MCrypt expects the key to be a binary string, but you pass a hex encoded string into it.
Use
$key = hex2bin($key);
or
$key = pack('H*', $key);
depending on PHP support. This must be done before calling mcrypt_encrypt().
Security:
Don't ever use ECB mode. It's not semantically secure. There is a lot that an attacker can get from ciphertexts without decrypting them. You need to use at the very least CBC mode with a random IV. You should also have an authentication tag of your ciphertexts.
This answer gives you every thing you need to know about this. One thing left, don't use MCrypt. It's an old unmaintained library.
This answer is also very helpful in that regard with a different way of achieving the same thing.
thanks to your your nice inputs, I was able to receive a positive answer from the server with the following 4 lines of code:
$key = pack('H*', "*5DB");
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,$mytxt, MCRYPT_MODE_ECB);
$hex2 = bin2hex($ciphertext);
echo strtoupper($hex2);
However, I have learned that
ECB is unsecure
mcrypt is old and unmaintained
I will check alternatives and update my code accordingly. Thanks again !

AES encryption inconsistency in PHP using the Open SSL library and coding CBC mode from scratch

I suppose I should deal with my first statement first. Is there an inconsistency in the way PHP does AES-128-CBC encryption when you use the Open SSL library?
I am asking this because if you look through RFC3602 for AES then you'll find some test vectors in section 4. The first one I tried was:
Case #1: Encrypting 16 bytes (1 block) using AES-CBC with 128-bit key
Key : 0x06a9214036b8a15b512e03d534120006
IV : 0x3dafba429d9eb430b422da802c9fac41
Paintext : "Single block msg"
Cphertext: 0xe353779c1079aeb82708942dbe77181a
Using the open SSL library with the following code:
echo bin2hex(openssl_encrypt($str, 'aes-128-cbc', $key, OPENSSL_RAW_DATA, $iv));
You actually get back:
e353779c1079aeb82708942dbe77181ab97c825e1c785146542d396941bce55d
Now this is all well and good and decrypts back just fine, and the first 32 bytes are the expected cipher text "e353779c1079aeb82708942dbe77181a". However, there appears to be another 32 bytes at the end of the cipher text returned from the Open SSL library. Why is this? This question becomes relevant next.
As part of something I am doing for fun I am trying to implement AES CBC mode encryption sort of from scratch. The code I currently have for doing this is (based on the RFC previously referenced and on CBC diagrams at the "Block cipher mode of operation" Wikipedia page):
public function cbcEncrypt($str, $iv, $key) {
$bl = 16;
$bs = str_split($str,$bl);
$pv = null;
$r = '';
foreach($bs as $b) {
if($pv === null) $pv = $iv;
if(strlen($b)<$bl) $b = $this->pkcs7Pad($b, $bl);
$pv = openssl_encrypt($b^$pv, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
$r .= $pv;
}
return $r;
}
At the moment I'm pretty sure this code wont work on strings longer than the current test 16 byte string anyway, however, I ran this code side by side with the Open SSL implementation to compare. The return value from by CBC implementation is:
e353779c1079aeb82708942dbe77181a8b1ccc6f8cd525ffe22d6327d891a063
When called via:
$crypto = new CryptoTools();
$enc = $crypto->cbcEncrypt('Single block msg',hex2bin("3dafba429d9eb430b422da802c9fac41"),hex2bin("06a9214036b8a15b512e03d534120006"));
Again, the first 32 bytes are correct, but the second 32 bytes are again added but completely different from the Open SSL implementation of CBC. Any clues as to why?
Also, the Open SSL implementation of ECB mode returns a 32 byte string, which means CBC encrypting strings currently greater than 16 bytes in length the new value of $pv will be 32 bytes in length and then it will be XOR'd against the second plain text block when in reality shouldn't $pv always be 16 bytes in length? Is it usually just accepted that you truncate $pv from 32 to 16 bytes?
Just in case it helps, the pkcs7Pad method in the code above looks like:
public function pkcs7Pad($str, $b = 8) {
if(trim($str) == '') return false;
if((int)$b < 1) return false;
$p = $b - (strlen($str) % $b);
return $str . str_repeat(chr($p),$p);
}
Any help would be greatly appreciated. Needless to say there's not much documentation on this as people aren't usually stupid enough to try and reinvent the wheel, certainly in PHP...
This has to do with padding. The test vectors don't use any padding at all, while the openssl_encrypt function and your function apply PKCS#7 padding.
PKCS#7 padding is specified so that padding is added in all cases. When the plaintext length is a multiple of the block size, a full block of padding is added, which is why the ciphertext is 32 bytes long when the plaintext is 16 bytes.
Can't immediately see anything wrong with your function (though I'm not familiar with PHP), but you could try padding $str before splitting it instead of checking whether each block requires padding.
Ah ha! Got it! Thanks to ntoskrnl's answer and this Stackoverflow question I managed to come up with a solution! If you do:
echo bin2hex(base64_decode(openssl_encrypt($str, 'aes-128-cbc', $key, OPENSSL_ZERO_PADDING, $iv)));
You will match the test case provided by the RFC! You just need to remember that because you're now not doing OPENSSL_RAW_DATA you will get back a base64 encoded string and so will need to base64 decode it before converting it to hex to match the test case!
TLDR: it was a padding issue, just not an obvious one!

Cryptography libraries conflict (MCrypt, libgcrypt)

I'm trying to perform encryption and decryption (Rijndael 256, ecb mode) in two different components:
1. PHP - Server Side (using mcrypt)
2. C + + - Client Side (using gcrypt)
I ran into a problem when the client side could not decrypt correctly the encrypted data (made by the server side)
so... i checked the:
1. initial vector - same same (32 length)
2. the key - again the same key on both sides..
so i wrote some code in C++ that will encrypt the data (with the same parameters like in the php)
and i found out that the encrypted data contains different bytes (maybe encoding issue??)
I'll be more than glad to get some help
PHP - MCrypt
// Encrypt Function
function mc_encrypt($encrypt, $mc_key) {
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$iv = "static_init_vector_static_init_v";
echo "IV-Size: " . $iv_size . "\n";
echo "IV: " . $iv . "\n";
$passcrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $mc_key, $encrypt, MCRYPT_MODE_ECB, $iv);
print_hex($passcrypt);
return $encode;
}
mc_encrypt("Some text which should be encrypted...","keykeykeykeykeykeykeykeykeykeyke");
I'll post the C++ code in a comment
Thanks,
Johnny Depp
OK. I'll make my comment an answer:
An Initialization Vector (IV) isn't used in ECB mode. If it is provided different implementations might work differently.
If you want to be sure the implementations will work correctly then use an IV of 0 (zero). Even though you provide the IV, both implementations SHOULD ignore it but one can never be sure about that. Not providing an IV in ECB mode should work aswell but again, it all depends on the implementations.
According to the PHP documentation MCrypt will ignore it. GCrypt I'm not sure about.
mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB) should actually return 0 since you specify ECB mode.
Edit:
Do not call mcrypt_get_iv_size or mcrypt_create_iv.
Instead call mcrypt_encrypt without an IV. According to the PHP documentation all bytes in the IV will be set to '\0'.
Same goes for the C++ code. No need to set any IV at all. The libgcrypt code is complex but from glancing at the source of version 1.4.5 then in ECB mode it seems the IV isn't used at all.
If the resulting ciphertext still differs then the problem is something else.
A couple of possibilities comes to mind:
Encoding - Is the same encoding used in both the server and the client?
Endianness - What type of systems are the server and the client? Big- vs Little-endian?

Categories