Google_P12Signer

Signs data.

Defined (1)

The class is defined in the following location(s).

/gdwpm-api/auth/Google_P12Signer.php  
  1. class Google_P12Signer extends Google_Signer { 
  2. // OpenSSL private key resource 
  3. private $privateKey; 
  4.  
  5. // Creates a new signer from a .p12 file. 
  6. function __construct($p12, $password) { 
  7. if (!function_exists('openssl_x509_read')) { 
  8. throw new Exception( 
  9. 'The Google PHP API library needs the openssl PHP extension'); 
  10.  
  11. // This throws on error 
  12. $certs = array(); 
  13. if (!openssl_pkcs12_read($p12, $certs, $password)) { 
  14. throw new Google_AuthException("Unable to parse the p12 file. " . 
  15. "Is this a .p12 file? Is the password correct? OpenSSL error: " . 
  16. openssl_error_string()); 
  17. // TODO(beaton): is this part of the contract for the openssl_pkcs12_read 
  18. // method? What happens if there are multiple private keys? Do we care? 
  19. if (!array_key_exists("pkey", $certs) || !$certs["pkey"]) { 
  20. throw new Google_AuthException("No private key found in p12 file."); 
  21. $this->privateKey = openssl_pkey_get_private($certs["pkey"]); 
  22. if (!$this->privateKey) { 
  23. throw new Google_AuthException("Unable to load private key in "); 
  24.  
  25. function __destruct() { 
  26. if ($this->privateKey) { 
  27. openssl_pkey_free($this->privateKey); 
  28.  
  29. function sign($data) { 
  30. if(version_compare(PHP_VERSION, '5.3.0') < 0) { 
  31. throw new Google_AuthException( 
  32. "PHP 5.3.0 or higher is required to use service accounts."); 
  33. if (!openssl_sign($data, $signature, $this->privateKey, "sha256")) { 
  34. if (!$this->my_openssl_sign($data, $signature, $this->privateKey, "sha256")) { 
  35. throw new Google_AuthException("Unable to sign data"); 
  36. return $signature; 
  37.  
  38. /** thanks to the unnamed friend of Niels Castle for this magic hack 
  39. * src = http://stackoverflow.com/questions/10524198/what-version-of-openssl-is-needed-to-sign-with-sha256withrsaencryption 
  40. * */ 
  41. function my_openssl_sign($data, &$signature, $priv_key_id, $signature_alg = 'sha256WithRSAEncryption') { 
  42. $pinfo = openssl_pkey_get_details($priv_key_id); 
  43. $hash = hash('sha256', $data); 
  44. $t = '3031300d060960864801650304020105000420'; # sha256 
  45. $t .= $hash; 
  46. $pslen = $pinfo['bits']/8 - (strlen($t)/2 + 3); 
  47.  
  48. $eb = '0001' . str_repeat('FF', $pslen) . '00' . $t; 
  49. $eb = pack('H*', $eb); 
  50.  
  51. return openssl_private_encrypt($eb, $signature, $priv_key_id, OPENSSL_NO_PADDING);