PHP RSA加密解密

技术 置顶 精帖
0 938
peng49
peng49 2022-03-07 11:00:17
 

生成公钥、私钥对

生成原始 RSA私钥文件

openssl genrsa -out rsa_private_key.pem 1024

将原始 RSA私钥转换为 pkcs8格式

openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out private_key.pem

生成RSA公钥 rsa_public_key.pem

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

代码测试

  1. <?php
  2. function get_private_key() {
  3. $abs_path = './data/rsa_private_key.pem';
  4. $content = file_get_contents($abs_path);
  5. return openssl_pkey_get_private($content);
  6. }
  7. function get_public_key() {
  8. $abs_path = './data/rsa_public_key.pem';
  9. $content = file_get_contents($abs_path);
  10. return openssl_pkey_get_public($content);
  11. }
  12. function priv_encrypt($data = '') {
  13. if (!is_string($data)) {
  14. return null;
  15. }
  16. return openssl_private_encrypt($data, $encrypted, get_private_key()) ? base64_encode($encrypted) : null;
  17. }
  18. function priv_decrypt($encrypted = '') {
  19. if (!is_string($encrypted)) {
  20. return null;
  21. }
  22. return (openssl_private_decrypt(base64_decode($encrypted), $decrypted, get_private_key())) ? $decrypted : null;
  23. }
  24. function public_encrypt($data = '') {
  25. if (!is_string($data)) {
  26. return null;
  27. }
  28. return openssl_public_encrypt($data, $encrypted, get_public_key()) ? base64_encode($encrypted) : null;
  29. }
  30. function public_decrypt($encrypted = '') {
  31. if (!is_string($encrypted)) {
  32. return null;
  33. }
  34. return (openssl_public_decrypt(base64_decode($encrypted), $decrypted, get_public_key())) ? $decrypted : null;
  35. }
  36. //私钥加密
  37. $encrypted = priv_encrypt('123456');
  38. var_dump($encrypted);
  39. //公钥解密
  40. var_dump(public_decrypt($encrypted));
  41. //公钥加密
  42. $encrypted = public_encrypt('999999');
  43. var_dump($encrypted);
  44. //私钥解密
  45. var_dump(priv_decrypt($encrypted));

注意: RSA加解密中必须考虑到的密钥长度、明文长度和密文长度问题。明文长度需要小于密钥长度,而密文长度则等于密钥长度。因此当加密内容长度大于密钥长度时,有效的RSA加解密就需要对内容进行分段

参考链接:
PHP 使用非对称加密算法(RSA)
RSA加密长度限制问题

回帖
登录
忘记密码?