brix / crypto-js

JavaScript library of crypto standards.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Wong encryption across php and cryptojs

AhmedHumk opened this issue · comments

I have written this function in typescript to encrypt string in typescript and decrypt it in php and vise versa.

Typescript side:

function AESEncrypt(Textdata : string){
    let Utf8 = CryptoJS.enc.Utf8;
    let AES = CryptoJS.AES;
    let mymode = CryptoJS.mode;
    let mysalt = CryptoJS.enc.Hex.stringify(CryptoJS.lib.WordArray.random(8 / 2));
    var myiv = CryptoJS.enc.Hex.stringify(CryptoJS.lib.WordArray.random(16 / 2));
    let mykey = Utf8.parse(keygen);
    let newiv = Utf8.parse(myiv);
    let newsalt = Utf8.parse(mysalt);

    let encrypted = AES.encrypt(Textdata, mykey, {
        iv: newiv,
        padding: CryptoJS.pad.Pkcs7,
        mode:mymode.CBC
    }).toString();
    let genIV = Utf8.stringify(newiv);
    let genSalt = Utf8.stringify(newsalt);
    let decoded = mybase64.base64Decode(encrypted);
    let outdata = genSalt + genIV + decoded;
    let outMessage = mybase64.base64encode(outdata);
    
    return outMessage;
}

Php side :

function AESEncrypt($Textdata, $Pwkey)
    {
    $output = false;
    $encrypt_method = "AES-256-CBC";
	$IV=openssl_random_pseudo_bytes(16, $securityok);
	$Salt=openssl_random_pseudo_bytes(8, $securityok);
	$encrypted = openssl_encrypt($Textdata, $encrypt_method, $Pwkey, 0,$IV);
	$OutData=Base64_encode($Salt.$IV.Base64_decode($encrypted));
	return $OutData;
    }

	
function AESDecrypt($Textdata, $Pwkey)
    {
    $output = false;
    $encrypt_method = "AES-256-CBC"; #32 chars is a must
    $total=base64_decode($Textdata);
	$salt=substr($total, 0, 8);
	$iv=substr($total, 8, 16);
	$encodedstr=Base64_Encode(substr($total, 24, strlen($total)-24));
	$OutData=openssl_decrypt($encodedstr, $encrypt_method, $Pwkey, 0,$iv);
	return $OutData;
    }

i have tried to make a few research and it seems i had to pad the string with PKCS5Padding before starting encrypting but i cant find anyway to do it with cryptojs or typescript