示例#1
0
function EncryptedPin($sPin, $sCardNo, $sPubKeyURL)
{
    global $log;
    $sPubKeyURL = trim(SDK_ENCRYPT_CERT_PATH, " ");
    /**
     * [WeEngine System] Copyright (c) 2014 WE7.CC
     * WeEngine is NOT a free software, it under the license terms, visited http://www.we7.cc/ for more details.
     */
    $fp = fopen($sPubKeyURL, "r");
    if ($fp != NULL) {
        $sCrt = fread($fp, 8192);
        fclose($fp);
    }
    $sPubCrt = openssl_x509_read($sCrt);
    if ($sPubCrt === FALSE) {
        print "openssl_x509_read in false!";
        return -1;
    }
    $sPubKey = openssl_x509_parse($sPubCrt);
    $sInput = Pin2PinBlockWithCardNO($sPin, $sCardNo);
    if ($sInput == 1) {
        print "Pin2PinBlockWithCardNO Error ! : " . $sInput;
        return 1;
    }
    $iRet = openssl_public_encrypt($sInput, $sOutData, $sCrt, OPENSSL_PKCS1_PADDING);
    if ($iRet === TRUE) {
        $sBase64EncodeOutData = base64_encode($sOutData);
        return $sBase64EncodeOutData;
    } else {
        print "openssl_public_encrypt Error !";
        return -1;
    }
}
示例#2
0
 public function make_request()
 {
     $g = stream_context_create(array("ssl" => array("capture_peer_cert" => true)));
     set_error_handler(function () {
         return true;
     });
     $r = stream_socket_client("ssl://{$this->target}:{$this->target_port}", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $g);
     restore_error_handler();
     if (!$r) {
         return true;
     } else {
         $cont = stream_context_get_params($r);
         $cert = openssl_x509_read($cont["options"]["ssl"]["peer_certificate"]);
         $cert_data = openssl_x509_parse($cert);
         openssl_x509_export($cert, $out, FALSE);
         $signature_algorithm = null;
         if (preg_match('/^\\s+Signature Algorithm:\\s*(.*)\\s*$/m', $out, $match)) {
             $signature_algorithm = $match[1];
         }
         $this->sha_type = $signature_algorithm;
         $this->common_name = $cert_data['subject']['CN'];
         $this->alternative_names = $cert_data['extensions']['subjectAltName'];
         $this->issuer = $cert_data['issuer']['O'];
         $this->valid_from = date('m-d-Y H:i:s', strval($cert_data['validFrom_time_t']));
         $this->valid_to = date('m-d-Y H:i:s', strval($cert_data['validTo_time_t']));
         $this->parse_alternative_names();
     }
 }
示例#3
0
文件: webid.lib.php 项目: sgml/rww.io
function webid_claim()
{
    $r = array('uri' => array());
    if (isset($_SERVER['SSL_CLIENT_CERT'])) {
        $pem = $_SERVER['SSL_CLIENT_CERT'];
        if ($pem) {
            $x509 = openssl_x509_read($pem);
            $pubKey = openssl_pkey_get_public($x509);
            $keyData = openssl_pkey_get_details($pubKey);
            if (isset($keyData['rsa'])) {
                if (isset($keyData['rsa']['n'])) {
                    $r['m'] = strtolower(array_pop(unpack("H*", $keyData['rsa']['n'])));
                }
                if (isset($keyData['rsa']['e'])) {
                    $r['e'] = hexdec(array_shift(unpack("H*", $keyData['rsa']['e'])));
                }
            }
            $d = openssl_x509_parse($x509);
            if (isset($d['extensions']) && isset($d['extensions']['subjectAltName'])) {
                foreach (explode(', ', $d['extensions']['subjectAltName']) as $elt) {
                    if (substr($elt, 0, 4) == 'URI:') {
                        $r['uri'][] = substr($elt, 4);
                    }
                }
            }
        }
    }
    return $r;
}
示例#4
0
 protected static function getCertIdByCerPath($certPath)
 {
     $x509data = file_get_contents($certPath);
     openssl_x509_read($x509data);
     $certData = openssl_x509_parse($x509data);
     return $certData['serialNumber'];
 }
