Ejemplo n.º 1
0
Archivo: JWS.php Proyecto: gree/jose
 private function rsa($public_or_private_key, $padding_mode)
 {
     if ($public_or_private_key instanceof JOSE_JWK) {
         $rsa = $public_or_private_key->toKey();
     } else {
         if ($public_or_private_key instanceof RSA) {
             $rsa = $public_or_private_key;
         } else {
             $rsa = new RSA();
             $rsa->loadKey($public_or_private_key);
         }
     }
     $rsa->setHash($this->digest());
     $rsa->setMGFHash($this->digest());
     $rsa->setSignatureMode($padding_mode);
     return $rsa;
 }
Ejemplo n.º 2
0
 private function rsa($public_or_private_key, $padding_mode)
 {
     if ($public_or_private_key instanceof JOSE_JWK) {
         $rsa = $public_or_private_key->toKey();
     } else {
         if ($public_or_private_key instanceof RSA) {
             $rsa = $public_or_private_key;
         } else {
             $rsa = new RSA();
             $rsa->loadKey($public_or_private_key);
         }
     }
     $rsa->setHash($this->digest());
     $rsa->setMGFHash($this->digest());
     $rsa->setSaltLength(false);
     # NOTE: https://github.com/phpseclib/phpseclib/issues/768
     $rsa->setSignatureMode($padding_mode);
     return $rsa;
 }
