PHP Encryption & VB.net Decryption - php

I'm trying to do a simple task. Encypt a value in PHP and Decrypt it in my VB.net app.
I figure I'd use tripleDES or Rijdael 128 or 256
I though this should be simple. Can anyone point me in the right direction?
Thank you

I also looked long and hard for solutions to this problem. Here is a complete set of code for both php and vb.net that will do what you are looking for. Should be pretty easy to translate to C# as well.
########################################
# BEGIN PHP CODE
########################################
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// I blantantly stole, tweaked and happily used this code from:
// Lord of Ports http://www.experts-exchange.com/M_1736399.html
$ky = 'lkirwf897+22#bbtrm8814z5qq=498j5'; // 32 * 8 = 256 bit key
$iv = '741952hheeyy66#cs!9hjv887mxx7#8y'; // 32 * 8 = 256 bit iv
$text = "Here is my data to encrypt!!!";
$from_vb = "QBlgcQ2+v3wd8RLjhtu07ZBd8aQWjPMfTc/73TPzlyA="; // enter value from vb.net app here to test
$etext = encryptRJ256($ky, $iv, $text);
$dtext = decryptRJ256($ky, $iv, $etext);
$vtext = decryptRJ256($ky, $iv, $from_vb);
echo "<HR>orignal string: $text";
echo "<HR>encrypted in php: $etext";
echo "<HR>decrypted in php: $dtext";
echo "<HR>encrypted in vb: $from_vb";
echo "<HR>from vb decrypted in php: $vtext";
echo "<HR>If you like it say thanks! richard dot varno at gmail dot com";
exit;
function decryptRJ256($key,$iv,$string_to_decrypt)
{
$string_to_decrypt = base64_decode($string_to_decrypt);
$rtn = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $string_to_decrypt, MCRYPT_MODE_CBC, $iv);
$rtn = rtrim($rtn, "\0\4");
return($rtn);
}
function encryptRJ256($key,$iv,$string_to_encrypt)
{
$rtn = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $string_to_encrypt, MCRYPT_MODE_CBC, $iv);
$rtn = base64_encode($rtn);
return($rtn);
}
?>
########################################
# END PHP CODE
########################################
########################################
# BEGIN VB.NET CODE (console app)
########################################
Imports System
Imports System.Text
Imports System.Security.Cryptography
Imports System.IO
Module Module1
' I blantantly stole, tweaked and happily used this code from:
' Lord of Ports http://www.experts-exchange.com/M_1736399.html
Sub Main()
'Shared 256 bit Key and IV here
Dim sKy As String = "lkirwf897+22#bbtrm8814z5qq=498j5" '32 chr shared ascii string (32 * 8 = 256 bit)
Dim sIV As String = "741952hheeyy66#cs!9hjv887mxx7#8y" '32 chr shared ascii string (32 * 8 = 256 bit)
Dim sTextVal As String = "Here is my data to encrypt!!!"
Dim eText As String
Dim dText As String
eText = EncryptRJ256(sKy, sIV, sTextVal)
dText = DecryptRJ256(sKy, sIV, eText)
Console.WriteLine("key: " & sKy)
Console.WriteLine()
Console.WriteLine(" iv: " & sIV)
Console.WriteLine("txt: " & sTextVal)
Console.WriteLine("encrypted: " & eText)
Console.WriteLine("decrypted: " & dText)
Console.WriteLine("If you like it say thanks! richard dot varno at gmail dot com")
Console.WriteLine("press any key to exit")
Console.ReadKey(True)
End Sub
Public Function DecryptRJ256(ByVal prm_key As String, ByVal prm_iv As String, ByVal prm_text_to_decrypt As String)
Dim sEncryptedString As String = prm_text_to_decrypt
Dim myRijndael As New RijndaelManaged
myRijndael.Padding = PaddingMode.Zeros
myRijndael.Mode = CipherMode.CBC
myRijndael.KeySize = 256
myRijndael.BlockSize = 256
Dim key() As Byte
Dim IV() As Byte
key = System.Text.Encoding.ASCII.GetBytes(prm_key)
IV = System.Text.Encoding.ASCII.GetBytes(prm_iv)
Dim decryptor As ICryptoTransform = myRijndael.CreateDecryptor(key, IV)
Dim sEncrypted As Byte() = Convert.FromBase64String(sEncryptedString)
Dim fromEncrypt() As Byte = New Byte(sEncrypted.Length) {}
Dim msDecrypt As New MemoryStream(sEncrypted)
Dim csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)
csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length)
Return (System.Text.Encoding.ASCII.GetString(fromEncrypt))
End Function
Public Function EncryptRJ256(ByVal prm_key As String, ByVal prm_iv As String, ByVal prm_text_to_encrypt As String)
Dim sToEncrypt As String = prm_text_to_encrypt
Dim myRijndael As New RijndaelManaged
myRijndael.Padding = PaddingMode.Zeros
myRijndael.Mode = CipherMode.CBC
myRijndael.KeySize = 256
myRijndael.BlockSize = 256
Dim encrypted() As Byte
Dim toEncrypt() As Byte
Dim key() As Byte
Dim IV() As Byte
key = System.Text.Encoding.ASCII.GetBytes(prm_key)
IV = System.Text.Encoding.ASCII.GetBytes(prm_iv)
Dim encryptor As ICryptoTransform = myRijndael.CreateEncryptor(key, IV)
Dim msEncrypt As New MemoryStream()
Dim csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
toEncrypt = System.Text.Encoding.ASCII.GetBytes(sToEncrypt)
csEncrypt.Write(toEncrypt, 0, toEncrypt.Length)
csEncrypt.FlushFinalBlock()
encrypted = msEncrypt.ToArray()
Return (Convert.ToBase64String(encrypted))
End Function
End Module
########################################
# END VB.NET CODE
########################################