示例#5
0
 /**
  * 证书Id验证密码方法
  * @param $sPin
  * @param $sCardNo
  * @param array $options 参数数组
  * @return array
  */
 function encryptedPin($sPin, $sCardNo, $options)
 {
     $resArr = ['code' => 1];
     $fp = fopen($options['encrypt_cert_path'], "r");
     if ($fp != NULL) {
         $sCrt = fread($fp, 8192);
         fclose($fp);
         $sPubCrt = openssl_x509_read($sCrt);
         if ($sPubCrt === false) {
             $resArr['code'] = 2;
             $resArr['message'] = '读取密码加密证书数据失败';
         } else {
             $pinBlock = new UnionPayPinBlock();
             $sInput = $pinBlock->Pin2PinBlockWithCardNO($sPin, $sCardNo);
             if ($sInput['code'] > 0) {
                 $resArr['code'] = 3;
                 $resArr['message'] = $sInput['message'];
             } else {
                 $iRet = openssl_public_encrypt($sInput['data'], $sOutData, $sCrt, OPENSSL_PKCS1_PADDING);
                 if ($iRet === true) {
                     $resArr['data'] = base64_encode($sOutData);
                 } else {
                     $resArr['code'] = 3;
                     $resArr['message'] = '加密失败';
                 }
             }
         }
     } else {
         $resArr['code'] = 1;
         $resArr['message'] = '打开密码加密证书失败';
     }
     return $resArr;
 }
示例#6
0
function EncryptedPin($sPin, $sCardNo, $sPubKeyURL)
{
    global $log;
    $sPubKeyURL = trim(SDK_ENCRYPT_CERT_PATH, " ");
    $fp = fopen($sPubKeyURL, "r");
    if ($fp != NULL) {
        $sCrt = fread($fp, 8192);
        fclose($fp);
    }
    $sPubCrt = openssl_x509_read($sCrt);
    if ($sPubCrt === FALSE) {
        print "openssl_x509_read in false!";
        return -1;
    }
    $sPubKey = openssl_x509_parse($sPubCrt);
    $sInput = Pin2PinBlockWithCardNO($sPin, $sCardNo);
    if ($sInput == 1) {
        print "Pin2PinBlockWithCardNO Error ! : " . $sInput;
        return 1;
    }
    $iRet = openssl_public_encrypt($sInput, $sOutData, $sCrt, OPENSSL_PKCS1_PADDING);
    if ($iRet === TRUE) {
        $sBase64EncodeOutData = base64_encode($sOutData);
        return $sBase64EncodeOutData;
    } else {
        print "openssl_public_encrypt Error !";
        return -1;
    }
}
 /**
  * Get the fingerprint from the specified certificate
  *
  * @param string $certificate
  * @return fingerprint or null on failure
  */
 public static function get_fingerprint($certificate, $hash = null)
 {
     $fingerprint = null;
     // The openssl_x509_read() function will throw an warning if the supplied
     // parameter cannot be coerced into an X509 certificate
     // @codingStandardsIgnoreStart
     $resource = @openssl_x509_read($certificate);
     // @codingStandardsIgnoreEnd
     if (false !== $resource) {
         $output = null;
         $result = openssl_x509_export($resource, $output);
         if (false !== $result) {
             $output = str_replace(self::CERTIFICATE_BEGIN, '', $output);
             $output = str_replace(self::CERTIFICATE_END, '', $output);
             // Base64 decode
             $fingerprint = base64_decode($output);
             // Hash
             if (null !== $hash) {
                 $fingerprint = hash($hash, $fingerprint);
             }
         }
         // @todo else what to do?
     }
     // @todo else what to do?
     return $fingerprint;
 }
 public function setup()
 {
     $proxyServer = Phake::mock('EngineBlock_Corto_ProxyServer');
     $log = Phake::mock('Psr\\Log\\LoggerInterface');
     Phake::when($proxyServer)->getSessionLog()->thenReturn($log);
     Phake::when($proxyServer)->getSigningCertificates()->thenReturn(new EngineBlock_X509_KeyPair(new EngineBlock_X509_Certificate(openssl_x509_read(file_get_contents(__DIR__ . '/test.pem.crt'))), new EngineBlock_X509_PrivateKey(__DIR__ . '/test.pem.key')));
     $this->bindings = new EngineBlock_Corto_Module_Bindings($proxyServer);
 }
示例#9
0
function getCertIdByCerPath($cert_path)
{
    $x509data = file_get_contents($cert_path);
    openssl_x509_read($x509data);
    $certdata = openssl_x509_parse($x509data);
    $cert_id = $certdata['serialNumber'];
    return $cert_id;
}
 /**
  * Parse a given string as a X.509 certificate.
  *
  * @param string $x509CertificateContent
  * @return EngineBlock_X509_Certificate
  * @throws EngineBlock_Exception
  */
 public function fromString($x509CertificateContent)
 {
     $opensslCertificate = openssl_x509_read($x509CertificateContent);
     if (!$opensslCertificate) {
         throw new EngineBlock_Exception("Unable to read X.509 certificate from content: '{$x509CertificateContent}'");
     }
     return new EngineBlock_X509_Certificate($opensslCertificate);
 }
