Example #1
0
function vaildateCert($CAX509, $CheckX509)
{
    $x509 = new File_X509();
    $x509->loadCA($CAX509);
    $cert = $x509->loadX509($CheckX509);
    return $x509->validateSignature();
}
Example #2
0
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));
    }
}
Example #3
0
 /**
  * @return string
  */
 public function getPublicKey()
 {
     $pem = (string) $this->file->getPublicKey();
     $pem = preg_replace('/\\-+BEGIN PUBLIC KEY\\-+/', '', $pem);
     $pem = preg_replace('/\\-+END PUBLIC KEY\\-+/', '', $pem);
     $pem = str_replace(array("\n", "\r", "\t"), '', trim($pem));
     return $pem;
 }
Example #4
0
 public function testBadSignatureSPKAC()
 {
     $test = 'MIICQDCCASgwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQChgo9mWzQm3TSwGgpZnIc54' . 'TZ8gYpfAO/AI0etvyWDqnFfdNCUQsqxTdSi6/rtrJdLGBsszRGrRIc/0JqmjM+jCHGYutLeo4xwgr' . 'a3HAZrWDypL5IlRWnLmLA4U/qGXCXNSk+9NrJl39X3IDA8o/aOJyr9iMUJMvswcWjVjPom3NhAgmJ' . 'ZwW0vUEMw9zszExpiRnGSO5XXntQW2qvfzo+J3NzS3BBbKxEmTsfOLHextcXeFQUaBQHXB/WOtweW' . 'Y/Bd4iZ8ETmhal28g1HWVcTFPD+V+KPRFeARlVEW6JmcJucW2WdJlBGKXXXPEfdHrDS3OgD/eDWfM' . 'JE4mChZ/icxAgMBAAEWADANBgkqhkiG9w0BAQQFAAOCAQEAUMvIKhlSgEgbC081b/FJwh6mbuVgYN' . 'ZV37Ts2WjrHoDFlabu9WXU8xzgaXct3sO51vJM5I36rY4UPyc6w3y9dLaamEwKUoWnpHG8mlXs2JG' . 'GEUOvxh5z9yfk/2ZmdCVBlKnU1LDB+ZDyNyNh5B0YULrJKw9e0jV+ymP7srwUSBcdUfZh1KEKGVIN' . 'Uv4J3GuL8V63E2unWCHGRPw4EmFVTbWpgMx96XR7p/pMavu6/pVKgYQqWLOmEeOK+dmT/QVon28d5' . 'dmeL7aWrpP+3x3L0A9cATksracQX676XogdAEXJ59fcr/S5AGw1TFErbyBbfyeAWvzDZIXeMXpb9h' . 'yNtA==';
     $x509 = new File_X509();
     $spkac = $x509->loadSPKAC($test);
     $spkac['publicKeyAndChallenge']['challenge'] = 'zzzz';
     $x509->loadSPKAC($x509->saveSPKAC($spkac));
     $this->assertFalse($x509->validateSignature(), 'Failed asserting that the signature is invalid');
 }
Example #5
0
 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');
 }
    public function testLoadCSR()
    {
        $test = '-----BEGIN CERTIFICATE REQUEST-----
MIIBWzCBxQIBADAeMRwwGgYDVQQKDBNwaHBzZWNsaWIgZGVtbyBjZXJ0MIGdMAsG
CSqGSIb3DQEBAQOBjQAwgYkCgYEAtHDb4zoUyiRYsJ5PZrF/IJKAF9ZoHRpTxMA8
a7iyFdsl/vvZLNPsNnFTXXnGdvsyFDEsF7AubaIXw8UKFPYqQRTzSVsvnNgIoVYj
tTAXlB4oHipr7Kxcn4CXfmR0TYogyLvVZSZJYxh+CAuG4V9XM4HqkeE5gyBOsKGy
5FUU8zMCAwEAAaAAMA0GCSqGSIb3DQEBBQUAA4GBAJjdaA9K9DN5xvSiOlCmmV1E
npzHkI1Trraveu0gtRjT/EzHoqjCBI0ekCZ9+fhrex8Sm6Nsq9IgHYyrqnE+PQko
4Nf2w2U3DWxU26D5E9DlI+bLyOCq4jqATLjHyyAsOZY/2+U73AZ82MJM/mGdh5fQ
v5RwaQHmQEzHofTzF7I+
-----END CERTIFICATE REQUEST-----';
        $x509 = new File_X509();
        $spkac = $x509->loadCSR($test);
        $this->assertInternalType('array', $spkac);
    }
 public function generateKeyPair($keyPath, $keySize = 1024)
 {
     $privKey = new \Crypt_RSA();
     extract($privKey->createKey($keySize));
     $privKey->loadKey($privatekey);
     $pubKey = new \Crypt_RSA();
     $pubKey->loadKey($publickey);
     $pubKey->setPublicKey();
     $subject = new \File_X509();
     $subject->setDNProp('id-of-organization', 'phpseclib demo cert');
     $subject->setPublicKey($pubKey);
     $issuer = new \File_X509();
     $issuer->setPrivateKey($privKey);
     $issuer->setDN($subject->getDN());
     $x509 = new \File_X509();
     $result = $x509->sign($issuer, $subject);
     file_put_contents($keyPath . '/private.key', $privKey->getPrivateKey());
     file_put_contents($keyPath . '/public.crt', $x509->saveX509($result));
 }
