• PHP 使用openssl 进行加密 解密


    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 "读取公钥文件
    :$pub_file
    ";
    	    $pub_key = openssl_get_publickey($pub_file);
    	    var_dump($pub_key);
            $encrypt_result = openssl_public_encrypt('yangxunwu', $encrypted, $pub_key);
            if($encrypt_result){
            	echo "
    加密数据成功
    ".json_encode($encrypted)."
    ";
            }else{
    
            	die("
    加密数据失败".openssl_error_string()."
    ");
            }
    
            $pri_file = file_get_contents('rsa_private_key.pem');
            echo "读取私钥文件
    $pri_file
    ";
            $pri_key = openssl_get_privatekey($pri_file);
            var_dump($pri_key);
            
            $decrypt_result = openssl_private_decrypt($encrypted, $decrypted, $pri_key);
            if($decrypt_result){
            	echo "
    解密数据成功
    ".$decrypted."
    ";
            }else{
            	die("
    解密数据失败".openssl_error_string()."
    ");
            	
            }
    

    运行:

    http://man.linuxde.net/openssl
  • 相关阅读:
    虚拟机vmware的连接方式以及IP端口,协议等概念
    python3爬虫--shell命令的使用和firefox firebug获取目标信息的xpath
    numpy的基本用法
    scrapy模拟请求头
    (1)python Scrapy爬虫框架
    flutter ui
    dart 类
    dart 基础
    黑苹果镜像下载地址
    android9.0请求异常
  • 原文地址:https://www.cnblogs.com/yangxunwu1992/p/6593461.html
Copyright © 2020-2023  润新知