示例#11
0
/**
 * 验签 方法 二 (未知公匙,获得需经转换)
 * [rsa_verify2 description]
 * @param  [type] $cert_file [description]
 * @param  [type] $data      [description]
 * @param  [type] $signature [description]
 * @return [type]            [description]
 */
function rsa_verify2($cert_file, $data, $signature)
{
    $cert = der2pem(file_get_contents($cert_file));
    $certs = openssl_x509_read($cert);
    $key = openssl_get_publickey($certs);
    $result = (bool) openssl_verify($data, base64_decode($signature), $key, OPENSSL_ALGO_SHA1);
    openssl_free_key($key);
    return $result;
}
 /**
  * @return bool
  */
 protected function validateSslOptions()
 {
     // Get the contents.
     if (!is_readable($this->certPath)) {
         $this->stdErr->writeln("The certificate file could not be read: " . $this->certPath);
         return false;
     }
     $sslCert = trim(file_get_contents($this->certPath));
     // Do a bit of validation.
     $certResource = openssl_x509_read($sslCert);
     if (!$certResource) {
         $this->stdErr->writeln("The certificate file is not a valid X509 certificate: " . $this->certPath);
         return false;
     }
     // Then the key. Does it match?
     if (!is_readable($this->keyPath)) {
         $this->stdErr->writeln("The private key file could not be read: " . $this->keyPath);
         return false;
     }
     $sslPrivateKey = trim(file_get_contents($this->keyPath));
     $keyResource = openssl_pkey_get_private($sslPrivateKey);
     if (!$keyResource) {
         $this->stdErr->writeln("Private key not valid, or passphrase-protected: " . $this->keyPath);
         return false;
     }
     $keyMatch = openssl_x509_check_private_key($certResource, $keyResource);
     if (!$keyMatch) {
         $this->stdErr->writeln("The provided certificate does not match the provided private key.");
         return false;
     }
     // Each chain needs to contain one or more valid certificates.
     $chainFileContents = $this->readChainFiles($this->chainPaths);
     foreach ($chainFileContents as $filePath => $data) {
         $chainResource = openssl_x509_read($data);
         if (!$chainResource) {
             $this->stdErr->writeln("File contains an invalid X509 certificate: " . $filePath);
             return false;
         }
         openssl_x509_free($chainResource);
     }
     // Split up the chain file contents.
     $chain = [];
     $begin = '-----BEGIN CERTIFICATE-----';
     foreach ($chainFileContents as $data) {
         if (substr_count($data, $begin) > 1) {
             foreach (explode($begin, $data) as $cert) {
                 $chain[] = $begin . $cert;
             }
         } else {
             $chain[] = $data;
         }
     }
     // Yay we win.
     $this->sslOptions = ['certificate' => $sslCert, 'key' => $sslPrivateKey, 'chain' => $chain];
     return true;
 }
示例#13
0
function cert_signature_algorithm($raw_cert_data)
{
    $cert_read = openssl_x509_read($raw_cert_data);
    openssl_x509_export($cert_read, $out, FALSE);
    $signature_algorithm = null;
    if (preg_match('/^\\s+Signature Algorithm:\\s*(.*)\\s*$/m', $out, $match)) {
        $signature_algorithm = $match[1];
    }
    return $signature_algorithm;
}
示例#14
0
 public static function calculateThumbprint($certificate, $hash)
 {
     if (function_exists('openssl_x509_fingerprint')) {
         $cert = openssl_x509_read($certificate);
         return openssl_x509_fingerprint($cert, $hash);
     }
     $cert = preg_replace('#-.*-|\\r|\\n#', '', $certificate);
     $bin = base64_decode($cert);
     return hash($hash, $bin);
 }
 /**
  * Constructs a verifier from the supplied PEM-encoded certificate.
  *
  * $pem: a PEM encoded certificate (not a file).
  * @param $pem
  * @throws Google_AuthException
  * @throws Google_Exception
  */
 function __construct($pem)
 {
     if (!function_exists('openssl_x509_read')) {
         throw new Google_Exception('Google API PHP client needs the openssl PHP extension');
     }
     $this->publicKey = openssl_x509_read($pem);
     if (!$this->publicKey) {
         throw new Google_AuthException("Unable to parse PEM: {$pem}");
     }
 }