We have some ciphers working between C# on .NET and PHP. I am not familiar with VB.net. I assume it uses the same crypto library System.Security.Cryptography.
On PHP side, we switched from mcrypt to OpenSSL because some modes and paddings are not supported by mcrypt.
As long as you use same algorithm (DES, AES etc), same mode (CBC, ECB etc), same padding (PKCS1, PKCS5), the cipher should work on both platforms.
Example of encryption using AES-128 on PHP side using mcrypt,
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128);
$data = $this->paddingAlgorithm->padData($data, $blockSize);
return $iv . mcrypt_encrypt($this->MCRYPT_DES, $keyBytes, $data, MCRYPT_MODE_CBC, $iv);
Please note that we use PKCS7 padding but mcrypt doesn't support it so we have to write the padding algorithm. We also prepend the IV (Initial Vector) to the cipher text. You might store it somewhere else but you need that to decrypt.
Here is the corresponding C# code to setup the cipher to decrypt,
// create the underlying symmetric algorithm with the given name
algorithm = (SymmetricAlgorithm)CryptoConfig.CreateFromName("RIJNDAEL");
// set cipher mode
algorithm.Mode = CipherMode.CBC;
// set padding mode
algorithm.Padding = PaddingMode.PKCS7;

For PHP you should look at the mcrypt extension, which should support all of the ciphers you specified

Disclaimer: I've never actually used the Crytography classes in .NET.
To do Rijndael decryption in .NET, you're probably looking for the System.Security.Cryptography.RijndaelManaged class.
That page also has some examples of how to use it, although you may also need an instance of RSACryptoServiceProvider... I'm not sure.

Related

Encrypt in PHP, decrypt in C