Ejemplo n.º 3
0
 /**
  * Verifies the signature for the specified path.
  *
  * @param string $signaturePath
  * @param string $basePath
  * @param string $certificateCN
  * @return array
  * @throws InvalidSignatureException
  * @throws \Exception
  */
 private function verify($signaturePath, $basePath, $certificateCN)
 {
     if (!$this->isCodeCheckEnforced()) {
         return [];
     }
     $signatureData = json_decode($this->fileAccessHelper->file_get_contents($signaturePath), true);
     if (!is_array($signatureData)) {
         throw new InvalidSignatureException('Signature data not found.');
     }
     $expectedHashes = $signatureData['hashes'];
     ksort($expectedHashes);
     $signature = base64_decode($signatureData['signature']);
     $certificate = $signatureData['certificate'];
     // Check if certificate is signed by ownCloud Root Authority
     $x509 = new \phpseclib\File\X509();
     $rootCertificatePublicKey = $this->fileAccessHelper->file_get_contents($this->environmentHelper->getServerRoot() . '/resources/codesigning/root.crt');
     $x509->loadCA($rootCertificatePublicKey);
     $x509->loadX509($certificate);
     if (!$x509->validateSignature()) {
         throw new InvalidSignatureException('Certificate is not valid.');
     }
     // Verify if certificate has proper CN. "core" CN is always trusted.
     if ($x509->getDN(X509::DN_OPENSSL)['CN'] !== $certificateCN && $x509->getDN(X509::DN_OPENSSL)['CN'] !== 'core') {
         throw new InvalidSignatureException(sprintf('Certificate is not valid for required scope. (Requested: %s, current: %s)', $certificateCN, $x509->getDN(true)));
     }
     // Check if the signature of the files is valid
     $rsa = new \phpseclib\Crypt\RSA();
     $rsa->loadKey($x509->currentCert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey']);
     $rsa->setSignatureMode(RSA::SIGNATURE_PSS);
     $rsa->setMGFHash('sha512');
     if (!$rsa->verify(json_encode($expectedHashes), $signature)) {
         throw new InvalidSignatureException('Signature could not get verified.');
     }
     // Compare the list of files which are not identical
     $currentInstanceHashes = $this->generateHashes($this->getFolderIterator($basePath), $basePath);
     $differencesA = array_diff($expectedHashes, $currentInstanceHashes);
     $differencesB = array_diff($currentInstanceHashes, $expectedHashes);
     $differences = array_unique(array_merge($differencesA, $differencesB));
     $differenceArray = [];
     foreach ($differences as $filename => $hash) {
         // Check if file should not exist in the new signature table
         if (!array_key_exists($filename, $expectedHashes)) {
             $differenceArray['EXTRA_FILE'][$filename]['expected'] = '';
             $differenceArray['EXTRA_FILE'][$filename]['current'] = $hash;
             continue;
         }
         // Check if file is missing
         if (!array_key_exists($filename, $currentInstanceHashes)) {
             $differenceArray['FILE_MISSING'][$filename]['expected'] = $expectedHashes[$filename];
             $differenceArray['FILE_MISSING'][$filename]['current'] = '';
             continue;
         }
         // Check if hash does mismatch
         if ($expectedHashes[$filename] !== $currentInstanceHashes[$filename]) {
             $differenceArray['INVALID_HASH'][$filename]['expected'] = $expectedHashes[$filename];
             $differenceArray['INVALID_HASH'][$filename]['current'] = $currentInstanceHashes[$filename];
             continue;
         }
         // Should never happen.
         throw new \Exception('Invalid behaviour in file hash comparison experienced. Please report this error to the developers.');
     }
     return $differenceArray;
 }
Ejemplo n.º 4
0
 /**
  * Creates the signature data
  *
  * @param array $hashes
  * @param X509 $certificate
  * @param RSA $privateKey
  * @return string
  */
 private function createSignatureData(array $hashes, X509 $certificate, RSA $privateKey)
 {
     ksort($hashes);
     $privateKey->setSignatureMode(RSA::SIGNATURE_PSS);
     $privateKey->setMGFHash('sha512');
     $signature = $privateKey->sign(json_encode($hashes));
     return ['hashes' => $hashes, 'signature' => base64_encode($signature), 'certificate' => $certificate->saveX509($certificate->currentCert)];
 }
Ejemplo n.º 5
0
 /**
  * Verify with RSASS-PSS + MGF1+SHA256
  * 
  * @param string $message
  * @param string $signature
  * @param PublicKey $rsaPublicKey
  * @return bool
  */
 public static function verify($message, $signature, PublicKey $rsaPublicKey)
 {
     static $rsa = null;
     if (!$rsa) {
         $rsa = new RSA();
         $rsa->setSignatureMode(RSA::SIGNATURE_PSS);
         $rsa->setMGFHash('sha256');
     }
     $rsa->loadKey($rsaPublicKey->getKey());
     return $rsa->verify($message, $signature);
 }
Ejemplo n.º 6
0
    /**
     * Validates a signature
     *
     * Returns true if the signature is verified, false if it is not correct or null on error
     *
     * @param string $publicKeyAlgorithm
     * @param string $publicKey
     * @param string $signatureAlgorithm
     * @param string $signature
     * @param string $signatureSubject
     * @access private
     * @return int
     */
    function _validateSignature($publicKeyAlgorithm, $publicKey, $signatureAlgorithm, $signature, $signatureSubject)
    {
        switch ($publicKeyAlgorithm) {
            case 'rsaEncryption':
                $rsa = new RSA();
                $rsa->loadKey($publicKey);

                switch ($signatureAlgorithm) {
                    case 'md2WithRSAEncryption':
                    case 'md5WithRSAEncryption':
                    case 'sha1WithRSAEncryption':
                    case 'sha224WithRSAEncryption':
                    case 'sha256WithRSAEncryption':
                    case 'sha384WithRSAEncryption':
                    case 'sha512WithRSAEncryption':
                        $rsa->setHash(preg_replace('#WithRSAEncryption$#', '', $signatureAlgorithm));
                        $rsa->setSignatureMode(RSA::SIGNATURE_PKCS1);
                        if (!@$rsa->verify($signatureSubject, $signature)) {
                            return false;
                        }
                        break;
                    default:
                        return null;
                }
                break;
            default:
                return null;
        }

        return true;
    }
Ejemplo n.º 7
0
 static function crypt_rsa_key($mod, $exp, $hash = 'SHA256')
 {
     $rsa = new Crypt_RSA();
     $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
     $rsa->setHash(strtolower($hash));
     $rsa->modulus = new Math_BigInteger($mod, 256);
     $rsa->k = strlen($rsa->modulus->toBytes());
     $rsa->exponent = new Math_BigInteger($exp, 256);
     $rsa->setPublicKey();
     return $rsa;
 }
 /**
  * Static method for quick calls to calculate a signature.
  * @link https://developer.walmartapis.com/#authentication
  * @param string $consumerId
  * @param string $privateKey
  * @param string $requestUrl
  * @param string $requestMethod
  * @param string|null $timestamp
  * @return string
  * @throws \Exception
  */
 public static function calculateSignature($consumerId, $privateKey, $requestUrl, $requestMethod, $timestamp = null)
 {
     if (is_null($timestamp) || !is_numeric($timestamp)) {
         $timestamp = self::getMilliseconds();
     }
     /**
      * Append values into string for signing
      */
     $message = $consumerId . "\n" . $requestUrl . "\n" . strtoupper($requestMethod) . "\n" . $timestamp . "\n";
     /**
      * Get RSA object for signing
      */
     $rsa = new RSA();
     $decodedPrivateKey = base64_decode($privateKey);
     $rsa->setPrivateKeyFormat(RSA::PRIVATE_FORMAT_PKCS8);
     $rsa->setPublicKeyFormat(RSA::PRIVATE_FORMAT_PKCS8);
     /**
      * Load private key
      */
     if ($rsa->loadKey($decodedPrivateKey, RSA::PRIVATE_FORMAT_PKCS8)) {
         /**
          * Make sure we use SHA256 for signing
          */
         $rsa->setHash('sha256');
         $rsa->setSignatureMode(RSA::SIGNATURE_PKCS1);
         $signed = $rsa->sign($message);
         /**
          * Return Base64 Encode generated signature
          */
         return base64_encode($signed);
     } else {
         throw new \Exception("Unable to load private key", 1446780146);
     }
 }