示例#16
0
 /**
  * Constructs a verifier from the supplied PEM-encoded certificate.
  *
  * $pem: a PEM encoded certificate (not a file).
  */
 function __construct($pem)
 {
     if (!function_exists('openssl_x509_read')) {
         throw new Exception('The Google PHP API library needs the openssl PHP extension');
     }
     $this->publicKey = openssl_x509_read($pem);
     if (!$this->publicKey) {
         throw new apiAuthException("Unable to parse PEM: {$pem}");
     }
 }
示例#17
0
 private function validateCert($cert)
 {
     $data = openssl_x509_read($cert);
     $certData = openssl_x509_parse($data);
     $certValidDate = gmmktime(0, 0, 0, substr($certData['validTo'], 2, 2), substr($certData['validTo'], 4, 2), substr($certData['validTo'], 0, 2));
     if ($certValidDate < time()) {
         error_log(__METHOD__ . ': Certificate expired in ' . date('Y-m-d', $certValidDate));
         return false;
     }
     return true;
 }
function cert_signature_algorithm($raw_cert_data)
{
    $cert_read = openssl_x509_read($raw_cert_data);
    //if param 3 is FALSE, $out is filled with both the PEM file as wel all the contents of `openssl x509 -noout -text -in cert.pem.
    //we use that to get the signature alg.
    openssl_x509_export($cert_read, $out, FALSE);
    $signature_algorithm = null;
    if (preg_match('/^\\s+Signature Algorithm:\\s*(.*)\\s*$/m', $out, $match)) {
        $signature_algorithm = $match[1];
    }
    return $signature_algorithm;
}
示例#19
0
 /**
  * 验证签名
  * @method verifySign
  * @since 0.0.1
  * @return {boolean}
  * @example $this->verifySign();
  */
 public function verifySign()
 {
     if (empty($_POST) || !isset($_POST['Plain']) || !isset($_POST['Signature'])) {
         return false;
     }
     $cer = file_get_contents(\Yii::getAlias($this->verifyCertPath));
     $_cer = openssl_x509_read($cer);
     $pkey = openssl_get_publickey($_cer);
     $result = openssl_verify($_POST['Plain'], hex2bin($_POST['Signature']), $pkey, OPENSSL_ALGO_MD5);
     openssl_free_key($pkey);
     return $result;
 }
示例#20
0
 /**
  * Sets the PayPal certificate
  *
  * @param mixed $fileName - The path to the PayPal certificate.
  * @return bollean TRUE if the certificate is read successfully, FALSE otherwise.
  */
 public function setPayPalCertificate($fileName)
 {
     if (is_readable($fileName)) {
         $certificate = openssl_x509_read(file_get_contents($fileName));
         if ($certificate !== FALSE) {
             $this->paypalCertificate = $certificate;
             $this->paypalCertificateFile = $fileName;
             return TRUE;
         }
     }
     return FALSE;
 }
示例#21
0
 public function __construct($pem)
 {
     if (!is_string($pem)) {
         throw new \InvalidArgumentException("Invalid variable type: Expected string, got " . gettype($pem));
     }
     if (!($cert = @openssl_x509_read($pem))) {
         throw new InvalidCertificateException("Invalid PEM encoded certificate!");
     }
     $this->pem = $pem;
     if (!($this->info = openssl_x509_parse($cert))) {
         throw new InvalidCertificateException("Invalid PEM encoded certificate!");
     }
 }
示例#22
0
 static function certificado_decodificar($certificado)
 {
     $resource = openssl_x509_read($certificado);
     $output = null;
     $result = openssl_x509_export($resource, $output);
     if ($result !== false) {
         $output = str_replace('-----BEGIN CERTIFICATE-----', '', $output);
         $output = str_replace('-----END CERTIFICATE-----', '', $output);
         return base64_decode($output);
     } else {
         throw new toba_error("El certificado no es un certificado valido", "Detalles: {$certificado}");
     }
 }
示例#23
0
 public function Certificate($path, $cert_password = '')
 {
     $this->path = $path;
     $this->cert_password = $cert_password;
     if (file_exists($this->path) == false) {
         return $this;
     }
     $pkcs12 = file_get_contents($this->path);
     if (openssl_pkcs12_read($pkcs12, $this->certs, $cert_password) == true) {
         $this->cert_data = openssl_x509_read($this->certs['cert']);
         $this->cert_info = openssl_x509_parse($this->cert_data);
     }
 }