Example #8
0
 /**
  * @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;
 }
Example #9
0
 /**
  * @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);
 }
Example #10
0
// Load the certificate public key.
$pubkey = new Crypt_RSA();
$pubkey->loadKey(file_get_contents('certs/pubkey.pem'));
$pubkey->setPublicKey();
// Build the new certificate.
$iPhoneDeviceCA = new File_X509();
$iPhoneDeviceCA->loadCA($pemca);
$iPhoneDeviceCA->setPublicKey($pubkey);
$iPhoneDeviceCA->setDN('C=US, ST=Some-State, L=Cupertino, O=Apple Inc., OU=Apple iPhone, CN=Apple iPhone Device CA');
$iPhoneDeviceCA->setStartDate('-1 day');
$iPhoneDeviceCA->setEndDate('+ 1 year');
$iPhoneDeviceCA->setSerialNumber('10134611745959375605', 10);
// Sign new certificate.
$iPhoneDeviceCA_Result = $iPhoneDeviceCA->sign($ca, $iPhoneDeviceCA);
// Output it.
echo $iPhoneDeviceCA->saveX509($iPhoneDeviceCA_Result) . "\n";
// subject=/C=US/O=Apple Inc./OU=Apple iPhone/CN=Apple iPhone Device CA
// issuer=/C=US/O=Apple Inc./OU=Apple Certification Authority/CN=Apple iPhone
// Certification Authority
// Build the new certificate.
$iPhoneActivation = new File_X509();
$iPhoneActivation->loadCA($pemca);
$iPhoneActivation->setPublicKey($pubkey);
$iPhoneActivation->setDN('C=US, ST=Some-State, L=Cupertino, O=Apple Inc., OU=Apple iPhone, CN=Apple iPhone Activation');
$iPhoneActivation->setStartDate('-1 day');
$iPhoneActivation->setEndDate('+ 1 year');
$iPhoneActivation->setSerialNumber('2', 10);
// Sign new certificate.
$iPhoneActivation_Result = $iPhoneActivation->sign($ca, $iPhoneActivation);
// Output it.
echo $iPhoneActivation->saveX509($iPhoneActivation_Result) . "\n";
Example #11
0
                    $open = '<pre>';
                    $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 -->
Example #12
0
 /**
  * In this case, we have an app whose $appCertPem appears valid, and we have CRL
  * whose $crlDistCertPem is signed, but the $crlDistCertPem has usage rules
  * which do not allow signing CRLs.
  */
 public function testCRL_SignedByNonDist()
 {
     // create CA
     $caKeyPairPems = KeyPair::create();
     $caCertPem = CA::create($caKeyPairPems, '/O=test');
     $this->assertNotEmpty($caCertPem);
     // create would-be CRL dist authority -- but not really authorized for signing CRLs.
     // note createCSR() instead of createCrlDistCSR().
     $crlDistKeyPairPems = KeyPair::create();
     $crlDistCertPem = CA::signCSR($caKeyPairPems, $caCertPem, CA::createAppCSR($crlDistKeyPairPems, '/O=test'));
     $this->assertNotEmpty($crlDistCertPem);
     $certValidator = new DefaultCertificateValidator($caCertPem, NULL, NULL);
     $certValidator->validateCert($crlDistCertPem);
     // create CRL
     $crlDistCertObj = X509Util::loadCert($crlDistCertPem, $crlDistKeyPairPems, $caCertPem);
     $this->assertNotEmpty($crlDistCertObj);
     $crlObj = new \File_X509();
     $crlObj->setSerialNumber(1, 10);
     $crlObj->setEndDate('+2 days');
     $crlPem = $crlObj->saveCRL($crlObj->signCRL($crlDistCertObj, $crlObj));
     $this->assertNotEmpty($crlPem);
     $crlObj->loadCRL($crlPem);
     // create cert
     $appKeyPair = KeyPair::create();
     $appCertPem = CA::signCSR($caKeyPairPems, $caCertPem, CA::createAppCSR($appKeyPair, '/O=Application Provider'), 4321);
     // validate cert - fails due to improper CRL
     try {
         $certValidator = new DefaultCertificateValidator($caCertPem, $crlDistCertPem, $crlPem);
         $certValidator->validateCert($appCertPem);
         $this->fail('Expected InvalidCertException, but no exception was reported.');
     } catch (InvalidCertException $e) {
         $this->assertRegExp('/CRL-signing certificate is not a CRL-signing certificate/', $e->getMessage());
     }
 }
