Errors decrypting as3crypto blowfish data in PHP - php

I'm kind of new to ActionScript 3 at the moment and been trying to use the as3crypto library to encrypt some data with the blowfish algorithm before submitting it to the server for processing. I know you can use https, but most browsers still display the outbound data making it very easy for a user to fake a request. That's why I want to let the user see the page request, but not be able to read the data without decrypting.
Unfortunately for me the deocumentation on the as3crypto library is pretty much non existent aside from comments in the code (which don't help too much). I've set up the flash side of things with a couple static functions to "implement" the as3crypto blowfish encryption and they work fine for encrypting/decrypting within flash only. The problem comes when I try to use the key to decrypt in PHP using the mcrypt library. The output I get is not the original code and I've spent a couple days trying to figure out why to no avail.
Below is the code and explanations. For purposes of this example, the key used was 'mykey' (without the quotes) and the encoded data was 'Hello World' (again without the quotes).
Flash code (as3crypto blowfish helper):
package lib.ef.crypto
{
import com.hurlant.util.Base64;
import com.hurlant.crypto.Crypto;
import flash.utils.ByteArray;
import com.hurlant.crypto.symmetric.IPad;
import com.hurlant.crypto.symmetric.ICipher;
import com.hurlant.crypto.symmetric.NullPad;
public class Blowfish
{
/**
* Encrypts a string.
* #param text The text string to encrypt.
* #param key A cipher key to encrypt the text with.
*/
static public function encrypt($text:String, $key:String=""):String
{
var cryptKey:ByteArray = new ByteArray();
cryptKey.writeUTF( $key );
var iPad:IPad = new NullPad();
var crypt:ICipher = Crypto.getCipher('blowfish-cfb',cryptKey,iPad);
iPad.setBlockSize( crypt.getBlockSize() );
var cryptText:ByteArray = new ByteArray();
cryptText.writeUTF( $text );
crypt.encrypt( cryptText );
trace( Base64.encodeByteArray( cryptText ) );
return null;
}
static public function decrypt($text:String, $key:String=""):String
{
return new String();
}
}
}
The output of that varies from run to run, but for the purpose of this example run, the base64 encoded output I get is 'EkKo9htSJUnzBmxc0A=='
When I bring that code into PHP it is base64 decoded before being passed into the method below to decrypt it:
public static function decrypt($crypttext,$key)
{
if( !function_exists('mcrypt_module_open') ) trigger_error('The blowfish encryption class requires the Mcrypt library to be compiled into PHP.');
$plaintext = '';
$td = mcrypt_module_open('blowfish', '', 'cfb', '');
$blocksize = mcrypt_enc_get_block_size($td);
$iv = substr($crypttext, 0, $blocksize);
$crypttext = substr($crypttext, $blocksize);
if (true)
{
mcrypt_generic_init($td, $key, $iv);
$plaintext = mdecrypt_generic($td, $crypttext);
}
return $plaintext;
}
At this point the output is completely unreadable. I suspect the issue may be related to the fact that either the as3crypto implementation of blowfish isn't correct (unlikely) or it could be something to do with the padding it uses (currently null padding) or lastly I've thought it may have something to do with the randomly generated initialization vector in as3crypto not being prepended to the front of the encoded string? That last one I haven't been able to really test because the as3crypto library is large, complicated, and not documented much at all. I've googled this issue and tested everything for a couple days now and I just keep coming up with unusable data in PHP. I know if I can get the Flash to PHP system working, I can reverse engineer it to get the PHP to Flash encryption running as well.
I welcome all input on this matter as it's actually been costing me sleep at night lol Thank you in advance :)
I've done some further testing today and attempted to see if it was the initialization vector as I suspected. I don't believe that's the problem. I modified some things in flash so that I could get an output of the IV used to generate the encoded output:
package lib.ef.crypto
{
import com.hurlant.util.Base64;
import com.hurlant.crypto.Crypto;
import flash.utils.ByteArray;
import com.hurlant.crypto.symmetric.IPad;
import com.hurlant.crypto.symmetric.ICipher;
import com.hurlant.crypto.symmetric.NullPad;
public class Blowfish
{
/**
* Encrypts a string.
* #param text The text string to encrypt.
* #param key A cipher key to encrypt the text with.
*/
static public function encrypt($text:String, $key:String=""):String
{
var cryptKey:ByteArray = new ByteArray();
cryptKey.writeUTF( $key );
var iPad:IPad = new NullPad();
var crypt = Crypto.getCipher('blowfish-cfb',cryptKey,iPad);
iPad.setBlockSize( crypt.getBlockSize() );
var cryptText:ByteArray = new ByteArray();
cryptText.writeUTF( $text );
crypt.encrypt( cryptText );
cryptText.position = 0;
var iv:ByteArray = crypt.IV;
iv.position = 0;
trace( Base64.encodeByteArray( iv ) );
trace( Base64.encodeByteArray( cryptText ) );
return null;
}
static public function decrypt($text:String, $key:String=""):String
{
return new String();
}
}
}
For this example I got an encoded IV of '1bcGpqIbWRc=' and encoded encrypted data of 'XpgART3hNQO10vcgLA==' I plugged those into a modified PHP function after base64_decode() ing them:
public static function decrypt($crypttext,$key,$iv=NULL)
{
if( !function_exists('mcrypt_module_open') ) trigger_error('The blowfish encryption class requires the Mcrypt library to be compiled into PHP.');
$plaintext = '';
$td = mcrypt_module_open('blowfish', '', 'cfb', '');
if( $iv === NULL ){
$ivsize = mcrypt_enc_get_iv_size($td);
echo '<pre>'.$ivsize.'</pre>';
$iv = substr($crypttext, 0, $ivsize);
echo '<pre>'.strlen($iv).'</pre>';
$crypttext = substr($crypttext, $ivsize);
}
if ($iv)
{
mcrypt_generic_init($td, $key, $iv);
$plaintext = mdecrypt_generic($td, $crypttext);
}
return $plaintext;
}
Even this output is incorrect. I've done some tests to make sure the IV is the correct size both in flash and PHP, but for some reason the PHP side of things just can't decrypt the blowfish encoded output from Flash. I've tried using both NULL and PKCS5 padding in as3crypto and neither works with PHP's system. I've tested to make sure the IV strings are the same in both Flash and PHP. They're both using the same keys. Both are using CFB mode. I don't get it. Same algorithm, same key, same IV, same mode, but they can't decrypt from each other. It's seeming to me that the as3crypto implementation of blowfish may be incorrect. Can anyone confirm this?

After doing some digging through the as3Crypto library files and demo code, I found that the problem is I need to use the getCipher function with simple-blowfish-cfb mode instead of blowfish-cfb mode. The encrypted output from calling crypt.encyrpt( cryptText ) will then be already prefixed with the IV of the algorithm so you make a single call to Base64.encodeByteArray( cryptText ) to get the output to send to PHP. When you initialize PHP the way I have above, it will slice off the IV from the string and decrypt properly. Hopefully this helps anyone else who comes along with this problem.
The "correct" flash and PHP code* is below for all you TLDR;ers who just want a quick copy/paste solution :P
*Note: I had to remove some of my application specific calls in both code samples and did not test them to insure they're 100% functional, but they should illustrate the concept/structure enough that if they don't work correctly "out of the box" you can easily mend them for your use.
PHP "helper" class:
class Blowfish
{
public static function encrypt($plaintext,$key)
{
if( !function_exists('mcrypt_module_open') ) trigger_error('The blowfish encryption class requires the Mcrypt library to be compiled into PHP.');
$td = mcrypt_module_open('blowfish', '', 'cbc', '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);
$crypttext = mcrypt_generic($td, $plaintext);
mcrypt_generic_deinit($td);
$out = $iv.$crypttext;
return $out;
}
public static function decrypt($crypttext,$key)
{
if( !function_exists('mcrypt_module_open') ) trigger_error('The blowfish encryption class requires the Mcrypt library to be compiled into PHP.');
$plaintext = '';
$td = mcrypt_module_open('blowfish', '', 'cbc', '');
$ivsize = mcrypt_enc_get_iv_size($td);
$iv = substr($crypttext, 0, $ivsize);
$crypttext = substr($crypttext, $ivsize);
if ($iv)
{
mcrypt_generic_init($td, $key, $iv);
$plaintext = mdecrypt_generic($td, $crypttext);
}
return $plaintext;
}
}
Flash "helper" class:
package [your package name]
{
import com.hurlant.util.Base64;
import com.hurlant.util.Hex;
import com.hurlant.crypto.Crypto;
import flash.utils.ByteArray;
import com.hurlant.crypto.symmetric.IPad;
import com.hurlant.crypto.symmetric.ICipher;
import com.hurlant.crypto.symmetric.IVMode;
import com.hurlant.crypto.symmetric.NullPad;
public class Blowfish
{
/**
* Encrypts a string.
* #param txt The text string to encrypt.
* #param k A cipher key to encrypt the text with.
*/
static public function encrypt(txt:String, k:String=""):String
{
var kdata:ByteArray;
kdata = Hex.toArray(Hex.fromString(k));
var data:ByteArray;
data = Hex.toArray(Hex.fromString(txt));
var pad:IPad = new NullPad;
var mode:ICipher = Crypto.getCipher('simple-blowfish-cbc', kdata, pad);
pad.setBlockSize(mode.getBlockSize());
mode.encrypt(data);
return Base64.encodeByteArray( data );
}
/**
* Decrypts a string.
* #param txt The text string to decrypt.
* #param k A cipher key to decrypt the text with.
*/
static public function decrypt(txt:String, k:String=""):String
{
var kdata:ByteArray;
kdata = Hex.toArray(Hex.fromString( Base64.decode( k ) ));
var data:ByteArray;
data = Hex.toArray(Hex.fromString(txt));
var pad:IPad = new NullPad;
var mode:ICipher = Crypto.getCipher('simple-blowfish-cbc', kdata, pad);
pad.setBlockSize(mode.getBlockSize());
mode.decrypt(data);
data.position = 0;
return data.readUTFBytes( data.bytesAvailable );
}
}
}

Thanx!
See here the correct "decrypt":
static public function decrypt(txt:String, k:String=""):String{
var kdata:ByteArray;
kdata = Hex.toArray(Hex.fromString(k));
var data:ByteArray;
data = Base64.decodeToByteArray(txt);
var pad:IPad = new NullPad;
var mode:ICipher = Crypto.getCipher('simple-blowfish-cbc', kdata, pad);
pad.setBlockSize(mode.getBlockSize());
mode.decrypt(data);
data.position = 0;
return data.readUTFBytes( data.bytesAvailable );
}

Related

Why does decipherIv.final() fail in node.js when decrypting a value encrypted using PHP?

PHP version: 5.6.39
Node.js version: 10.9.0
Objective: Encrypt using PHP and decrypt using Node.js
Stuck Point: I'm currently assuming that both the PHP and Node.js bindings to OpenSSL make use of PKCS7 padding. Do PHP and Node.js use incompatible bindings to OpenSSL?
Example PHP encryption/decryption code:
class SymmetricEncryption {
public static function simpleEncrypt($key, $plaintext) {
$iv = openssl_random_pseudo_bytes(16);
$ciphertext = openssl_encrypt($plaintext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv)
return base64_encode($iv) . "." . base64_encode($ciphertext);
}
public static function simpleDecrypt($key, $token) {
list($iv, $ciphertext) = explode(".", $token);
return openssl_decrypt(
base64_decode($ciphertext),
"aes-256-cbc",
$key,
OPENSSL_RAW_DATA,
base64_decode($iv)
);
}
}
Example Node.js encryption/decryption code:
class SymmetricEncryption {
static simpleEncrypt(key: Buffer, plaintext: string): string {
const iv = randomBytes(16)
const cipher = createCipheriv('aes-256-cbc', key, iv)
const encrypted = cipher.update(plaintext)
const token = Buffer.concat([encrypted, cipher.final()])
return iv.toString('base64') + "." + token.toString('base64')
}
static simpleDecrypt(key: Buffer, token: string): string {
const [iv, ciphertext] = token.split(".").map(piece => Buffer.from(piece, 'base64'))
const decipher = createDecipheriv('aes-256-cbc', key, iv)
const output = decipher.update(ciphertext)
return Buffer.concat([output, decipher.final()]).toString('utf8')
}
}
I've tested each implementation independently of one another successfully, but when encrypting in PHP and decrypting in node.js I get the following error:
Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
The stack trace points me to the offending line, which is decipher.final() in the simpleDecrypt method.
I'm using the following (failing) unit test to verify my implementation
it('should be able to decrypt values from php', () => {
const testAesKey = Buffer.from('9E9CEB8356ED0212C37B4D8CEA7C04B6239175420203AF7A345527AF9ADB0EB8', 'hex')
const phpToken = 'oMhL/oIPAGQdMvphMyWdJw==.bELyRSIwy+nQGIyLj+aN8A=='
const decrypted = SymmetricEncryption.simpleDecrypt(testAesKey, phpToken)
expect(decrypted).toBe('hello world')
})
The phpToken variable I'm using here was created using the following code:
$testAesKey = "9E9CEB8356ED0212C37B4D8CEA7C04B6239175420203AF7A345527AF9ADB0EB8";
echo SymmetricEncryption::simpleEncrypt($testAesKey, "hello world");
I suspect your issue is caused by how you pass your key in PHP. The documentation for openssl_encrypt doesn't specify anywhere that it interprets the key as hex. It does, however, truncate keys that are too long.
What is likely happening here is PHP is truncating your 64 character hex string down to 32 bytes, and using those for the key. Try using hex2bin on your PHP key before using it - this should fix your issue!
$testAesKey = hex2bin("9E9CEB8356ED0212C37B4D8CEA7C04B6239175420203AF7A345527AF9ADB0EB8");

Openssl equivalent to mcrypt_get_block_size

I am currently in the process of replacing Mcrypt with OpenSSL since Mcrypt will be deprecated in PHP 7.1. I need is a way to get the blocksize per algorithm like mcrypt_get_block_size().
I am wondering if there is an equivalent function to mcrypt_get_block_size() but it's pretty badly documented can't seem to find it.
php-openssl unfortunately doesn't have an API that would give you the cipher blockSize. If you really need it, you'd have to hard-code the blockSize (per algorithm).
However, typical applications would only need to support a single encryption algorithm, and in that case you should already know what the block size is for your case.
And also, the only use cases I've had for mcrypt_get_block_size(), mcrypt_enc_get_block_size() is PKCS#7 padding, which OpenSSL already does by default for block cipher algorithms. So it may be the case that you don't need this at all.
The following function can be used as a replacement for PHP >= 5.4.0.
It just bruteforces the block length out of openssl_encrypt().
if (!function_exists('openssl_cipher_block_length')) {
/**
* Returns the block length for a given cipher.
*
* #param string $cipher
* A cipher method (see openssl_get_cipher_methods()).
*
* #retval int
* The cipher's block length.
* Returns false if the actual length cannot be determined.
* Returns 0 for some cipher modes that do not use blocks
* to encrypt data.
*
* #note
* PHP >= 5.4.0 is required for this function to work.
*/
function openssl_cipher_block_length($cipher)
{
$ivSize = #openssl_cipher_iv_length($cipher);
// Invalid or unsupported cipher.
if (false === $ivSize) {
return false;
}
$iv = str_repeat("a", $ivSize);
// Loop over possible block sizes, from 1 upto 1024 bytes.
// The upper limit is arbitrary but high enough that is
// sufficient for any current & foreseeable cipher.
for ($size = 1; $size < 1024; $size++) {
$output = openssl_encrypt(
// Try varying the length of the raw data
str_repeat("a", $size),
// Cipher to use
$cipher,
// OpenSSL expands the key as necessary,
// so this value is actually not relevant.
"a",
// Disable data padding: php_openssl will return false
// if the input data's length is not a multiple
// of the block size.
//
// We also pass OPENSSL_RAW_DATA so that PHP does not
// base64-encode the data (since we just throw it away
// afterwards anyway)
OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING,
// Feed it with an IV to avoid nasty warnings.
// The actual value is not relevant as long as
// it has the proper length.
$iv
);
if (false !== $output) {
return $size;
}
}
// Could not determine the cipher's block length.
return false;
}
}
I think you can do something like that:
$method = 'AES-256-CBC';
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
$block_size = strlen(openssl_encrypt('', $method, '', OPENSSL_RAW_DATA, $iv));
It's basically encrypting an empty string and, as the data will be padded to the block size, check the result length.
I've tested it with some different methods, and it seems to work properly.
A more general approach that might help you involves using this polyfill: mcrypt_compat. A polyfill is a library that implements functionality which is not supported yet/anymore.
Step 1: install the library with Composer
composer require phpseclib/mcrypt_compat
Step 2: require Composer's autoloader at the top of the PHP script where you use the mcrypt functions (make sure the relative path is correct)
require_once('../vendor/autoload.php');
By now, you can use functions like mcrypt_get_block_size() in this PHP script
txigreman this solution worked for me, i managed to change MCRYPT code to use OPENSSL
this is my function to encrypt which replaced MCRYPT i mixed some code from MCRYPT and new code from openssl, while decrypt is not working but i can open payment page of provider and finish payment- thats what i needed and after it redirects me to success page, NeO.network.ae payment gateway
public $method = 'aes-256-cbc';
$this->EncryptedString = $this->encryptData($this->beforeEncryptionString, $this->merchantKey, $this->method);
public function encryptData(string $data, string $key, string $method): string
{
$ivSize = openssl_cipher_iv_length($method);
$iv = 'YOUR_IV';
$size = strlen(openssl_encrypt('', $method, '', OPENSSL_RAW_DATA, $iv));
$pad = $size - ( strlen( $data ) % $size );
$padtext = $data . str_repeat( chr( $pad ), $pad );
$encrypted = openssl_encrypt($padtext, $method, base64_decode( $key ), OPENSSL_RAW_DATA, $iv);
$encrypted = base64_encode($encrypted);
return $encrypted;
}

What is the best way to store e-mail accounts data used for sending mailing to customers in PHP?

I'm using PEAR::Mail to send a lot of e-mails to our customers. I want to be able to send those e-mails using different SMTP accounts (because of different mailing types). We have like 6-7 accounts, and in the future there might be more. Each of them has different password and we want to be able to store those passwords in database so it's not hardcoded and so you can add them more easily with administrator panel.
I know I want to use encryption for password storing, but imo hashing is not an option here. I want to be able to read those passwords, not only compare the hashes.
I would like to do it with storing encrypted passwords in database but encrypt them with some algorithm. And that's where I have problem - I don't know much about that. I'm attaching my test code for encryption, but I would like your opinion on how should I improve it:
if (!function_exists('hex2bin')) {
function hex2bin($data) {
$len = strlen($data);
return pack('H' . $len, $data);
}
}
$key = $_GET['key'];
$text = $_GET['text'];
$encr = $_GET['encr'];
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
if ($text != null) {
echo bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv));
}
if ($encr != null) {
echo mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, hex2bin($encr), MCRYPT_MODE_ECB);
}
ECB mode is insecure and the IV is ignored with this mode. You should really use CBC (MCRYPT_MODE_CBC) instead.
When using CBC an IV is required for encryption and the same IV is required for decryption, so you need to hang on to this value (but don't use the same IV for all encryption/decryption, generating a random one as in your code example is correct). The IV does not need to be stored securely (any more securely than the encrypted data), and it's standard proceedure to prepend the IV to the encrypted data.
bin2hex($iv . mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv));
When decrypting you strip off the IV and pass it in to mcrypt_decrypt.
$cipherTextDecoded = hex2bin($encr);
$iv = substr($cipherTextDecoded, 0, $iv_size);
$cipherText = substr($cipherTextDecoded, $iv_size);
mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $cipherText, MCRYPT_MODE_CBC, $iv);
Also note that you should be using a binary key. $_GET['key'] is returning a string of text, and because you're not hex decoding it your keyspace is limited to all possible 256-bit strings rather than all 256-bit binary values.
Further, it's a bit misleading in PHP, but the 256 in MCRYPT_RIJNDAEL_256 refers to the block size, not the strength of the encryption. If you want to use 256 bit encryption, just pass a 256 bit key to the mcrypt functions. If that was your goal I'd consider using MCRYPT_RIJNDAEL_128 instead, this will make the encrypted text compatible with AES-128. If you ever need to decrypt the data in some other system (unlikely I know), it's much easier to find an AES-128 imeplementation than Rijindael 256.
I created a class which does everything what Syon mentioned. I'm attaching it here for future reference, if anyone would like to use it then feel free.
<?php
if (!function_exists('hex2bin')) {
function hex2bin($data) {
$len = strlen($data);
return pack('H' . $len, $data);
}
}
/**
* Encipherer - Class used for encoding and decoding
*
* #author kelu
* #version $Id$
*
*/
class Encipherer {
private $key;
private $iv_size;
private $mode = MCRYPT_MODE_CBC;
private $algorithm = MCRYPT_RIJNDAEL_256;
private $rand = MCRYPT_RAND;
/**
* returns singleton
*
* #return Encipherer
*/
public static function Instance()
{
static $inst = null;
if ($inst === null) {
$inst = new Encipherer;
}
return $inst;
}
private function __construct($key = '') {
$this->iv_size = mcrypt_get_iv_size($this->algorithm, $this->mode);
$this->key = $this->key = hex2bin($key);
}
private function __clone()
{
return Encipherer::Instance();
}
public function setKey($key) {
$this->key = $this->key = hex2bin($key);
}
public function encrypt($text) {
$iv = mcrypt_create_iv($this->iv_size, $this->rand);
return bin2hex($iv . mcrypt_encrypt($this->algorithm, $this->key, $text, $this->mode, $iv));
}
public function decrypt($text) {
$cipherTextDecoded = hex2bin($text);
$iv = substr($cipherTextDecoded, 0, $this->iv_size);
$cipherText = substr($cipherTextDecoded, $this->iv_size);
return mcrypt_decrypt($this->algorithm, $this->key, $cipherText, $this->mode, $iv);
}
}
?>
Example usage:
<?
$enc = Encipherer::Instance();
$enc->setKey('1234qwerty');
$encrypted = $enc->encrypt('secret message');
$decrypted = $enc->decrypt($encrypted);
?>