示例#24
0
 public function testConsructorSupoprtsMultipleInputTypesAndCanGenerateProperKeyPin()
 {
     $certPath = __DIR__ . '/_files/mxr.mozilla.org.pem';
     $certString = file_get_contents($certPath);
     $certResource = openssl_x509_read($certString);
     $expectedPin = '47cac6d8f2c2363675e6f433970f27523824d0ec';
     $cert = new X509Certificate($certPath);
     $this->assertSame($cert->getPin(), $expectedPin);
     $cert = new X509Certificate($certString);
     $this->assertSame($cert->getPin(), $expectedPin);
     $cert = new X509Certificate($certResource);
     $this->assertSame($cert->getPin(), $expectedPin);
 }
示例#25
0
 public function getBase64()
 {
     $this->checkLoaded();
     $resource = openssl_x509_read($this->cert);
     $output = null;
     $result = openssl_x509_export($resource, $output);
     if ($result !== false) {
         $output = str_replace('-----BEGIN CERTIFICATE-----', '', $output);
         $output = str_replace('-----END CERTIFICATE-----', '', $output);
         return base64_decode($output);
     } else {
         throw new \Exception("El certificado no es un certificado valido", "Detalles: {$this->cert}");
     }
 }
示例#26
0
 /**
  * @param $certificate mixed X.509 resource, X.509 certificate string, or path to X.509 certificate file.
  */
 public function __construct($certificate)
 {
     if (is_string($certificate)) {
         if (is_readable($certificate)) {
             $certificate = file_get_contents($certificate);
         }
         // We're surpressing errors here in favor of the more verbose exception below.
         $certificate = @openssl_x509_read($certificate);
     }
     if (@get_resource_type($certificate) !== 'OpenSSL X.509') {
         throw new \InvalidArgumentException('Argument passed to constructor' . ' of %s must be an X.509 resource, X.509 certificate string, or' . ' valid path to an X.509 certificate.');
     }
     $this->certificate = $certificate;
 }
示例#27
0
 /**
  * @param string $certificate
  *
  * @throws \InvalidArgumentException
  *
  * @return array
  */
 public static function loadKeyFromCertificate($certificate)
 {
     try {
         $res = openssl_x509_read($certificate);
     } catch (\Exception $e) {
         $certificate = self::convertDerToPem($certificate);
         $res = openssl_x509_read($certificate);
     }
     if (false === $res) {
         throw new \InvalidArgumentException('Unable to load the certificate');
     }
     $values = self::loadKeyFromX509Resource($res);
     openssl_x509_free($res);
     return $values;
 }
示例#28
0
 public static function getCertFromFiles($path)
 {
     if (!is_array($path)) {
         $path = array($path);
     }
     $chain = array();
     foreach ($path as $index => $certPath) {
         if (!file_exists($certPath) || !is_readable($certPath)) {
             throw new \RuntimeException('Path to cert is not accessible: ' . $certPath);
         }
         $certFile = file_get_contents($certPath);
         $chain[$index] = openssl_x509_read($certFile);
     }
     $cert = static::getCertFromChain($chain);
     return $cert;
 }
示例#29
0
 public static function getIssuer($cert)
 {
     if ($cert == NULL) {
         return 'http://schemas.xmlsoap.org/ws/2005/05/identity/issuer/self';
     } else {
         $resource = file_get_contents($cert);
         $check_cert = openssl_x509_read($resource);
         $array = openssl_x509_parse($check_cert);
         openssl_x509_free($check_cert);
         $schema = $array['name'];
         $pattern = '/.*CN=/';
         $replacement = '';
         $CN = preg_replace($pattern, $replacement, $schema);
         return $CN;
     }
 }
示例#30
0
 /**
  *  reads in a certificate file and creates a fingerprint
  *  @param Filename of the certificate
  *  @return fingerprint
  */
 function createCertFingerprint($filename)
 {
     if (is_readable($filename)) {
         $cert = file_get_contents($filename);
     } else {
         return false;
     }
     $data = openssl_x509_read($cert);
     if (!openssl_x509_export($data, $data)) {
         return false;
     }
     $data = str_replace("-----BEGIN CERTIFICATE-----", "", $data);
     $data = str_replace("-----END CERTIFICATE-----", "", $data);
     $data = base64_decode($data);
     $fingerprint = sha1($data);
     $fingerprint = strtoupper($fingerprint);
     return $fingerprint;
 }