PageRenderTime 48ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/core/src/main/php/security/KeyPair.class.php

http://github.com/xp-framework/xp-framework
PHP | 96 lines | 32 code | 7 blank | 57 comment | 2 complexity | 35e9fc1f4c9ae013b849d1eef55c4bc1 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /* This class is part of the XP framework
  3. *
  4. * $Id$
  5. */
  6. uses(
  7. 'security.OpenSslUtil',
  8. 'security.crypto.PublicKey',
  9. 'security.crypto.PrivateKey'
  10. );
  11. /**
  12. * Key pair
  13. *
  14. * <code>
  15. * uses('security.KeyPair');
  16. *
  17. * try {
  18. * if ($keypair= KeyPair::generate('md5', OPENSSL_KEYTYPE_RSA, 384)) {
  19. * $export= $keypair->export('krowemarf-px');
  20. * }
  21. * } catch(XPException $e) {
  22. * $e->printStackTrace();
  23. * exit();
  24. * }
  25. *
  26. * var_dump(
  27. * $keypair,
  28. * $export
  29. * );
  30. * </code>
  31. *
  32. * @see php://openssl_pkey_new
  33. * @ext openssl
  34. */
  35. class KeyPair extends Object {
  36. /**
  37. * Generates a new private and public key pair.
  38. *
  39. * Supported algorithms
  40. * <pre>
  41. * md2 MD2 Digest
  42. * md5 MD5 Digest
  43. * mdc2 MDC2 Digest
  44. * rmd160 RMD-160 Digest
  45. * sha SHA Digest
  46. * sha1 SHA-1 Digest
  47. * </pre>
  48. *
  49. * @param string algorithm default "md5"
  50. * @param int type default OPENSSL_KEYTYPE_RSA
  51. * @param int bits default 1024
  52. * @return security.KeyPair
  53. */
  54. public static function generate($algorithm= 'md5', $type= OPENSSL_KEYTYPE_RSA, $bits= 1024) {
  55. if (FALSE === ($res= openssl_pkey_new(array(
  56. 'digest_alg' => $algorithm,
  57. 'private_key_type' => $type,
  58. 'private_key_bits' => $bits
  59. )))) {
  60. trigger_error(implode("\n @", OpenSslUtil::getErrors()), E_USER_NOTICE);
  61. throw new XPException('Could not generate keypair');
  62. }
  63. $k= new self();
  64. $k->_res= $res;
  65. return $k;
  66. }
  67. /**
  68. * Export this keypair
  69. *
  70. * @param string passphrase default NULL
  71. * @return string key
  72. */
  73. public function export($passphrase= NULL) {
  74. if (FALSE === openssl_pkey_export($this->_res, $out, $passphrase)) {
  75. trigger_error(implode("\n @", OpenSslUtil::getErrors()), E_USER_NOTICE);
  76. throw new XPException('Could not export key');
  77. }
  78. return $out;
  79. }
  80. /**
  81. * Retrieves the private key associated with this keypair
  82. *
  83. * @return security.crypto.PrivateKey
  84. */
  85. public function getPrivateKey() {
  86. return new PrivateKey(openssl_pkey_get_private($this->export(NULL)));
  87. }
  88. }
  89. ?>