PHP MYCRYPT - RIJNDAEL_128 with Mcrypt CBC is giving incorrect output

I am using a text
const ENCRYPTION_KEY = '3aa22e01c04c7059778c54d122b0273689fba00f4a166a66d15f7ba6a8ba8743';
$str = "1844427316My Name Is Dave1336407610774000000000000";
function encrypt($str){
trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128,ENCRYPTION_KEY, $str,MCRYPT_MODE_CBC,mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_CBC),MCRYPT_RAND))));
}
function decrypt($encryptedtext){
return trim(
mcrypt_decrypt(
MCRYPT_RIJNDAEL_128,
ENCRYPTION_KEY,
base64_decode($encryptedtext),
MCRYPT_MODE_CBC,
mcrypt_create_iv(
mcrypt_get_iv_size(
MCRYPT_RIJNDAEL_128,
MCRYPT_MODE_CBC
),
MCRYPT_RAND
)
)
);
}
But whenever I refresh the page calling these function with values mentioned above, I get different values encryption, but in decryption, the initial decrypted value changes everytime but rest gets decrypted correctly like wise:
F7…Ÿ{4©eŠQ9­t¤e Is Dave1336407610774000000000000
I have also refered the SIMILAR QUESTION and used the "iv" function in decryption as well as answered in it
Could some one guide me whats getting wrong in here?
It was thoughtful But I found the Solution:
While decrypting, I used the same IV and key as when encrypting.
My encrypt function needs to return the IV as well as the encrypted data. That IV is sent to the decrypt function with the data and the key.
See the below Change in Code with complete code:
class Encypt{
const ENCRYPTION_KEY = '3aa22e01c04c7059778c54d122b0273689fba00f4a166a66d15f7ba6a8ba8743';
function createQueryString(){
$str = "1844427316My Name Is Dave1336407610774000000000000";
$encStr = $this->encrypt($str);
return $encStr;
}
function encrypt($strValue){
$iv =mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_CBC),MCRYPT_RAND);
$encData = trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128,self::ENCRYPTION_KEY, $strValue,MCRYPT_MODE_CBC,$iv)));
$data['iv'] = $iv;
$data['encdata'] = $encData;
return $data;
}
/**
* Function to decrypt data using AES Encryption Symmetric Algorithm 128 bytes
*/
function decrypt($strValue, $iv){
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128,ENCRYPTION_KEY,base64_decode($strValue),MCRYPT_MODE_CBC,$iv));
}
}
$enc_obj = new Encypt();
$encstr = $enc_obj->createQueryString();
echo "Encrypted Str:-->".$encstr['encdata']."<br>";
$deCrypt = $enc_obj->decrypt($encstr['encdata'], $encstr['iv']);
echo "Decrypted Str:-->".$deCrypt;

