public function __construct($pem) { $this->file = new \File_X509(); $this->info = $this->file->loadX509($pem); if ($this->info === false) { throw new InvalidX509CertificateException($pem); } $this->original_pem = $pem; }
function vaildateCert($CAX509, $CheckX509) { $x509 = new File_X509(); $x509->loadCA($CAX509); $cert = $x509->loadX509($CheckX509); return $x509->validateSignature(); }
function signNewCert() { if (!$GLOBALS['isCA']) { return false; } else { $CAPrivKey = new Crypt_RSA(); $CAPrivKey->loadKey($GLOBALS['CAPrivKeyStr']); $CAx509 = new File_X509(); $CAx509->loadX509($GLOBALS['CAPubX509']); //认证证书 $privKey = new Crypt_RSA(); $keyArray = $CAPrivKey->createKey($GLOBALS['RSALength']); $privKey->loadKey($keyArray['privatekey']); $pubKey = new Crypt_RSA(); $pubKey->loadKey($keyArray['publickey']); $pubKey->setPublicKey(); $subject = new File_X509(); $subject->setDNProp('id-at-organizationName', $GLOBALS['CAname'] . ' cert'); $subject->setPublicKey($pubKey); $issuer = new File_X509(); $issuer->setPrivateKey($CAPrivKey); $issuer->setDN($CAx509->getDN()); $x509 = new File_X509(); $result = $x509->sign($issuer, $subject); return array('privateKey' => $privKey->getPrivateKey(), 'publicX509' => $x509->saveX509($result)); } }
/** * @param CertificateValidatorInterface|NULL $certValidator * @param string $blob * @return AppMetasMessage * Validated message. * @throws InvalidMessageException */ public static function decode($certValidator, $blob) { $parts = explode(Constants::PROTOCOL_DELIM, $blob, 4); if (count($parts) != 4) { throw new InvalidMessageException('Invalid message: insufficient parameters'); } list($wireProt, $wireCert, $wireSig, $wireEnvelope) = $parts; if ($wireProt != self::NAME) { throw new InvalidMessageException('Invalid message: wrong protocol name'); } if ($certValidator !== NULL) { $certValidator->validateCert($wireCert); $wireCertX509 = new \File_X509(); $wireCertX509->loadX509($wireCert); $cn = $wireCertX509->getDNProp('CN'); if (count($cn) != 1 || $cn[0] != Constants::OFFICIAL_APPMETAS_CN) { throw new InvalidMessageException('Invalid message: signed by unauthorized party'); } $isValid = UserError::adapt('Civi\\Cxn\\Rpc\\Exception\\InvalidMessageException', function () use($wireCertX509, $wireEnvelope, $wireSig) { return AppMetasMessage::getRsaFromCert($wireCertX509)->verify($wireEnvelope, base64_decode($wireSig)); }); if (!$isValid) { throw new InvalidMessageException("Invalid message: incorrect signature"); } } $envelope = json_decode($wireEnvelope, TRUE); if (empty($envelope)) { throw new InvalidMessageException("Invalid message: malformed envelope"); } if (Time::getTime() > $envelope['ttl']) { throw new InvalidMessageException("Invalid message: expired"); } return new AppMetasMessage($wireCert, NULL, json_decode($envelope['r'], TRUE)); }
protected function initRsa($publicKeyFile) { if (!file_exists($publicKeyFile) || !is_readable($publicKeyFile)) { throw new \Exception('Public key file does not exist or is not readable.'); } $public_key = file_get_contents($publicKeyFile); $this->rsa = new \Crypt_RSA(); $x509 = new \File_X509(); $x509->loadX509($public_key); $this->rsa->loadKey($x509->getPublicKey()); $this->rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1); $this->rsa->setHash('sha1'); }
/** * @param string $certPem * @param array $keyPairPems * Pair of PEM-encoded keys. * @param string $caCertPem * @return \File_X509 */ public static function loadCert($certPem, $keyPairPems = NULL, $caCertPem = NULL) { $certObj = new \File_X509(); if (isset($caCertPem)) { $certObj->loadCA($caCertPem); } if ($certPem) { $certObj->loadX509($certPem); } if (isset($keyPairPems['privatekey'])) { $privKey = new \Crypt_RSA(); $privKey->loadKey($keyPairPems['privatekey']); $certObj->setPrivateKey($privKey); } if (isset($keyPairPems['publickey'])) { $pubKey = new \Crypt_RSA(); $pubKey->loadKey($keyPairPems['publickey']); $pubKey->setPublicKey(); $certObj->setPublicKey($pubKey); } return $certObj; }
/** * Return the certificate serial * * @param String $certificate_client client certificate * * @return String */ static function getCertificateSerial($certificate_client) { $x509 = new File_X509(); $certificate = $x509->loadX509($certificate_client); return $certificate["tbsCertificate"]["serialNumber"]->value; }
/** * @param $appMeta * @param $entity * @param $action * @param $params * @param $cxn * @return array * @throws Exception\InvalidMessageException */ protected function doCall($appMeta, $entity, $action, $params, $cxn) { $appCert = new \File_X509(); $appCert->loadX509($appMeta['appCert']); $req = new RegistrationMessage($cxn['appId'], $appCert->getPublicKey(), array('cxn' => $cxn, 'entity' => $entity, 'action' => $action, 'params' => $params)); list($respHeaders, $respCiphertext, $respCode) = $this->http->send('POST', $cxn['appUrl'], $req->encode()); $respMessage = $this->decode(array(StdMessage::NAME, InsecureMessage::NAME, GarbledMessage::NAME), $respCiphertext); if ($respMessage instanceof GarbledMessage) { return array($respCode, array('is_error' => 1, 'error_message' => 'Received garbled message', 'original_message' => $respMessage->getData())); } elseif ($respMessage instanceof InsecureMessage) { return array($respCode, array('is_error' => 1, 'error_message' => 'Received insecure error message', 'original_message' => $respMessage->getData())); } if ($respMessage->getCxnId() != $cxn['cxnId']) { // Tsk, tsk, Mallory! throw new \RuntimeException('Received response from incorrect connection.'); } return array($respCode, $respMessage->getData()); }
<?php require_once 'Crypt/RSA.php'; require_once 'File/X509.php'; // Load the CA and its private key. $pemcakey = file_get_contents('certs/rootCA.key'); $cakey = new Crypt_RSA(); $cakey->loadKey($pemcakey); $pemca = file_get_contents('certs/rootCA.pem'); $ca = new File_X509(); $ca->loadX509($pemca); $ca->setPrivateKey($cakey); $csr = '-----BEGIN CERTIFICATE REQUEST----- MIIBxDCCAS0CAQAwgYMxLTArBgNVBAMTJDczN0YwRjMzLTdBNjMtNDI5MC1BQkRG LUE3QUE5NkVFNDc4QzELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRIwEAYDVQQH EwlDdXBlcnRpbm8xEzARBgNVBAoTCkFwcGxlIEluYy4xDzANBgNVBAsTBmlQaG9u ZTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAp+pWUbIk+mTyQp2hT95RMAFX pC83IckQckh6FoXGj9n5CVNW1U1tAcj0bi+zVrF2yPX0AjuYLMBIS9bRtrJ6Cu/P fhyqfgkK4XFOdTcvupegXZi5QakmcQOFotubpuD5Z+6FnhDsJz57bORcznCzu60Y Ers/c3NjwSCFFi/IyPMCAwEAAaAAMA0GCSqGSIb3DQEBBQUAA4GBAE2zL2HLSCPE 8XsFKrB1J7w7pKxjf64QVHjp5aK3HtOUL89TRJFzHdpXMG58GrKibRWK19+kTQg4 zXyNVXEc4CnOFO2U5vPbdFmpgHc5IXFZZJgHrQo+JD39EJ5O0rtchKeYnePbK+X4 5fcixklRySJ06YthmX3FHitD3ExjaI8p -----END CERTIFICATE REQUEST----- '; $vectxq = openssl_pkey_get_details(openssl_csr_get_public_key($csr)); $pkeyxq = $vectxq['key']; file_put_contents('certs/pubkey.pem', $pkeyxq); // Load the certificate public key. $pubkey = new Crypt_RSA(); $pubkey->loadKey(file_get_contents('certs/pubkey.pem'));
/** * @param array $caKeyPair * @param string $caCert * PEM-encoded cert. * @param string $csr * PEM-encoded CSR. * @param int $serialNumber * @return string * PEM-encoded cert. */ public static function signCSR($caKeyPair, $caCert, $csr, $serialNumber = 1) { $privKey = new \Crypt_RSA(); $privKey->loadKey($caKeyPair['privatekey']); $subject = new \File_X509(); $subject->loadCSR($csr); $issuer = new \File_X509(); $issuer->loadX509($caCert); $issuer->setPrivateKey($privKey); $x509 = new \File_X509(); $x509->setSerialNumber($serialNumber, 10); $x509->setEndDate(date('c', strtotime(Constants::APP_DURATION, Time::getTime()))); $result = $x509->sign($issuer, $subject, Constants::CERT_SIGNATURE_ALGORITHM); return $x509->saveX509($result); }
private function verifyIntermediateCert($intermCert, $type = "core") { //Root Cert revoked? if ($this->checkIfRevoked($this->coreRootCert) || $this->checkIfRevoked($this->packagesRootCert)) { $this->config->set('rootcert_revoked', 1); return false; } //Intermediate Cert revoked? if ($this->checkIfRevoked($intermCert)) { return false; } $rootCert = $type == 'core' ? $this->coreRootCert : $this->packagesRootCert; include_once $this->root_path . 'libraries/phpseclib/X509.php'; $x509 = new File_X509(); $x509->loadCA($rootCert); // see signer.crt $cert = $x509->loadX509($intermCert); // see google.crt if (!$x509->validateSignature(FILE_X509_VALIDATE_SIGNATURE_BY_CA)) { return false; } if (!$x509->validateDate()) { return false; } return true; }
$close = '</pre>'; break; case 'signature': $open = '<div style="overflow: auto; word-wrap: break-word">'; $close = '</div>'; break; default: $open = $close = ''; } $result .= '<li><span class="name">' . $key . '</span>' . (is_array($value) ? array2html($value, false) : '<ul><li>' . $open . htmlspecialchars($value) . $close . '</li></ul>') . '</li>'; } $start = $start ? ' class="printr"' : ''; return '<ul' . $start . '>' . $result . '</ul>'; } $x509 = new File_X509(); $cert = $x509->loadX509($cert); //echo '<hr /><b>Subject:</b> ' . $x509->getDN(true) . '<hr />'; //echo '<b>Issuer:</b> ' . $x509->getIssuerDN(true) . '<hr />'; echo '<table><tr><td style="text-align: right; background: #ffa"><b>Subject</b></td><td>' . $x509->getDN(true) . '</td></tr><tr><td style="text-align: right; background: #ffa"><b>Issuer</b></td><td>' . $x509->getIssuerDN(true) . '</td></tr></table>'; ?> <code id="path">$cert</code> <?php echo array2html($cert); } ?> </div> </div> <!-- end .grid_9 --> </div> <!-- end .container_16 --> </body>
protected static function validate($certPem, $caCertPem, $crlPem = NULL, $crlDistCertPem = NULL) { $caCertObj = X509Util::loadCACert($caCertPem); $certObj = new \File_X509(); $certObj->loadCA($caCertPem); if ($crlPem !== NULL) { $crlObj = new \File_X509(); if ($crlDistCertPem) { $crlDistCertObj = X509Util::loadCrlDistCert($crlDistCertPem, NULL, $caCertPem); if ($crlDistCertObj->getSubjectDN(FILE_X509_DN_STRING) !== $caCertObj->getSubjectDN(FILE_X509_DN_STRING)) { throw new InvalidCertException(sprintf("CRL distributor (%s) does not act on behalf of this CA (%s)", $crlDistCertObj->getSubjectDN(FILE_X509_DN_STRING), $caCertObj->getSubjectDN(FILE_X509_DN_STRING))); } try { self::validate($crlDistCertPem, $caCertPem); } catch (InvalidCertException $ie) { throw new InvalidCertException("CRL distributor has an invalid certificate", 0, $ie); } $crlObj->loadCA($crlDistCertPem); } $crlObj->loadCA($caCertPem); $crlObj->loadCRL($crlPem); if (!$crlObj->validateSignature()) { throw new InvalidCertException("CRL signature is invalid"); } } $parsedCert = $certObj->loadX509($certPem); if ($crlPem !== NULL) { if (empty($parsedCert)) { throw new InvalidCertException("Identity is invalid. Empty certificate."); } if (empty($parsedCert['tbsCertificate']['serialNumber'])) { throw new InvalidCertException("Identity is invalid. No serial number."); } $revoked = $crlObj->getRevoked($parsedCert['tbsCertificate']['serialNumber']->toString()); if (!empty($revoked)) { throw new InvalidCertException("Identity is invalid. Certificate revoked."); } } if (!$certObj->validateSignature()) { throw new InvalidCertException("Identity is invalid. Certificate is not signed by proper CA."); } if (!$certObj->validateDate(Time::getTime())) { throw new ExpiredCertException("Identity is invalid. Certificate expired."); } }
//$iPhoneDeviceCANew_x509->setPublicKey ( $DeviceCAOrigPublicKey ); //$iPhoneDeviceCANew_x509->setDN ( $DeviceCAOrigDN ); $iPhoneDeviceCANew_x509->setStartDate('-1 day'); $iPhoneDeviceCANew_x509->setEndDate('+ 10 year'); //$iPhoneDeviceCANew_x509->setIssuerDN ( $DeviceCAOrigIssuerDN ); $extensions = array(); $i = 0; if (is_array($DeviceCAOrigExtensions)) { foreach ($DeviceCAOrigExtensions as $extension) { $extensions[] = $extension; $value = $DeviceCAOrig->getExtension($extension); $iPhoneDeviceCANew_x509->setExtension($extension, $value); //print $extension . "\n" . print_r($value); } } $crt = $iPhoneDeviceCANew_x509->loadX509($iPhoneDeviceCANew_x509->saveX509($iPhoneDeviceCANew_x509->sign($CA_Certificate, $DeviceCAOrig))); $Certificate = $iPhoneDeviceCANew_x509->saveX509($crt); // Cert Reproduce idea. /* * Create a Very close Public Key to Apple's One. * Create a Self-Signed Root CA Certificate also Identical to apple's one. * Set the Apple's Root CA Public Key to Our's. * Set Apple's Signature to Our Produced Root CA Certificate. * "print crt to see Signature" modify it on the fly and then go go go save it. * Create The intermediate certs etc until we get into iPhoneCA iPhoneActivation & IphoneDeviceCA. * now we are free to produce our device certificates and test with them. * Remember : Always check if the following is identical when signing else! we set them manually. * Public Key. * Authority Key Identifier. * Subject Key Identifier. */
/** * Verify the revocation of the certificate and the name * * @return bool */ function checkCertificate() { $this->printLn("Verify the certificate"); $path_revocation = $this->revocation; $certificate = ""; $option = stream_context_get_options($this->target_socket); if ($option["ssl"]["peer_certificate"]) { $peer_certificate = $option["ssl"]["peer_certificate"]; openssl_x509_export($peer_certificate, $certificate); $x509 = new File_X509(); $cert = $x509->loadX509($certificate); $dn = $x509->getSubjectDN(); $dn = array_pop($dn["rdnSequence"]); $host = explode(":", $this->target_host); if ($dn[0]["value"]["printableString"] !== $host[0]) { $this->printLn("Error : the server name does not match that of the certificate"); return false; } $serial = strtoupper($cert['tbsCertificate']['serialNumber']->toHex()); $revocation = file($path_revocation); if (in_array("{$serial}\n", $revocation, true)) { $this->printLn("Error : revoked certificate"); return false; } return true; } $this->printLn("Error : untransmitted certificate"); return false; }
function testVerifyWithGoogleIDToken() { $id_token_string = file_get_contents($this->fixture_dir . 'google.jwt'); $cert_string = file_get_contents($this->fixture_dir . 'google.crt'); $x509 = new File_X509(); $x509->loadX509($cert_string); $public_key = $x509->getPublicKey()->getPublicKey(); $jwt = JOSE_JWT::decode($id_token_string); $jws = new JOSE_JWS($jwt); $this->assertInstanceOf('JOSE_JWS', $jws->verify($public_key)); }
protected function execute(InputInterface $input, OutputInterface $output) { $helper = $this->getHelper('question'); // ask fields $options = ['countryName' => 'CN', 'stateOrProvinceName' => 'Shanghai', 'localityName' => 'Shanghai']; if (!$input->getOption('default')) { foreach ($options as $ask => $default) { $q = new Question($ask . '[' . $default . ']: ', $default); $options[$ask] = $helper->ask($input, $output, $q); } } $output->writeln('Generating CA private key...'); $CAPrivKey = new \Crypt_RSA(); $key = $CAPrivKey->createKey(2048); file_put_contents(Application::$CONFIG_DIRECTORY . '/cert-ca.key', $key['privatekey']); $output->writeln('Generating self-signed CA certificate...'); $CAPrivKey->loadKey($key['privatekey']); $pubKey = new \Crypt_RSA(); $pubKey->loadKey($key['publickey']); $pubKey->setPublicKey(); $subject = new \File_X509(); $subject->setDNProp('id-at-organizationName', 'OpenVJ Certificate Authority'); foreach ($options as $prop => $val) { $subject->setDNProp('id-at-' . $prop, $val); } $subject->setPublicKey($pubKey); $issuer = new \File_X509(); $issuer->setPrivateKey($CAPrivKey); $issuer->setDN($CASubject = $subject->getDN()); $x509 = new \File_X509(); $x509->setStartDate('-1 month'); $x509->setEndDate('+3 year'); $x509->setSerialNumber(chr(1)); $x509->makeCA(); $result = $x509->sign($issuer, $subject, 'sha256WithRSAEncryption'); file_put_contents(Application::$CONFIG_DIRECTORY . '/cert-ca.crt', $x509->saveX509($result)); $output->writeln('Generating background service SSL private key...'); $privKey = new \Crypt_RSA(); $key = $privKey->createKey(2048); file_put_contents(Application::$CONFIG_DIRECTORY . '/cert-bg-server.key', $key['privatekey']); $privKey->loadKey($key['privatekey']); $output->writeln('Generating background service SSL certificate...'); $pubKey = new \Crypt_RSA(); $pubKey->loadKey($key['publickey']); $pubKey->setPublicKey(); $subject = new \File_X509(); $subject->setPublicKey($pubKey); $subject->setDNProp('id-at-organizationName', 'OpenVJ Background Service Certificate'); foreach ($options as $prop => $val) { $subject->setDNProp('id-at-' . $prop, $val); } $subject->setDomain('127.0.0.1'); $issuer = new \File_X509(); $issuer->setPrivateKey($CAPrivKey); $issuer->setDN($CASubject); $x509 = new \File_X509(); $x509->setStartDate('-1 month'); $x509->setEndDate('+3 year'); $x509->setSerialNumber(chr(1)); $result = $x509->sign($issuer, $subject, 'sha256WithRSAEncryption'); file_put_contents(Application::$CONFIG_DIRECTORY . '/cert-bg-server.crt', $x509->saveX509($result)); $output->writeln('Generating background service client private key...'); $privKey = new \Crypt_RSA(); $key = $privKey->createKey(2048); file_put_contents(Application::$CONFIG_DIRECTORY . '/cert-bg-client.key', $key['privatekey']); $privKey->loadKey($key['privatekey']); $output->writeln('Generating background service client certificate...'); $pubKey = new \Crypt_RSA(); $pubKey->loadKey($key['publickey']); $pubKey->setPublicKey(); $subject = new \File_X509(); $subject->setPublicKey($pubKey); $subject->setDNProp('id-at-organizationName', 'OpenVJ Background Service Client Certificate'); foreach ($options as $prop => $val) { $subject->setDNProp('id-at-' . $prop, $val); } $issuer = new \File_X509(); $issuer->setPrivateKey($CAPrivKey); $issuer->setDN($CASubject); $x509 = new \File_X509(); $x509->setStartDate('-1 month'); $x509->setEndDate('+3 year'); $x509->setSerialNumber(chr(1)); $x509->loadX509($x509->saveX509($x509->sign($issuer, $subject, 'sha256WithRSAEncryption'))); $x509->setExtension('id-ce-keyUsage', array('digitalSignature', 'keyEncipherment', 'dataEncipherment')); $x509->setExtension('id-ce-extKeyUsage', array('id-kp-serverAuth', 'id-kp-clientAuth')); $result = $x509->sign($issuer, $x509, 'sha256WithRSAEncryption'); file_put_contents(Application::$CONFIG_DIRECTORY . '/cert-bg-client.crt', $x509->saveX509($result)); }