Process PKCS7 signature with certificate in it.
        :param data:
        :param name:
        :return:
775117
def process_pkcs7(self, data, name):
        
        from cryptography.hazmat.backends.openssl.backend import backend
        from cryptography.hazmat.backends.openssl.x509 import _Certificate

        # DER conversion
        is_pem = startswith(data, '-----')
        if self.re_match(r'^[a-zA-Z0-9-\s+=/]+$', data):
            is_pem = True

        try:
            der = data
            if is_pem:
                data = data.decode('utf8')
                data = re.sub(r'\s*-----\s*BEGIN\s+PKCS7\s*-----', '', data)
                data = re.sub(r'\s*-----\s*END\s+PKCS7\s*-----', '', data)
                der = base64.b64decode(data)

            bio = backend._bytes_to_bio(der)
            pkcs7 = backend._lib.d2i_PKCS7_bio(bio.bio, backend._ffi.NULL)
            backend.openssl_assert(pkcs7 != backend._ffi.NULL)
            signers = backend._lib.PKCS7_get0_signers(pkcs7, backend._ffi.NULL, 0)
            backend.openssl_assert(signers != backend._ffi.NULL)
            backend.openssl_assert(backend._lib.sk_X509_num(signers) > 0)
            x509_ptr = backend._lib.sk_X509_value(signers, 0)
            backend.openssl_assert(x509_ptr != backend._ffi.NULL)
            x509_ptr = backend._ffi.gc(x509_ptr, backend._lib.X509_free)
            x509 = _Certificate(backend, x509_ptr)

            self.num_pkcs7_cert += 1

            return [self.process_x509(x509, name=name, pem=False, source='pkcs7-cert', aux='')]

        except Exception as e:
            logger.debug('Error in PKCS7 processing %s: %s' % (name, e))
            self.trace_logger.log(e)
185305
def process_ssh(self, data, name):
        
        if data is None or len(data) == 0:
            return

        ret = []
        try:
            lines = [x.strip() for x in data.split(b'\n')]
            for idx, line in enumerate(lines):
                ret.append(self.process_ssh_line(line, name, idx))

        except Exception as e:
            logger.debug('Exception in processing SSH public key %s : %s' % (name, e))
            self.trace_logger.log(e)
        return ret
1070301
def sign(data, low_r = true, extra_entropy = nil)
      sig = secp256k1_module.sign_data(data, priv_key, extra_entropy)
      if low_r && !sig_has_low_r?(sig)
        counter = 1
        until sig_has_low_r?(sig)
          extra_entropy = [counter].pack('I*').bth.ljust(64, '0').htb
          sig = secp256k1_module.sign_data(data, priv_key, extra_entropy)
          counter += 1
        end
      end
      sig
    end
143552
def _pkcs1imify(self, data):
        
        SHA1_DIGESTINFO = '\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14'
        size = len(util.deflate_long(self.n, 0))
        filler = '\xff' * (size - len(SHA1_DIGESTINFO) - len(data) - 3)
        return '\x00\x01' + filler + '\x00' + SHA1_DIGESTINFO + data
1241570
def sign(self, data):
        
        if self.signing_key is None:
            raise MissingSigningKeyError("KeyPair does not contain secret key. "
                                         "Use Keypair.from_seed method to create a new keypair with a secret key.")
        return self.signing_key.sign(data)
668744
def _sign(self, data: bytes) -> bytes:
        
        assert self._raiden_service is not None
        return self._raiden_service.signer.sign(data=data)
966355
def _compute_signature(parameters, access_key_secret):
    '''
    
    '''

    def percent_encode(line):
        if not isinstance(line, six.string_types):
            return line

        s = line
        if sys.stdin.encoding is None:
            s = line.decode().encode('utf8')
        else:
            s = line.decode(sys.stdin.encoding).encode('utf8')
        res = _quote(s, '')
        res = res.replace('+', '%20')
        res = res.replace('*', '%2A')
        res = res.replace('%7E', '~')
        return res

    sortedParameters = sorted(list(parameters.items()), key=lambda items: items[0])

    canonicalizedQueryString = ''
    for k, v in sortedParameters:
        canonicalizedQueryString += '&' + percent_encode(k) \
            + '=' + percent_encode(v)

    # All aliyun API only support GET method
    stringToSign = 'GET&%2F&' + percent_encode(canonicalizedQueryString[1:])

    h = hmac.new(to_bytes(access_key_secret + "&"), stringToSign, sha1)
    signature = base64.encodestring(h.digest()).strip()
    return signature