encryption decryption function in php

import gnupg, urllib
retk = urllib.urlopen("http://keyserver.pramberger.at/pks/"
"lookup?op=get&search=userid for the key is required")
pub_key = retk.read()
#print pub_key
gpg = gnupg.GPG(gnupghome="/tmp/foldername", verbose=True)
print "Import the Key :", gpg.import_keys(pub_key).summary()
print "Encrypt the Message:"
msg = "Hellllllllllo"
uid = "userid that has the key on public key server"
enc = gpg.encrypt(msg, uid,always_trust=True)
print "*The enc content***************************== ", enc
this function written in python gives me encrypted message.The encryption is done using the public key which i am getting from public key server(pramberger.at).
Now how can i implement the same functionality (getting the key from any public key server and using that key encrypt the message) in php.
Have a look at mcrypt here: PHP.NET Mcrypt
Tutorials are as follows:
An Introduction to mcrypt in PHP
Two-way encryption using PHP and Mcrypt
PHP Encryption / MCrypt Library
Code example using Mcrypt:
<?php
/*
* phpFreaksCrypto.class.php4 -> phpFreaksCrypto Class (PHP4)
*/
/**
* #author Dustin Whittle
* #version 0.01
*/
if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME']))
{
// tell people trying to access this file directly goodbye...
exit('This file can not be accessed directly...');
}
class phpFreaksCrypto
{
var $td;
// this gets called when class is instantiated
function phpFreaksCrypto($key = 'MyRandomStringThatWillAlwaysBeTheSame', $iv = false, $algorithm = 'tripledes', $mode = 'ecb')
{
if(extension_loaded('mcrypt') === FALSE)
{
$prefix = (PHP_SHLIB_SUFFIX == 'dll') ? 'php_' : '';
dl($prefix . 'mcrypt.' . PHP_SHLIB_SUFFIX) or die('The Mcrypt module could not be loaded.');
}
if($mode != 'ecb' && $iv === false)
{
/*
the iv must remain the same from encryption to decryption and is usually
passed into the encrypted string in some form, but not always.
*/
die('In order to use encryption modes other then ecb, you must specify a unique and consistent initialization vector.');
}
// set mcrypt mode and cipher
$this->td = mcrypt_module_open($algorithm, '', $mode, '') ;
// Unix has better pseudo random number generator then mcrypt, so if it is available lets use it!
$random_seed = strstr(PHP_OS, "WIN") ? MCRYPT_RAND : MCRYPT_DEV_RANDOM;
// if initialization vector set in constructor use it else, generate from random seed
$iv = ($iv === false) ? mcrypt_create_iv(mcrypt_enc_get_iv_size($this->td), $random_seed) : substr($iv, 0, mcrypt_enc_get_iv_size($this->td));
// get the expected key size based on mode and cipher
$expected_key_size = mcrypt_enc_get_key_size($this->td);
// we dont need to know the real key, we just need to be able to confirm a hashed version
$key = substr(md5($key), 0, $expected_key_size);
// initialize mcrypt library with mode/cipher, encryption key, and random initialization vector
mcrypt_generic_init($this->td, $key, $iv);
}
function encrypt($plain_string)
{
/*
encrypt string using mcrypt and then encode any special characters
and then return the encrypted string
*/
return base64_encode(mcrypt_generic($this->td, $plain_string));
}
function decrypt($encrypted_string)
{
/*
remove any special characters then decrypt string using mcrypt and then trim null padding
and then finally return the encrypted string
*/
return trim(mdecrypt_generic($this->td, base64_decode($encrypted_string)));
}
// since php 4 does not have deconstructors, we will need to manually call this function
function __destruct()
{
// shutdown mcrypt
mcrypt_generic_deinit($this->td);
// close mcrypt cipher module
mcrypt_module_close($this->td);
}
}
?>
The PHP equivalent should be the GnuPG extension. Take a look at the manual for gnupg_encrypt() and gnupg_decrypt().

Categories