PHP 使用openssl 进行加密 解密

时间:2022-10-29 15:52:51
linux下命令直接使用openssl命令生成公钥和私钥,参考openssl 命令如下
# 产生1024位RSA私匙,用3DES加密它,口令为123,
# 输出到文件rsa_private_key.pem
# openssl genrsa -out rsa_private_key.pem

# 从文件rsa_private_key.pem读取私匙
# 生成的公钥匙输出到文件rsa_public_key.pem
# openssl rsa -in rsa_private_key.pem -out rsa_public_key.pem

# 用公钥匙rsapublickey.pem加密文件data.txt,
# 输出到文件cipher.txt
# openssl rsautl -encrypt -pubin -inkey rsa_public_key.pem -in data.txt -out cipher.txt

# 使用私钥匙rsa_private_key.pem解密密文cipher.txt,
# 输出到文件data.txt
# openssl rsautl -decrypt -inkey rsa_private_key.pem -in cipher.txt -out data.txt

# 用私钥匙rsaprivatekey.pem给文件plain.txt签名,
# 输出到文件signature.bin
# openssl rsautl -sign -inkey rsa_private_key.pem -in data.txt -out signature.bin

# 用公钥匙rsa_public_key.pem验证签名signature.bin,
# 输出到文件plain.txt
# openssl rsautl -verify -pubin -inkey rsa_public_key.pem -in signature.bin -out data

生成公钥和私钥文件

# openssl genrsa -out rsa_private_key.pem
# openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem

使用PHP读取公钥和私钥对数据进行加密和解密

<?php
$pub_file = file_get_contents('rsa_public_key.pem');
echo "读取公钥文件\n:$pub_file\n";
$pub_key = openssl_get_publickey($pub_file);
var_dump($pub_key);
$encrypt_result = openssl_public_encrypt('yangxunwu', $encrypted, $pub_key);
if($encrypt_result){
echo "\n加密数据成功\n".json_encode($encrypted)."\n";
}else{

die("\n加密数据失败".openssl_error_string()."\n");
}

$pri_file = file_get_contents('rsa_private_key.pem');
echo "读取私钥文件\n$pri_file\n";
$pri_key = openssl_get_privatekey($pri_file);
var_dump($pri_key);

$decrypt_result = openssl_private_decrypt($encrypted, $decrypted, $pri_key);
if($decrypt_result){
echo "\n解密数据成功\n".$decrypted."\n";
}else{
die("\n解密数据失败".openssl_error_string()."\n");

}

运行:

PHP 使用openssl 进行加密 解密

http://man.linuxde.net/openssl