658652
def hashdata(self, subject):
        _data = bytearray()

        if isinstance(subject, six.string_types):
            subject = subject.encode('charmap')

        

        if self.type == SignatureType.BinaryDocument:
            """
            For binary document signatures (type 0x00), the document data is
            hashed directly.
            """
            if isinstance(subject, (SKEData, IntegrityProtectedSKEData)):
                _data += subject.__bytearray__()
            else:
                _data += bytearray(subject)

        if self.type == SignatureType.CanonicalDocument:
            """
            For text document signatures (type 0x01), the
            document is canonicalized by converting line endings to <CR><LF>,
            and the resulting data is hashed.
            """
            _data += re.subn(br'\r?\n', b'\r\n', subject)[0]

        if self.type in {SignatureType.Generic_Cert, SignatureType.Persona_Cert, SignatureType.Casual_Cert,
                         SignatureType.Positive_Cert, SignatureType.CertRevocation, SignatureType.Subkey_Binding,
                         SignatureType.PrimaryKey_Binding}:
            """
            When a signature is made over a key, the hash data starts with the
            octet 0x99, followed by a two-octet length of the key, and then body
            of the key packet.  (Note that this is an old-style packet header for
            a key packet with two-octet length.) ...
            Key revocation signatures (types 0x20 and 0x28)
            hash only the key being revoked.
            """
            _s = b''
            if isinstance(subject, PGPUID):
                _s = subject._parent.hashdata

            elif isinstance(subject, PGPKey) and not subject.is_primary:
                _s = subject._parent.hashdata

            elif isinstance(subject, PGPKey) and subject.is_primary:
                _s = subject.hashdata

            if len(_s) > 0:
                _data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s

        if self.type in {SignatureType.Subkey_Binding, SignatureType.PrimaryKey_Binding}:
            """
            A subkey binding signature
            (type 0x18) or primary key binding signature (type 0x19) then hashes
            the subkey using the same format as the main key (also using 0x99 as
            the first octet).
            """
            if subject.is_primary:
                _s = subject.subkeys[self.signer].hashdata

            else:
                _s = subject.hashdata

            _data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s

        if self.type in {SignatureType.KeyRevocation, SignatureType.SubkeyRevocation, SignatureType.DirectlyOnKey}:
            """
            The signature is calculated directly on the key being revoked.  A
            revoked key is not to be used.  Only revocation signatures by the
            key being revoked, or by an authorized revocation key, should be
            considered valid revocation signatures.

            Subkey revocation signature
            The signature is calculated directly on the subkey being revoked.
            A revoked subkey is not to be used.  Only revocation signatures
            by the top-level signature key that is bound to this subkey, or
            by an authorized revocation key, should be considered valid
            revocation signatures.
            
            - clarification from draft-ietf-openpgp-rfc4880bis-02:
            Primary key revocation signatures (type 0x20) hash
            only the key being revoked.  Subkey revocation signature (type 0x28)
            hash first the primary key and then the subkey being revoked

            Signature directly on a key
            This signature is calculated directly on a key.  It binds the
            information in the Signature subpackets to the key, and is
            appropriate to be used for subpackets that provide information
            about the key, such as the Revocation Key subpacket.  It is also
            appropriate for statements that non-self certifiers want to make
            about the key itself, rather than the binding between a key and a
            name.
            """
            if self.type == SignatureType.SubkeyRevocation:
                # hash the primary key first if this is a Subkey Revocation signature
                _s = subject.parent.hashdata
                _data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s

            _s = subject.hashdata
            _data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s

        if self.type in {SignatureType.Generic_Cert, SignatureType.Persona_Cert, SignatureType.Casual_Cert,
                         SignatureType.Positive_Cert, SignatureType.CertRevocation}:
            """
            A certification signature (type 0x10 through 0x13) hashes the User
            ID being bound to the key into the hash context after the above
            data.  ...  A V4 certification
            hashes the constant 0xB4 for User ID certifications or the constant
            0xD1 for User Attribute certifications, followed by a four-octet
            number giving the length of the User ID or User Attribute data, and
            then the User ID or User Attribute data.

            ...

            The [certificate revocation] signature
            is computed over the same data as the certificate that it
            revokes, and should have a later creation date than that
            certificate.
            """

            _s = subject.hashdata
            if subject.is_uid:
                _data += b'\xb4'

            else:
                _data += b'\xd1'

            _data += self.int_to_bytes(len(_s), 4) + _s

        # if this is a new signature, do update_hlen
        if 0 in list(self._signature.signature):
            self._signature.update_hlen()

        """
        Once the data body is hashed, then a trailer is hashed. (...)
        A V4 signature hashes the packet body
        starting from its first field, the version number, through the end
        of the hashed subpacket data.  Thus, the fields hashed are the
        signature version, the signature type, the public-key algorithm, the
        hash algorithm, the hashed subpacket length, and the hashed
        subpacket body.

        V4 signatures also hash in a final trailer of six octets: the
        version of the Signature packet, i.e., 0x04; 0xFF; and a four-octet,
        big-endian number that is the length of the hashed data from the
        Signature packet (note that this number does not include these final
        six octets).
        """

        hcontext = bytearray()
        hcontext.append(self._signature.header.version if not self.embedded else self._signature._sig.header.version)
        hcontext.append(self.type)
        hcontext.append(self.key_algorithm)
        hcontext.append(self.hash_algorithm)
        hcontext += self._signature.subpackets.__hashbytearray__()
        hlen = len(hcontext)
        _data += hcontext
        _data += b'\x04\xff'
        _data += self.int_to_bytes(hlen, 4)
        return bytes(_data)