Example #13
0
 /**
  * Sign an X.509 certificate
  *
  * $issuer's private key needs to be loaded.
  * $subject can be either an existing X.509 cert (if you want to resign it),
  * a CSR or something with the DN and public key explicitly set.
  *
  * @param File_X509 $issuer        	
  * @param File_X509 $subject        	
  * @param String $signatureAlgorithm
  *        	optional
  * @access public
  * @return Mixed
  */
 function sign($issuer, $subject, $signatureAlgorithm = 'sha1WithRSAEncryption')
 {
     if (!is_object($issuer->privateKey) || empty($issuer->dn)) {
         return false;
     }
     if (isset($subject->publicKey) && !($subjectPublicKey = $subject->_formatSubjectPublicKey())) {
         return false;
     }
     $currentCert = isset($this->currentCert) ? $this->currentCert : null;
     $signatureSubject = isset($this->signatureSubject) ? $this->signatureSubject : null;
     if (isset($subject->currentCert) && is_array($subject->currentCert) && isset($subject->currentCert['tbsCertificate'])) {
         $this->currentCert = $subject->currentCert;
         $this->currentCert['tbsCertificate']['signature']['algorithm'] = $signatureAlgorithm;
         $this->currentCert['signatureAlgorithm']['algorithm'] = $signatureAlgorithm;
         if (!empty($this->startDate)) {
             $this->currentCert['tbsCertificate']['validity']['notBefore'] = $this->_timeField($this->startDate);
         }
         if (!empty($this->endDate)) {
             $this->currentCert['tbsCertificate']['validity']['notAfter'] = $this->_timeField($this->endDate);
         }
         if (!empty($this->serialNumber)) {
             $this->currentCert['tbsCertificate']['serialNumber'] = $this->serialNumber;
         }
         if (!empty($subject->dn)) {
             $this->currentCert['tbsCertificate']['subject'] = $subject->dn;
         }
         if (!empty($subject->publicKey)) {
             $this->currentCert['tbsCertificate']['subjectPublicKeyInfo'] = $subjectPublicKey;
         }
         $this->removeExtension('id-ce-authorityKeyIdentifier');
         if (isset($subject->domains)) {
             $this->removeExtension('id-ce-subjectAltName');
         }
     } else {
         if (isset($subject->currentCert) && is_array($subject->currentCert) && isset($subject->currentCert['tbsCertList'])) {
             return false;
         } else {
             if (!isset($subject->publicKey)) {
                 return false;
             }
             $startDate = !empty($this->startDate) ? $this->startDate : @date('D, d M Y H:i:s O');
             $endDate = !empty($this->endDate) ? $this->endDate : @date('D, d M Y H:i:s O', strtotime('+1 year'));
             $serialNumber = !empty($this->serialNumber) ? $this->serialNumber : new Math_BigInteger();
             $this->currentCert = array('tbsCertificate' => array('version' => 'v3', 'serialNumber' => $serialNumber, 'signature' => array('algorithm' => $signatureAlgorithm), 'issuer' => false, 'validity' => array('notBefore' => $this->_timeField($startDate), 'notAfter' => $this->_timeField($endDate)), 'subject' => $subject->dn, 'subjectPublicKeyInfo' => $subjectPublicKey), 'signatureAlgorithm' => array('algorithm' => $signatureAlgorithm), 'signature' => false);
             // Copy extensions from CSR.
             $csrexts = $subject->getAttribute('pkcs-9-at-extensionRequest', 0);
             if (!empty($csrexts)) {
                 $this->currentCert['tbsCertificate']['extensions'] = $csrexts;
             }
         }
     }
     $this->currentCert['tbsCertificate']['issuer'] = $issuer->dn;
     if (isset($issuer->currentKeyIdentifier)) {
         $this->setExtension('id-ce-authorityKeyIdentifier', array('keyIdentifier' => $issuer->currentKeyIdentifier));
         // $extensions =
         // &$this->currentCert['tbsCertificate']['extensions'];
         // if (isset($issuer->serialNumber)) {
         // $extensions[count($extensions) - 1]['authorityCertSerialNumber']
         // = $issuer->serialNumber;
         // }
         // unset($extensions);
     }
     if (isset($subject->currentKeyIdentifier)) {
         $this->setExtension('id-ce-subjectKeyIdentifier', $subject->currentKeyIdentifier);
     }
     $altName = array();
     if (isset($subject->domains) && count($subject->domains) > 1) {
         $altName = array_map(array('File_X509', '_dnsName'), $subject->domains);
     }
     if (isset($subject->ipAddresses) && count($subject->ipAddresses)) {
         // should an IP address appear as the CN if no domain name is
         // specified? idk
         // $ips = count($subject->domains) ? $subject->ipAddresses :
         // array_slice($subject->ipAddresses, 1);
         $ipAddresses = array();
         foreach ($subject->ipAddresses as $ipAddress) {
             $encoded = $subject->_ipAddress($ipAddress);
             if ($encoded !== false) {
                 $ipAddresses[] = $encoded;
             }
         }
         if (count($ipAddresses)) {
             $altName = array_merge($altName, $ipAddresses);
         }
     }
     if (!empty($altName)) {
         $this->setExtension('id-ce-subjectAltName', $altName);
     }
     if ($this->caFlag) {
         $keyUsage = $this->getExtension('id-ce-keyUsage');
         if (!$keyUsage) {
             $keyUsage = array();
         }
         $this->setExtension('id-ce-keyUsage', array_values(array_unique(array_merge($keyUsage, array('cRLSign', 'keyCertSign')))));
         $basicConstraints = $this->getExtension('id-ce-basicConstraints');
         if (!$basicConstraints) {
             $basicConstraints = array();
         }
         $this->setExtension('id-ce-basicConstraints', array_unique(array_merge(array('cA' => true), $basicConstraints)), true);
         if (!isset($subject->currentKeyIdentifier)) {
             $this->setExtension('id-ce-subjectKeyIdentifier', base64_encode($this->computeKeyIdentifier($this->currentCert)), false, false);
         }
     }
     // resync $this->signatureSubject
     // save $tbsCertificate in case there are any File_ASN1_Element objects
     // in it
     $tbsCertificate = $this->currentCert['tbsCertificate'];
     $this->loadX509($this->saveX509($this->currentCert));
     $result = $this->_sign($issuer->privateKey, $signatureAlgorithm);
     $result['tbsCertificate'] = $tbsCertificate;
     $this->currentCert = $currentCert;
     $this->signatureSubject = $signatureSubject;
     return $result;
 }
