如何在php中使用公钥加密word文档

时间:2014-01-08 17:56:32

标签: php encryption phpseclib

我遇到问题,我想使用公钥加密word文档(只有10 Kb),并且必须使用私钥解密。 我已经使用phpseclib库创建了密钥对。 http://phpseclib.sourceforge.net/crypt/examples.html 我可以使用该库加密和解密字符串。但我不知道如何使用密钥对加密文件。 有没有任何方法。(或使用file_get_contents) 谢谢所有

<?php

//create word docx using phpdocx
require("phpDocx.php"); 
    $phpdocx = new phpdocx("word_temp\loan_app_temp.docx");
                                //assign
                                $upfno='999';
                                $loanid_db='1234';
                                $phpdocx->assign("#upfno#","$upfno"); 
                                $phpdocx->assign("#loanid#","$loanid_db"); 
                                $phpdocx->assign("#fullname#","$name"); 
                                $phpdocx->assign("#initials#","$initials"); 

                                $phpdocx->save("word_gen\loan_docs\la_".$upfno."_".$loanid_db.".docx"); // sucessfully created.

// create key pair using phpseclib
set_include_path(get_include_path() . PATH_SEPARATOR . 'phpseclib');
include('phpseclib/Crypt/RSA.php');
$rsa = new Crypt_RSA();
//$rsa->setPassword('layanthi@123');
extract($rsa->createKey());
//echo "$privatekey<br />$publickey";
echo $privatekeydata=$privatekey;
echo '<br />';
echo $pubkey=$publickey;  //key pair genarated - ok

//encryption using pubkey - commented snippet from phpseclib
$file="word_gen\loan_docs\la_".$upfno."_".$loanid_db.".docx";
$message=file_get_contents($file);
 function rsa_encrypt($key, $message) {
    $rsa = new Crypt_RSA(); 
    $rsa->loadKey($key); 
    $encrypted = base64_encode($rsa->encrypt($message)); 
    return $encrypted;
}
echo $encrypt_file=rsa_encrypt($pubkey, $message);
//from here i want to save encryptted file to encrypt folder like
//$savepath="encrypt\la_".$upfno."_".$loanid_db.".docx";  but i dont know how to do that

//Deryption using phpseclib function is here - but how to use it for above  encryption
 function rsa_decrypt($key, $package) {
    $rsa = new Crypt_RSA(); 
    $rsa->loadKey($key); 
    $decrypted = $rsa->decrypt(base64_decode($package)); 
    return $decrypted;
}

1 个答案:

答案 0 :(得分:0)

echo $encrypt_file=rsa_encrypt($pubkey, $message);
$savepath="word_gen\encrypt\la_".$upfno."_".$loanid_db.".docx";

file_put_contents($savepath, $encrypt_file);

//Deryption using phpseclib function is here - but how to use it for above  encryption

 function rsa_decrypt($key, $package) {
    $rsa = new Crypt_RSA(); 
    $rsa->loadKey($key); 
    $decrypted = $rsa->decrypt(base64_decode($package)); 
    return $decrypted;
}

//get encrypt file
$encfile="word_gen\encrypt\la_".$upfno."_".$loanid_db.".docx";
$epackage=file_get_contents($encfile);

echo $decryptfile= rsa_decrypt($privatekeydata, $epackage);
$savepath_de="word_gen\decrypt\la_".$upfno."_".$loanid_db.".docx";

file_put_contents($savepath_de, $encrypt_file);

?>