I'd like to encrypt a string in PHP and then decrypt it in C. I'm stuck on the decryption part.
(PHP) I first encrypt the string:
function encrypt($plaintext, $key) {
$iv = 'aaaaaaaaaaaaaaaa';
$ciphertext = openssl_encrypt($plaintext, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $iv);
return $ciphertext;
}
echo encrypt('This is a test', 'test');
// output: 7q�7h_��8� ��L
(C) Then I want to decrypt it, I use tiny-AES-c library for the functions:
int test_decrypt_cbc(void) {
uint8_t key[] = "test";
uint8_t iv[] = "aaaaaaaaaaaaaaaa";
uint8_t str[] = "7q�7h_��8� ��L";
printf("%s", str);
printf("\n Decrypted buffer\n");
struct AES_ctx ctx;
AES_init_ctx_iv(&ctx, key, iv);
AES_CBC_decrypt_buffer(&ctx, str, sizeof(str));
printf("%s", str);
printf("\n");
return 1;
}
This outputs:
7q�7h_��8� ��L
Decrypted buffer
?L??Ɵ??m??Dˍ?'?&??c?W
It should instead output "This is a test".
How can I fix this?
In the PHP code, AES-256 is used. tiny-AES-c only supports AES-128 by default. In order for AES-256 to be supported, the corresponding constant must be defined in aes.h, i.e. the line //#define AES256 1 must be commented in, here.
PHP uses PKCS7 padding by default. The padding should be removed in the C code.
PHP implicitly pads too short keys with zero values to the specified length. Since AES-256-CBC was specified in the PHP code, the key test is extended as follows:
test\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0
In the C code this extended key must be used (see also the comment of #r3mainer).
For the transfer of the ciphertext between the two codes a suitable encoding must be used, e.g. Base64 or hexadecimal (see also the comment of #Ôrel). For the latter, bin2hex can be applied to the ciphertext in the PHP code. An example of a hex decoding in C can be found here.
A possible C-implementation is:
// Pad the key with zero values
uint8_t key[] = "test\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
uint8_t iv[] = "aaaaaaaaaaaaaaaa";
uint8_t ciphertextHex[] = "3771e837685ff5d4173801900de6e14c";
// Hex decode (e.g. https://stackoverflow.com/a/3409211/9014097)
uint8_t ciphertext[sizeof(ciphertextHex) / 2], * pos = ciphertextHex;
for (size_t count = 0; count < sizeof ciphertext / sizeof * ciphertext; count++) {
sscanf((const char*)pos, "%2hhx", &ciphertext[count]);
pos += 2;
}
// Decrypt
struct AES_ctx ctx;
AES_init_ctx_iv(&ctx, key, iv);
AES_CBC_decrypt_buffer(&ctx, ciphertext, sizeof(ciphertext));
// Remove the PKCS7 padding
uint8_t ciphertextLength = sizeof(ciphertext);
uint8_t numberOfPaddingBytes = ciphertext[ciphertextLength - 1];
ciphertext[ciphertextLength - numberOfPaddingBytes] = 0;
printf("%s", ciphertext);

Convert openssl AES in Php to Python AES

I have a php file which is as follow:
$encryption_encoded_key = 'c7e1wJFz+PBwQix80D1MbIwwOmOceZOzFGoidzDkF5g=';
function my_encrypt($data, $key) {
$encryption_key = base64_decode($key);
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cfb'));
$encrypted = openssl_encrypt($data, 'aes-256-cfb', $encryption_key, 1, $iv);
// The $iv is just as important as the key for decrypting, so save it with encrypted data using a unique separator (::)
return base64_encode($encrypted . '::' . $iv);
}
function my_decrypt($data, $key) {
// Remove the base64 encoding from key
$encryption_key = base64_decode($key);
// To decrypt, split the encrypted data from IV - unique separator used was "::"
list($encrypted_data, $iv) = explode('::', base64_decode($data), 2);
return openssl_decrypt($encrypted_data, 'aes-256-cfb', $encryption_key, 1, $iv);
}
$data = 'USER_ID||NAME||EMAIL||MOBILE';
$data_encrypted = my_encrypt($data, $encryption_encoded_key);
echo $data_encrypted;
$data_decrypted = my_decrypt($data_encrypted, $encryption_encoded_key);
echo "Decrypted string: ". $data_decrypted;
This works fine, and is able to encrypt/decrypt with the encryption key, now i also have a python file:
import hashlib
import base64
from Crypto.Cipher import AES
from Crypto import Random
encryption_encoded_key = 'c7e1wJFz+PBwQix80D1MbIwwOmOceZOzFGoidzDkF5g='
def my_encrypt(data, key):
#Remove the base64 encoding from key
encryption_key = base64.b64decode(key)
#Generate an initialization vector
bs = AES.block_size
iv = Random.new().read(bs)
cipher = AES.new(encryption_key, AES.MODE_CFB, iv)
#Encrypt the data using AES 256 encryption in CBC mode using our encryption key and initialization vector.
encrypted = cipher.encrypt(data)
#The iv is just as important as the key for decrypting, so save it with encrypted data using a unique separator (::)
return base64.b64encode(encrypted + '::' + iv)
def my_decrypt(data, key):
#Remove the base64 encoding from key
encryption_key = base64.b64decode(key)
#To decrypt, split the encrypted data from IV - unique separator used was "::"
encrypted_data, iv = base64.b64decode(data).split('::')
cipher = AES.new(encryption_key, AES.MODE_CFB, iv)
return cipher.decrypt(encrypted_data)
data = 'USER_ID||NAME||EMAIL||MOBILE'
print "Actual string: %s" %(data)
data_encrypted = my_encrypt(data, encryption_encoded_key)
print data_encrypted
data_decrypted = my_decrypt(data_encrypted, encryption_encoded_key)
print "Decrypted string: %s" %(data_decrypted)
This also works fine when i try to use this from python, it is able to encrypt/decrypt input string,
I want to encrypt using php file and decrypt the output in python, both should use AES 256 Encryption using CFB mode, what am i doing wrong ?
To use CFB mode you need to specify a segment size for it. OpenSSL has aes-256-cfb (which is 128 bit), aes-256-cfb1 (i.e. 1-bit) and aes-256-cfb8 (8 bit) (and similar modes for AES-128 and 192). So you are using 128 bit cfb in your php code.
The Python library accepts a segment_size argument to AES.new, but the default is 8, so you are using different modes in the two versions.
To get the Python code to decrypt the output of the PHP code, add a segment size of 128 to the cipher object:
cipher = AES.new(encryption_key, AES.MODE_CFB, iv, segment_size=128)
(N.B. this is using the newer PyCryptodome fork of PyCrypto. PyCrypto has a bug here and won’t work.)
Alternatively, you can get the PHP code to use CFB-8 by setting the cipher (don’t change both, obviously):
$encrypted = openssl_encrypt($data, 'aes-256-cfb8', $encryption_key, 1, $iv);

TripleDES encryption not getting same value in PHP as in VB

I found a lot of solutions that explain how to look at C# versus PHP, but none specific to VB. I did find one helpful hint about PHP padding with zeroes, but that didn't solve the problem as I matched that in VB and it didn't help. Anyway I am familiar with VB and we have another developer familiar with PHP and we are trying to make our functions match so that tripleDES encryption spits out the same value in both. We are integrating with a third party application, and I know the VB code is spitting out the correct value but PHP is not. I have both VB and PHP code listed below, would anyone out there be familiar enough with both to have any idea why the PHP code isn't returning the correct value? I know the value that is being returned from PHP is the correct length, but there is something off and it's not matching. Please help.
VB:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim dataToHash As String
Dim encryptedText As String = ""
dataToHash = "hereismystring"
Dim buffer As Byte() = Encryption(dataToHash, "abcd1234")
encryptedText = Convert.ToBase64String(buffer)
lblToken.Text = encryptedText.ToString()
End Sub
Public Shared Function Encryption(ByVal PlainText As String, ByVal key As String) As Byte()
Dim des As TripleDES = CreateDES(key)
Dim ct As ICryptoTransform = des.CreateEncryptor()
Dim input As Byte() = Encoding.Unicode.GetBytes(PlainText)
Return ct.TransformFinalBlock(input, 0, input.Length)
End Function
Private Shared Function CreateDES(ByVal key As String) As TripleDES
Dim md5 As MD5 = New MD5CryptoServiceProvider()
Dim des As TripleDES = New TripleDESCryptoServiceProvider()
des.Key = md5.ComputeHash(Encoding.Unicode.GetBytes(key))
des.IV = New Byte(des.BlockSize / 8 - 1) {}
des.Padding = PaddingMode.Zeros
Return des
End Function
PHP:
$start = "hereismystring";
$cipher = MCRYPT_TRIPLEDES;
$mode = MCRYPT_MODE_CBC;
$rawKey = "abcd1234";
$ssoKey = md5($key_encoded,true);
$key_size = strlen($ssoKey);
$iv_size = mcrypt_get_iv_size(MCRYPT_TRIPLEDES, MCRYPT_MODE_CBC);
$ssoIV = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$user_str = mb_convert_encoding($start,"UTF-16LE");
$key_blocksize = mcrypt_get_block_size($cipher,$mode);
$key_padding_size = $key_blocksize - (strlen($user_str) % $key_blocksize);
$user_str .= str_repeat(chr($key_padding_size), $key_padding_size);
$key_iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher,$mode),"");
$key_triple = substr($key_encoded,0,mcrypt_get_key_size($cipher,$mode));
$key_encoded_text = mcrypt_encrypt($cipher,$key_triple,$user_str,$mode,$key_iv);
$final = base64_encode($key2_encoded_text);
echo "<p>" . $final </p>";
?>
Thanks,
Joe

How do I convert mcrypt_encrypt from PHP into .NET code?

I'm looking to convert this function from PHP to VB. Could anyone help me understand why the output is not correct?
//get img
$img = file_get_contents('https://www.random.org/analysis/randbitmap-rdo-section.png');
//pad
$blocksize = 16;
$pad = $blocksize - (strlen($img) % $blocksize);
$paddedimg = $img . str_repeat(chr($pad), $pad);
//encrypt
$data = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, 'abcdefghijklmnop', $paddedimg, MCRYPT_MODE_ECB);
//output
echo base64_encode($data);
The above outputs;
wYkugZmmsCHNwFOr7sAgk6yUU2I+2rOtBmXAIcPleue+dT4zIvkSA6UYmW6tickeoIbyCylxrb5n ...
[rest truncated but goes on and total is 29484 characters]
Here's what I have in VB;
Public Sub GetBase64EncryptedImg()
Dim Img As Byte() = Nothing
Using wc As New WebClient
Img = wc.DownloadData("https://www.random.org/analysis/randbitmap-rdo-section.png")
End Using
MsgBox(EncryptECB(Img))
End Sub
Public Function EncryptECB(Data As Byte()) As String
Dim Key As Byte() = Encoding.UTF8.GetBytes("abcdefghijklmnop")
Dim Encrypted As Byte() = Nothing
Using rj As New RijndaelManaged()
Try
rj.Padding = PaddingMode.PKCS7
rj.Mode = CipherMode.ECB
rj.KeySize = 128
rj.BlockSize = 128
rj.Key = Key
Dim ms As New MemoryStream()
Using cs As New CryptoStream(ms, rj.CreateEncryptor(rj.Key, rj.IV), CryptoStreamMode.Write)
Using sr As New StreamWriter(cs)
sr.Write(Data)
End Using
Encrypted = ms.ToArray()
End Using
Finally
rj.Clear()
End Try
End Using
Return Convert.ToBase64String(Encrypted)
End Function
The VB outputs;
pVngUaXYYv1tJSPzjDuwKw==
That's it, nowhere close to the right number of characters. Where am I going wrong here?
EDIT: Re being marked as duplicate, that question/answer gives back a base64 encoded string. mcrypt_encrypt doesn't, so I'm not sure how to apply the code in that answer.
EDIT2: That duplicate gives uses an IV value whereas the code above doesn't. Would that not differentiate the two to deserve a unique answer? Or is it as simple as removing the line setting the IV property of the RijndaelManaged object?
EDIT3: Completely reworked the question