Example #14
0
$subject->setDNProp('id-at-organizationName', 'phpseclib demo CA');
$subject->setPublicKey($pubKey);
$issuer = new File_X509();
$issuer->setPrivateKey($CAPrivKey);
$issuer->setDN($CASubject = $subject->getDN());
$x509 = new File_X509();
$x509->makeCA();
$result = $x509->sign($issuer, $subject);
echo "the CA cert to be imported into the browser is as follows:\r\n\r\n";
echo $x509->saveX509($result);
echo "\r\n\r\n";
// create private key / x.509 cert for stunnel / website
$privKey = new Crypt_RSA();
extract($privKey->createKey());
$privKey->loadKey($privatekey);
$pubKey = new Crypt_RSA();
$pubKey->loadKey($publickey);
$pubKey->setPublicKey();
$subject = new File_X509();
$subject->setDNProp('id-at-organizationName', 'phpseclib demo cert');
$subject->setPublicKey($pubKey);
$issuer = new File_X509();
$issuer->setPrivateKey($CAPrivKey);
$issuer->setDN($CASubject);
$x509 = new File_X509();
$result = $x509->sign($issuer, $subject);
echo "the stunnel.pem contents are as follows:\r\n\r\n";
echo $privKey->getPrivateKey();
echo "\r\n";
echo $x509->saveX509($result);
echo "\r\n";
Example #15
0
 /**
  * Sign an X.509 certificate
  *
  * $issuer's private key needs to be loaded.
  * $subject can be either an existing X.509 cert (if you want to resign it),
  * a CSR or something with the DN and public key explicitly set.
  *
  * @param File_X509 $issuer
  * @param File_X509 $subject
  * @param string $signatureAlgorithm optional
  * @access public
  * @return mixed
  */
 function sign($issuer, $subject, $signatureAlgorithm = 'sha1WithRSAEncryption')
 {
     if (!is_object($issuer->privateKey) || empty($issuer->dn)) {
         return false;
     }
     if (isset($subject->publicKey) && !($subjectPublicKey = $subject->_formatSubjectPublicKey())) {
         return false;
     }
     $currentCert = isset($this->currentCert) ? $this->currentCert : null;
     $signatureSubject = isset($this->signatureSubject) ? $this->signatureSubject : null;
     if (isset($subject->currentCert) && is_array($subject->currentCert) && isset($subject->currentCert['tbsCertificate'])) {
         $this->currentCert = $subject->currentCert;
         $this->currentCert['tbsCertificate']['signature']['algorithm'] = $signatureAlgorithm;
         $this->currentCert['signatureAlgorithm']['algorithm'] = $signatureAlgorithm;
         if (!empty($this->startDate)) {
             $this->currentCert['tbsCertificate']['validity']['notBefore'] = $this->_timeField($this->startDate);
         }
         if (!empty($this->endDate)) {
             $this->currentCert['tbsCertificate']['validity']['notAfter'] = $this->_timeField($this->endDate);
         }
         if (!empty($this->serialNumber)) {
             $this->currentCert['tbsCertificate']['serialNumber'] = $this->serialNumber;
         }
         if (!empty($subject->dn)) {
             $this->currentCert['tbsCertificate']['subject'] = $subject->dn;
         }
         if (!empty($subject->publicKey)) {
             $this->currentCert['tbsCertificate']['subjectPublicKeyInfo'] = $subjectPublicKey;
         }
         $this->removeExtension('id-ce-authorityKeyIdentifier');
         if (isset($subject->domains)) {
             $this->removeExtension('id-ce-subjectAltName');
         }
     } elseif (isset($subject->currentCert) && is_array($subject->currentCert) && isset($subject->currentCert['tbsCertList'])) {
         return false;
     } else {
         if (!isset($subject->publicKey)) {
             return false;
         }
         $startDate = !empty($this->startDate) ? $this->startDate : @date('D, d M Y H:i:s O');
         $endDate = !empty($this->endDate) ? $this->endDate : @date('D, d M Y H:i:s O', strtotime('+1 year'));
         if (!empty($this->serialNumber)) {
             $serialNumber = $this->serialNumber;
         } else {
             if (!function_exists('crypt_random_string')) {
                 include_once 'Crypt/Random.php';
             }
             /* "The serial number MUST be a positive integer"
                                "Conforming CAs MUST NOT use serialNumber values longer than 20 octets."
                                 -- https://tools.ietf.org/html/rfc5280#section-4.1.2.2
             
                                for the integer to be positive the leading bit needs to be 0 hence the
                                application of a bitmap
                             */
             $serialNumber = new Math_BigInteger(crypt_random_string(20) & "" . str_repeat("ÿ", 19), 256);
         }
         $this->currentCert = array('tbsCertificate' => array('version' => 'v3', 'serialNumber' => $serialNumber, 'signature' => array('algorithm' => $signatureAlgorithm), 'issuer' => false, 'validity' => array('notBefore' => $this->_timeField($startDate), 'notAfter' => $this->_timeField($endDate)), 'subject' => $subject->dn, 'subjectPublicKeyInfo' => $subjectPublicKey), 'signatureAlgorithm' => array('algorithm' => $signatureAlgorithm), 'signature' => false);
         // Copy extensions from CSR.
         $csrexts = $subject->getAttribute('pkcs-9-at-extensionRequest', 0);
         if (!empty($csrexts)) {
             $this->currentCert['tbsCertificate']['extensions'] = $csrexts;
         }
     }
     $this->currentCert['tbsCertificate']['issuer'] = $issuer->dn;
     if (isset($issuer->currentKeyIdentifier)) {
         $this->setExtension('id-ce-authorityKeyIdentifier', array('keyIdentifier' => $issuer->currentKeyIdentifier));
         //$extensions = &$this->currentCert['tbsCertificate']['extensions'];
         //if (isset($issuer->serialNumber)) {
         //    $extensions[count($extensions) - 1]['authorityCertSerialNumber'] = $issuer->serialNumber;
         //}
         //unset($extensions);
     }
     if (isset($subject->currentKeyIdentifier)) {
         $this->setExtension('id-ce-subjectKeyIdentifier', $subject->currentKeyIdentifier);
     }
     $altName = array();
     if (isset($subject->domains) && count($subject->domains) > 1) {
         $altName = array_map(array('File_X509', '_dnsName'), $subject->domains);
     }
     if (isset($subject->ipAddresses) && count($subject->ipAddresses)) {
         // should an IP address appear as the CN if no domain name is specified? idk
         //$ips = count($subject->domains) ? $subject->ipAddresses : array_slice($subject->ipAddresses, 1);
         $ipAddresses = array();
         foreach ($subject->ipAddresses as $ipAddress) {
             $encoded = $subject->_ipAddress($ipAddress);
             if ($encoded !== false) {
                 $ipAddresses[] = $encoded;
             }
         }
         if (count($ipAddresses)) {
             $altName = array_merge($altName, $ipAddresses);
         }
     }
     if (!empty($altName)) {
         $this->setExtension('id-ce-subjectAltName', $altName);
     }
     if ($this->caFlag) {
         $keyUsage = $this->getExtension('id-ce-keyUsage');
         if (!$keyUsage) {
             $keyUsage = array();
         }
         $this->setExtension('id-ce-keyUsage', array_values(array_unique(array_merge($keyUsage, array('cRLSign', 'keyCertSign')))));
         $basicConstraints = $this->getExtension('id-ce-basicConstraints');
         if (!$basicConstraints) {
             $basicConstraints = array();
         }
         $this->setExtension('id-ce-basicConstraints', array_unique(array_merge(array('cA' => true), $basicConstraints)), true);
         if (!isset($subject->currentKeyIdentifier)) {
             $this->setExtension('id-ce-subjectKeyIdentifier', base64_encode($this->computeKeyIdentifier($this->currentCert)), false, false);
         }
     }
     // resync $this->signatureSubject
     // save $tbsCertificate in case there are any File_ASN1_Element objects in it
     $tbsCertificate = $this->currentCert['tbsCertificate'];
     $this->loadX509($this->saveX509($this->currentCert));
     $result = $this->_sign($issuer->privateKey, $signatureAlgorithm);
     $result['tbsCertificate'] = $tbsCertificate;
     $this->currentCert = $currentCert;
     $this->signatureSubject = $signatureSubject;
     return $result;
 }