131887
def process_pem_csr(self, data, name, idx):
        
        from cryptography.x509.base import load_der_x509_csr
        try:
            csr = load_der_x509_csr(pem_to_der(data), self.get_backend())
            self.num_pem_csr += 1
            return self.process_csr(csr, name=name, idx=idx, data=data, pem=True, source='pem-csr')

        except Exception as e:
            logger.debug('PEM processing failed: %s' % e)
            self.trace_logger.log(e)
1210527
public boolean verify(byte[] data, byte[] sign) {
		lock.lock();
		try {
			signature.initVerify(this.publicKey);
			signature.update(data);
			return signature.verify(sign);
		} catch (Exception e) {
			throw new CryptoException(e);
		} finally {
			lock.unlock();
		}
	}
520074
def load_pkcs12(self, key):
        
        self.x509 = key.get_certificate().to_cryptography()
        self.public_key = key.get_certificate().to_cryptography().public_key()
        self.private_key = key.get_privatekey().to_cryptography_key()
332281
private String certificationRequestToPEM(PKCS10CertificationRequest csr) throws IOException {
        PemObject pemCSR = new PemObject("CERTIFICATE REQUEST", csr.getEncoded());

        StringWriter str = new StringWriter();
        JcaPEMWriter pemWriter = new JcaPEMWriter(str);
        pemWriter.writeObject(pemCSR);
        pemWriter.close();
        str.close();
        return str.toString();
    }
370505
def verifyCert(self, cert):
        
        tbsCert = cert.tbsCertificate
        sigAlg = tbsCert.signature
        h = hash_by_oid[sigAlg.algorithm.val]
        sigVal = raw(cert.signatureValue)
        return self.verify(raw(tbsCert), sigVal, h=h, t='pkcs')
