llpay_security.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: tandunzhao
  5. * Date: 2017/12/27
  6. * Time: 下午8:06
  7. */
  8. namespace App\Libs\lianlianpay;
  9. class llpay_security
  10. {
  11. public static function aesEncrypt($data,$key,$nonce){
  12. return base64_encode( openssl_encrypt ($data, "AES-256-CTR", $key, true, $nonce . "\0\0\0\0\0\0\0\1"));
  13. }
  14. public static function aesDecrypt($data,$key,$nonce){
  15. return openssl_decrypt (base64_decode($data), "AES-256-CTR", $key, true, $nonce . "\0\0\0\0\0\0\0\1");
  16. }
  17. public static function genLetterDigitRandom($size) {
  18. $allLetterDigit = array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
  19. $randomSb = "";
  20. $digitSize = count($allLetterDigit)-1;
  21. for($i = 0; $i < $size; $i ++){
  22. $randomSb .= $allLetterDigit[rand(0,$digitSize)];
  23. }
  24. return $randomSb;
  25. }
  26. public static function rsaEncrypt($data,$public_key){
  27. openssl_public_encrypt ( $data, $encrypted, $public_key,OPENSSL_PKCS1_OAEP_PADDING ); // 公钥加密
  28. return base64_encode ( $encrypted );
  29. }
  30. public static function rsaDecrypt($data,$private_key){
  31. openssl_private_decrypt(base64_decode ($data), $decrypted, $private_key,OPENSSL_PKCS1_OAEP_PADDING ); // 私钥解密
  32. return $decrypted;
  33. }
  34. public static function lianlianpayEncrypt($req, $public_key, $hmack_key, $version, $aes_key, $nonce) {
  35. $B64hmack_key = llpay_security::rsaEncrypt ( $hmack_key, $public_key );
  36. $B64aes_key = llpay_security::rsaEncrypt ( $aes_key, $public_key );
  37. $B64nonce = base64_encode($nonce);
  38. $encry = llpay_security::aesEncrypt ( utf8_decode($req), $aes_key, $nonce);
  39. $message = $B64nonce . "$" .$encry;
  40. $sign = hex2bin(hash_hmac("sha256",$message,$hmack_key));
  41. $B64sign = base64_encode($sign);
  42. return $version . '$' . $B64hmack_key . '$' . $B64aes_key . '$' . $B64nonce . '$' . $encry . '$' . $B64sign;
  43. }
  44. public static function ll_encrypt($plaintext, $public_key) {
  45. $pu_key = openssl_pkey_get_public ( $public_key );
  46. $hmack_key = llpay_security::genLetterDigitRandom(32);
  47. $version = "lianpay1_0_1";
  48. $aes_key = llpay_security::genLetterDigitRandom(32);
  49. $nonce = llpay_security::genLetterDigitRandom(8);
  50. return llpay_security::lianlianpayEncrypt($plaintext, $pu_key, $hmack_key, $version, $aes_key, $nonce);
  51. }
  52. }