当前位置:   article > 正文

PHP非对称加密(公钥加密私钥解密):RSA (RSA/ECB/PKCS1Padding)+base64_encode/bin2hex加密_php rsa

php rsa

所谓非对称,就是使用公钥/私钥加密,然后用对应的私钥/公钥解密

 1.配对的公钥,私钥:

  1. //公钥(注意包括头(-----BEGIN PUBLIC KEY-----)尾(-----END PUBLIC KEY-----)标志)
  2. -----BEGIN PUBLIC KEY-----
  3. MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDbdq5NjtUEkAQ6wucPuhC0aRvSMsaX3GrhkwsLLdWZnVNVpkJRw
  4. yPFq9HJNuntRw7P9Sb3TkwrpN60x62kZ6qV8h1GoG4jIfofuVWPv1VzudAV6kWJWMl3sc
  5. +DtV5q1dy1KQLb6e90cuOynzxVT3j+Fx7ZOzovmdTkEcoRiYWV1QIDAQAB
  6. -----END PUBLIC KEY-----
  7. //私钥(注意包括头(-----BEGIN RSA PRIVATE KEY-----)尾(-----END RSA PRIVATE KEY-----)标志)
  8. -----BEGIN RSA PRIVATE KEY-----
  9. MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKBc0G8WmfydUuX6TnO5M3lSmNYqy8beEgBn24vWk6sWCZ2va+TRIWEew5dxmMXg5+N40a2XOJfyTxCALvzts+/J0q8efi2WIecPecWGNoDB8ZehGfzv3BQD5skk9sf1tL6ztU5tquPFajwmO85WR2pTFfk0CXgPEtLzPxntYfHpAgMBAAECgYB6DSo24qTgt3zYvOHpAhRDSrI4jun5uhtJY8Kdc/uAQ42eDl24EdOt75Q+N59nO/5CCzrLPEU+oJW8oVMh/mjr6gMv7QxhEr1iUrZmvAGTO2kB5sMgWfqPkiHeGddYWawcWGhAwQEJrrgGVldzaslY9FvWcmTjCjypEVvB7l1BgQJBAOJwB2RbRbI+z0d1M6DOawyu+J7JleMAQ42x9KyhiwYc/D0CZX0gkuyqGcwSh+c1CYjjdoRIh/531e1OZyBmRG0CQQC1TG68k+iXuz14+fgpHEttl2E3lQ6VfIzv+oaQHnRmmT92t2Eci70zkDFjVCGXxwQ279EokmP6RWfJG5Z1nV3tAkAZkHpVKzTQLeUq9SFyCzvsv6hUDQA+E56M1cWA4/AVLZqQrL+Wg+HylDW7Y3AyeztrV/rebm3kHdVqKEreTo11AkBPUou40nYXvQKeZbAgPJL79hnA+eSRnxcDAHfTop+HLFHKHV3N4Y38e4BAV1UDVT4Q00iOGc7Id4l7QijIePvZAkEA1OmJfbsaCx3T+4lZahzo8k7NzP5BS6izPVAVk8O3LHo3TggJZMa69Nc+8O82ZXOiOSt7bSONaST54ejjN8yhtg==
  10. -----END RSA PRIVATE KEY-----

 2.判断openssl扩展是否安装

 extension_loaded('openssl') or die('PHP加密需要openssl扩展支持');

3.判断公钥和私钥是否可用 

  1. //私钥文件路径
  2. $this->privateKey = file_get_contents(dirname(__FILE__) .'libraries/YCPAY/account/rsa_private_key.pem');
  3. //公钥文件路径
  4. $this->publicKey = file_get_contents(dirname(__FILE__) . 'libraries/YCPAY/account/rsa_public_key.pem');
  5. /**
  6. * 生成Resource类型的密钥,如果密钥文件内容被破坏,openssl_pkey_get_private函数返回false
  7. */
  8. $privateKey = openssl_pkey_get_private($this->privateKey);
  9. /**
  10. * 生成Resource类型的公钥,如果公钥文件内容被破坏,openssl_pkey_get_public函数返回false
  11. */
  12. $publicKey = openssl_pkey_get_public($this->publicKey);
  13. ($privateKey) or die('密钥不可用');
  14. ($publicKey) or die('公钥不可用');

4.公钥加密

由于openssl_public_encrypt()加密对加密串有字符限制(117字节),所有需要分段加密(每段32个字符,加密后拼接起来)

  1. define("BAOFOO_ENCRYPT_LEN", 32);
  2. // 公钥加密
  3. function encryptedByPublicKey($data_content)
  4. {
  5. $publicKey = openssl_pkey_get_public($this->publicKey);
  6. $encrypted = "";
  7. $totalLen = strlen($data_content);
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/1021495
推荐阅读
相关标签
  

闽ICP备14008679号