230005
SignerInfo verify(PKCS7 block, InputStream inputStream)
    throws NoSuchAlgorithmException, SignatureException, IOException {

       try {

            ContentInfo content = block.getContentInfo();
            if (inputStream == null) {
                inputStream = new ByteArrayInputStream(content.getContentBytes());
            }

            String digestAlgname = getDigestAlgorithmId().getName();

            InputStream dataSigned;

            // if there are authenticate attributes, get the message
            // digest and compare it with the digest of data
            if (authenticatedAttributes == null) {
                dataSigned = inputStream;
            } else {

                // first, check content type
                ObjectIdentifier contentType = (ObjectIdentifier)
                       authenticatedAttributes.getAttributeValue(
                         PKCS9Attribute.CONTENT_TYPE_OID);
                if (contentType == null ||
                    !contentType.equals(content.contentType))
                    return null;  // contentType does not match, bad SignerInfo

                // now, check message digest
                byte[] messageDigest = (byte[])
                    authenticatedAttributes.getAttributeValue(
                         PKCS9Attribute.MESSAGE_DIGEST_OID);

                if (messageDigest == null) // fail if there is no message digest
                    return null;

                MessageDigest md = MessageDigest.getInstance(
                        convertToStandardName(digestAlgname));

                byte[] buffer = new byte[4096];
                int read = 0;
                while ((read = inputStream.read(buffer)) != -1) {
                  md.update(buffer, 0 , read);
                }
                byte[] computedMessageDigest = md.digest();

                if (messageDigest.length != computedMessageDigest.length)
                    return null;
                for (int i = 0; i < messageDigest.length; i++) {
                    if (messageDigest[i] != computedMessageDigest[i])
                        return null;
                }

                // message digest attribute matched
                // digest of original data

                // the data actually signed is the DER encoding of
                // the authenticated attributes (tagged with
                // the "SET OF" tag, not 0xA0).
                dataSigned = new ByteArrayInputStream(authenticatedAttributes.getDerEncoding());
            }

            // put together digest algorithm and encryption algorithm
            // to form signing algorithm
            String encryptionAlgname =
                getDigestEncryptionAlgorithmId().getName();

            // Workaround: sometimes the encryptionAlgname is actually
            // a signature name
            String tmp = AlgorithmId.getEncAlgFromSigAlg(encryptionAlgname);
            if (tmp != null) encryptionAlgname = tmp;
            String algname = AlgorithmId.makeSigAlg(
                    digestAlgname, encryptionAlgname);

            Signature sig = Signature.getInstance(algname);
            X509Certificate cert = getCertificate(block);

            if (cert == null) {
                return null;
            }
            if (cert.hasUnsupportedCriticalExtension()) {
                throw new SignatureException("Certificate has unsupported "
                                             + "critical extension(s)");
            }

            // Make sure that if the usage of the key in the certificate is
            // restricted, it can be used for digital signatures.
            // XXX We may want to check for additional extensions in the
            // future.
            boolean[] keyUsageBits = cert.getKeyUsage();
            if (keyUsageBits != null) {
                KeyUsageExtension keyUsage;
                try {
                    // We don't care whether or not this extension was marked
                    // critical in the certificate.
                    // We're interested only in its value (i.e., the bits set)
                    // and treat the extension as critical.
                    keyUsage = new KeyUsageExtension(keyUsageBits);
                } catch (IOException ioe) {
                    throw new SignatureException("Failed to parse keyUsage "
                                                 + "extension");
                }

                boolean digSigAllowed = ((Boolean)keyUsage.get(
                        KeyUsageExtension.DIGITAL_SIGNATURE)).booleanValue();

                boolean nonRepuAllowed = ((Boolean)keyUsage.get(
                        KeyUsageExtension.NON_REPUDIATION)).booleanValue();

                if (!digSigAllowed && !nonRepuAllowed) {
                    throw new SignatureException("Key usage restricted: "
                                                 + "cannot be used for "
                                                 + "digital signatures");
                }
            }

            PublicKey key = cert.getPublicKey();
            sig.initVerify(key);

            byte[] buffer = new byte[4096];
            int read = 0;
            while ((read = dataSigned.read(buffer)) != -1) {
              sig.update(buffer, 0 , read);
            }
            if (sig.verify(encryptedDigest)) {
                return this;
            }

        } catch (IOException e) {
            throw new SignatureException("IO error verifying signature:\n" +
                                         e.getMessage());

        } catch (InvalidKeyException e) {
            throw new SignatureException("InvalidKey: " + e.getMessage());

        }
        return null;
    }
313143
def sign(payload, keypair):
    """"""
    get_ed25519ll()
    #
    header = {
                "alg": ALG,
                "jwk": {
                    "kty": ALG,  # alg -> kty in jwk-08.
                    "vk": native(urlsafe_b64encode(keypair.vk))
                }
             }

    encoded_header = urlsafe_b64encode(binary(json.dumps(header, sort_keys=True)))
    encoded_payload = urlsafe_b64encode(binary(json.dumps(payload, sort_keys=True)))
    secured_input = b".".join((encoded_header, encoded_payload))
    sig_msg = ed25519ll.crypto_sign(secured_input, keypair.sk)
    signature = sig_msg[:ed25519ll.SIGNATUREBYTES]
    encoded_signature = urlsafe_b64encode(signature)

    return {"recipients":
            [{"header": native(encoded_header),
              "signature": native(encoded_signature)}],
            "payload": native(encoded_payload)}
1140342
def verifyCertificate(self, name):
        
        certPath = os.path.join(self.basePath, self.DIR_CERTS, '%s.cert.pem' % name)
        if not os.path.isfile(certPath):
            raise ValueError('Certificate [%s] not found' % certPath)
        if subprocess.call([ 'openssl', 'x509', '-noout', '-text', '-in', certPath ]) != 0:
            raise ValueError('Failed to verify the certificate')
787310
def verify(self, signature, data):
        
        return self._pk.public_key.verify(signature, data)