Example #16
0
 /**
  * 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;
 }
Example #17
0
 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));
 }
Example #18
0
 /**
  * Quasi-private - marked public to work-around PHP 5.3 compat.
  *
  * @param \File_X509 $x509
  * @return \Crypt_RSA
  */
 public static function getRsaFromCert($x509)
 {
     $rsa = $x509->getPublicKey();
     if (!$rsa) {
         throw new InvalidMessageException("Invalid message: certificate missing or does not have public key");
     }
     $rsa->setEncryptionMode(Constants::RSA_ENC_MODE);
     $rsa->setSignatureMode(Constants::RSA_SIG_MODE);
     $rsa->setHash(Constants::RSA_HASH);
     return $rsa;
 }
 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));
 }
$iPhoneActivationOrigPublicKey = $iPhoneActivationOrigVect['key'];
$Message .= "Apple Certificate PRODUCTION : " . "\n" . $iPhoneActivationOrig . "\n";
$Message .= "Apple Certificate PublicKey, Apple Inc. : " . "\n" . $iPhoneActivationOrigPublicKey . "\n";
$iPhoneDeviceCAOrig = file_get_contents($iPhoneDeviceCAOrigFile);
$iPhoneDeviceCAOrigVect = openssl_pkey_get_details(openssl_pkey_get_public($iPhoneDeviceCAOrig));
$iPhoneDeviceCAOrigPublicKey = $iPhoneDeviceCAOrigVect['key'];
$Message .= "Apple Certificate PRODUCTION : " . "\n" . $iPhoneDeviceCAOrig . "\n";
$Message .= "Apple Certificate PublicKey, Apple Inc. : " . "\n" . $iPhoneDeviceCAOrigPublicKey . "\n";
//print $iPhoneDeviceCAOrig;
$DeviceCAOrig = new File_X509();
$DeviceCAOrig->loadX509($iPhoneDeviceCAOrig);
$DeviceCAOrigPublicKey = $DeviceCAOrig->getPublicKey($iPhoneDeviceCAOrig);
$DeviceCAOrigDN = $DeviceCAOrig->getDN(true);
$DeviceCAOrigIssuerDN = $DeviceCAOrig->getIssuerDN(true);
$DeviceCAOrigExtensions = $DeviceCAOrig->getExtensions();
$iPhoneDeviceCANew_x509 = new File_X509();
//$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);
    }
}
 /**
  * Verify that certificate is not revoked
  *
  * @param String $certificate_client String
  * @param String $list_revoked       String
  *
  * @return bool
  */
 static function isRevoked($certificate_client, $list_revoked)
 {
     $certificate = self::getInformationCertificate($certificate_client);
     if (!$certificate) {
         return false;
     }
     $serial = self::getCertificateSerial($certificate_client);
     $x509 = new File_X509();
     $crl = $x509->loadCRL($list_revoked);
     foreach ($crl["tbsCertList"]["revokedCertificates"] as $_cert) {
         if ($_cert["userCertificate"]->value === $serial) {
             return false;
         }
     }
     return true;
 }
 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.");
     }
 }
 /**
  * @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());
 }
 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;
 }
Example #25
0
 /**
  * Sign an X.509 certificate
  *
  * $issuer's private key needs to be loaded.
  * $subject can be either an existing X.509 cert (if you want to resign it),
  * a CSR or something with the DN and public key explicitly set.
  *
  * @param File_X509 $issuer
  * @param File_X509 $subject
  * @param String $signatureAlgorithm optional
  * @access public
  * @return Mixed
  */
 function sign($issuer, $subject, $signatureAlgorithm = 'sha1WithRSAEncryption')
 {
     if (!is_object($issuer->privateKey) || empty($issuer->dn)) {
         return false;
     }
     if (isset($subject->publicKey) && !($subjectPublicKey = $subject->_formatSubjectPublicKey())) {
         return false;
     }
     $currentCert = isset($this->currentCert) ? $this->currentCert : NULL;
     $signatureSubject = isset($this->signatureSubject) ? $this->signatureSubject : NULL;
     if (isset($subject->currentCert) && is_array($subject->currentCert) && isset($subject->currentCert['tbsCertificate'])) {
         $this->currentCert = $subject->currentCert;
         $this->currentCert['tbsCertificate']['signature']['algorithm'] = $this->currentCert['signatureAlgorithm']['algorithm'] = $signatureAlgorithm;
         if (!empty($this->startDate)) {
             $this->currentCert['tbsCertificate']['validity']['notBefore']['generalTime'] = $this->startDate;
             unset($this->currentCert['tbsCertificate']['validity']['notBefore']['utcTime']);
         }
         if (!empty($this->endDate)) {
             $this->currentCert['tbsCertificate']['validity']['notAfter']['generalTime'] = $this->endDate;
             unset($this->currentCert['tbsCertificate']['validity']['notAfter']['utcTime']);
         }
         if (!empty($this->serialNumber)) {
             $this->currentCert['tbsCertificate']['serialNumber'] = $this->serialNumber;
         }
         if (!empty($subject->dn)) {
             $this->currentCert['tbsCertificate']['subject'] = $subject->dn;
         }
         if (!empty($subject->publicKey)) {
             $this->currentCert['tbsCertificate']['subjectPublicKeyInfo'] = $subjectPublicKey;
         }
         $this->removeExtension('id-ce-authorityKeyIdentifier');
         if (isset($subject->domains)) {
             $this->removeExtension('id-ce-subjectAltName');
         }
     } else {
         if (isset($subject->currentCert) && is_array($subject->currentCert) && isset($subject->currentCert['tbsCertList'])) {
             return false;
         } else {
             if (!isset($subject->publicKey)) {
                 return false;
             }
             $startDate = !empty($this->startDate) ? $this->startDate : @date('M j H:i:s Y T');
             $endDate = !empty($this->endDate) ? $this->endDate : @date('M j H:i:s Y T', strtotime('+1 year'));
             $serialNumber = !empty($this->serialNumber) ? $this->serialNumber : new Math_BigInteger();
             $this->currentCert = array('tbsCertificate' => array('version' => 'v3', 'serialNumber' => $serialNumber, 'signature' => array('algorithm' => $signatureAlgorithm), 'issuer' => false, 'validity' => array('notBefore' => array('generalTime' => $startDate), 'notAfter' => array('generalTime' => $endDate)), 'subject' => $subject->dn, 'subjectPublicKeyInfo' => $subjectPublicKey), 'signatureAlgorithm' => array('algorithm' => $signatureAlgorithm), 'signature' => false);
         }
     }
     $this->currentCert['tbsCertificate']['issuer'] = $issuer->dn;
     if (isset($issuer->currentKeyIdentifier)) {
         $this->setExtension('id-ce-authorityKeyIdentifier', array('keyIdentifier' => $issuer->currentKeyIdentifier));
         //$extensions = &$this->currentCert['tbsCertificate']['extensions'];
         //if (isset($issuer->serialNumber)) {
         //    $extensions[count($extensions) - 1]['authorityCertSerialNumber'] = $issuer->serialNumber;
         //}
         //unset($extensions);
     }
     if (isset($subject->currentKeyIdentifier)) {
         $this->setExtension('id-ce-subjectKeyIdentifier', $subject->currentKeyIdentifier);
     }
     if (isset($subject->domains) && count($subject->domains) > 1) {
         $this->setExtension('id-ce-subjectAltName', array_map(array('File_X509', '_dnsName'), $subject->domains));
     }
     if ($this->caFlag) {
         $keyUsage = $this->getExtension('id-ce-keyUsage');
         if (!$keyUsage) {
             $keyUsage = array();
         }
         $this->setExtension('id-ce-keyUsage', array_values(array_unique(array_merge($keyUsage, array('cRLSign', 'keyCertSign')))));
         $basicConstraints = $this->getExtension('id-ce-basicConstraints');
         if (!$basicConstraints) {
             $basicConstraints = array();
         }
         $this->setExtension('id-ce-basicConstraints', array_unique(array_merge(array('cA' => true), $basicConstraints)), true);
         if (!isset($subject->currentKeyIdentifier)) {
             $this->setExtension('id-ce-subjectKeyIdentifier', base64_encode($this->computeKeyIdentifier($this->currentCert)), false, false);
         }
     }
     // resync $this->signatureSubject
     // save $tbsCertificate in case there are any File_ASN1_Element objects in it
     $tbsCertificate = $this->currentCert['tbsCertificate'];
     $this->loadX509($this->saveX509($this->currentCert));
     $result = $this->_sign($issuer->privateKey, $signatureAlgorithm);
     $result['tbsCertificate'] = $tbsCertificate;
     $this->currentCert = $currentCert;
     $this->signatureSubject = $signatureSubject;
     return $result;
 }
 $pemcakey = file_get_contents('certs/iPhoneDeviceCA_private.key');
 $cakey = new Crypt_RSA();
 $cakey->loadKey($pemcakey);
 $pemca = file_get_contents('certs/iPhoneDeviceCA.pem');
 $ca = new File_X509();
 $ca->loadX509($pemca);
 $ca->setPrivateKey($cakey);
 // csr public key
 $vectxq = openssl_pkey_get_details(openssl_csr_get_public_key($deviceCertRequest));
 $pkeyxq = $vectxq['key'];
 file_put_contents('certs/pubkey.pem', $pkeyxq);
 // Load the certificate public key.
 $pubkey = new Crypt_RSA();
 $pubkey->loadKey($pkeyxq);
 $pubkey->setPublicKey();
 $x509 = new File_X509();
 $csr = $x509->loadCSR($deviceCertRequest);
 // see csr.csr
 $dn = $x509->getDN(true);
 // Build the new certificate.
 $iPhoneDeviceCA = new File_X509();
 $iPhoneDeviceCA->loadCA($pemca);
 $iPhoneDeviceCA->setPublicKey($pubkey);
 $iPhoneDeviceCA->setDN($dn);
 $iPhoneDeviceCA->setStartDate('-1 day');
 $iPhoneDeviceCA->setEndDate('+ 1 year');
 $iPhoneDeviceCA->setSerialNumber('10134611745959375605', 10);
 // Sign new certificate.
 $iPhoneDeviceCA_Result = $iPhoneDeviceCA->sign($ca, $iPhoneDeviceCA);
 // Output it.
 $deviceCertificate = base64_encode($iPhoneDeviceCA->saveX509($iPhoneDeviceCA_Result) . "<br>");