Decrypting strings in Python that were encrypted with MCRYPT_RIJNDAEL_256 in PHP

I have a function in PHP that encrypts text as follows:
function encrypt($text)
{
$Key = "MyKey";
return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $Key, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
}
How do I decrypt these values in Python?
To decrypt this form of encryption, you will need to get a version of Rijndael. One can be found here. Then you will need to simulate the key and text padding used in the PHP Mcrypt module. They add '\0' to pad out the text and key to the correct size. They are using a 256 bit block size and the key size used with the key you give is 128 (it may increase if you give it a bigger key). Unfortunately, the Python implementation I've linked to only encodes a single block at a time. I've created python functions which simulate the encryption (for testing) and decryption in Python
import rijndael
import base64
KEY_SIZE = 16
BLOCK_SIZE = 32
def encrypt(key, plaintext):
padded_key = key.ljust(KEY_SIZE, '\0')
padded_text = plaintext + (BLOCK_SIZE - len(plaintext) % BLOCK_SIZE) * '\0'
# could also be one of
#if len(plaintext) % BLOCK_SIZE != 0:
# padded_text = plaintext.ljust((len(plaintext) / BLOCK_SIZE) + 1 * BLOCKSIZE), '\0')
# -OR-
#padded_text = plaintext.ljust((len(plaintext) + (BLOCK_SIZE - len(plaintext) % BLOCK_SIZE)), '\0')
r = rijndael.rijndael(padded_key, BLOCK_SIZE)
ciphertext = ''
for start in range(0, len(padded_text), BLOCK_SIZE):
ciphertext += r.encrypt(padded_text[start:start+BLOCK_SIZE])
encoded = base64.b64encode(ciphertext)
return encoded
def decrypt(key, encoded):
padded_key = key.ljust(KEY_SIZE, '\0')
ciphertext = base64.b64decode(encoded)
r = rijndael.rijndael(padded_key, BLOCK_SIZE)
padded_text = ''
for start in range(0, len(ciphertext), BLOCK_SIZE):
padded_text += r.decrypt(ciphertext[start:start+BLOCK_SIZE])
plaintext = padded_text.split('\x00', 1)[0]
return plaintext
This can be used as follows:
key = 'MyKey'
text = 'test'
encoded = encrypt(key, text)
print repr(encoded)
# prints 'I+KlvwIK2e690lPLDQMMUf5kfZmdZRIexYJp1SLWRJY='
decoded = decrypt(key, encoded)
print repr(decoded)
# prints 'test'
For comparison, here is the output from PHP with the same text:
$ php -a
Interactive shell
php > $key = 'MyKey';
php > $text = 'test';
php > $output = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB);
php > $encoded = base64_encode($output);
php > echo $encoded;
I+KlvwIK2e690lPLDQMMUf5kfZmdZRIexYJp1SLWRJY=
If you're willing to use MCRYPT_RIJNDAEL_128 rather than 256 on the PHP side, this is as simple as:
from Crypto.Cipher import AES
import base64
key="MyKey"
def decrypt(text)
cipher=AES.new(key)
return cipher.decrypt(base64.b64decode(text))
Although the answer from #101100 was a good one at the time, it's no longer viable. The reference is now a broken link, and the code would only run on older Pythons (<3).
Instead, the pprp project seems to fill the void nicely. On Python 2 or Python 3, just pip install pprp, then:
import pprp
import base64
KEY_SIZE = 16
BLOCK_SIZE = 32
def encrypt(key, plaintext):
key = key.encode('ascii')
plaintext = plaintext.encode('utf-8')
padded_key = key.ljust(KEY_SIZE, b'\0')
sg = pprp.data_source_gen(plaintext, block_size=BLOCK_SIZE)
eg = pprp.rjindael_encrypt_gen(padded_key, sg, block_size=BLOCK_SIZE)
ciphertext = pprp.encrypt_sink(eg)
encoded = base64.b64encode(ciphertext)
return encoded.decode('ascii')
def decrypt(key, encoded):
key = key.encode('ascii')
padded_key = key.ljust(KEY_SIZE, b'\0')
ciphertext = base64.b64decode(encoded.encode('ascii'))
sg = pprp.data_source_gen(ciphertext, block_size=BLOCK_SIZE)
dg = pprp.rjindael_decrypt_gen(padded_key, sg, block_size=BLOCK_SIZE)
return pprp.decrypt_sink(dg).decode('utf-8')
key = 'MyKey'
text = 'test'
encoded = encrypt(key, text)
print(repr(encoded))
# prints 'ju0pt5Y63Vj4qiViL4VL83Wjgirq4QsGDkj+tDcNcrw='
decoded = decrypt(key, encoded)
print(repr(decoded))
# prints 'test'
I'm a little dismayed that the ciphertext comes out different than what you see with 101100's answer. I have, however, used this technique to successfully decrypt data encrypted in PHP as described in the OP.

Categories