PHP gnupg加密解密

本文详细介绍了在PHP环境中安装GPG的过程,包括环境配置、扩展安装及使用示例。通过面向对象和面向过程两种方式,展示了如何利用GPG进行文件解密,适合PHP开发者学习和参考。
<?php

一:环境安装gpg
     https://blog.youkuaiyun.com/leyangjun/article/details/83146592


二:安装扩展
     下载安装地址:http://pecl.php.net/package/gnupg 下载后解压安装


三:PHP使用gpg解密例子

1:面向对象形式
$gpg = new gnupg(); //如果没有找到gnupg类,new \gnupg()命名空间冲突原因找不到
$gpg->seterrormode(gnupg::ERROR_EXCEPTION);

$publicKeyData = file_get_contents('/User/leyangjun/gpg.leyangjun_public.key');//导入对应的公钥,就是gpp生成的
$publicInfo = $gpg -> import($publicKeyData);

$privateKeyData = file_get_contents('/User/leyangjun/gpg.leyangjun_private.key');//导入私钥用于解密,导入后会自动找该私密解密
$gpg -> import($privateKeyData);


$cipherText = file_get_contents('/User/leyangjun/leyangjun.txt.gpg');//需要解密的文件
$gpg->adddecryptkey($publicInfo['fingerprint'], '');//fingerprint为钥匙指纹
try {
    $plaintext = $gpg->decrypt($ciphertext);  var_dump($plaintext);
} catch (Exception $e) {
    die('ERROR: ' . $e->getMessage());
}


//===========================================================================

2:面向过程形式
$gpg = gnupg_init();
$publicPath = Gpg::getPath('gpg_meitu_public');
$publicKey = file_get_contents('/User/leyangjun/gpg.leyangjun_public.key');//导入公钥
$publicInfo = gnupg_import($gpg,$publicKey);


$privateKey = file_get_contents('/User/leyangjun/gpg.leyangjun_private.key');//导入私钥
gnupg_import($gpg,$privateKey);

$DecryptFile = '/User/leyangjun/leyangjun.txt.gpg';
$cipherText = file_get_contents($DecryptFile);
gnupg_adddecryptkey($publicInfo['fingerprint'], '');
try {
    $plainText = gnupg_decrypt($gpg,$cipherText);
    var_dump($plainText);

}catch (Exception $e) {
    die('ERROR: ' . $e->getMessage());
}

 

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值