Skip to content

Instantly share code, notes, and snippets.

@truth3
Created October 29, 2019 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save truth3/714d5cd5a82769dcf81173f5a1a50e03 to your computer and use it in GitHub Desktop.
Save truth3/714d5cd5a82769dcf81173f5a1a50e03 to your computer and use it in GitHub Desktop.
<?php
$inFile = "encrypted.xml";
$outFile = "decrypted.xml";
$privateKeyFile = "private_key.pem";
$header = '<?xml version="1.0" encoding="UTF-8"?>';
//-----------------------------------------------
function rsaDecryptWithKeyString($encryptedData, $rsaPrivKey){
$key = openssl_get_privatekey($rsaPrivKey);
$data = base64_decode($encryptedData);
$outBuffer = '';
if (!$key || !openssl_private_decrypt($data,$outBuffer,$key,OPENSSL_PKCS1_OAEP_PADDING)){
$outBuffer = $encryptedData; //Error. can't decrypt
}
return $outBuffer;
}
function startElement($parser, $name, $attrs)
{
global $ofile;
fwrite($ofile, "<$name>");
}
function endElement($parser, $name)
{
global $ofile;
fwrite($ofile,"</$name>\n");
}
function characterDataHandler($parser, $data){
global $ofile,$rsaPrivKey;
fwrite($ofile, rsaDecryptWithKeyString($data, $rsaPrivKey));
}
$rsaPrivKey = file_get_contents($privateKeyFile);
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler( $xml_parser, "characterDataHandler");
if (!($fp = fopen($inFile, "r"))) {
die("could not open XML input");
}
$ofile = fopen($outFile, 'w');
fwrite($ofile, $header);
while ($data = fread($fp, 4096)) {
if (!xml_parse($xml_parser, $data, feof($fp))) {
die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}
}
xml_parser_free($xml_parser);
fclose($ofile);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment