Verifies the given ASN.1 encoded ECDSA signature against a hash using the
public key.

@param data
Hash of the data to verify.
@param signature
signature.
@param pub
The public key bytes to use.

@return -
192272
public static boolean verify(byte[] data, byte[] signature, byte[] pub) {
        return verify(data, ECDSASignature.decodeFromDER(signature), pub);
    }
1097220
private static org.jdom.Element signSamlElement(final org.jdom.Element element, final PrivateKey privKey, final PublicKey pubKey) {
        try {
            val providerName = System.getProperty("jsr105Provider", SIGNATURE_FACTORY_PROVIDER_CLASS);

            val clazz = Class.forName(providerName);
            val sigFactory = XMLSignatureFactory
                .getInstance("DOM", (Provider) clazz.getDeclaredConstructor().newInstance());

            val envelopedTransform = CollectionUtils.wrap(sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));

            val ref = sigFactory.newReference(StringUtils.EMPTY, sigFactory
                .newDigestMethod(DigestMethod.SHA1, null), envelopedTransform, null, null);

            val signatureMethod = getSignatureMethodFromPublicKey(pubKey, sigFactory);
            val canonicalizationMethod = sigFactory
                .newCanonicalizationMethod(
                    CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                    (C14NMethodParameterSpec) null);

            val signedInfo = sigFactory.newSignedInfo(canonicalizationMethod, signatureMethod, CollectionUtils.wrap(ref));

            val keyInfoFactory = sigFactory.getKeyInfoFactory();
            val keyValuePair = keyInfoFactory.newKeyValue(pubKey);

            val keyInfo = keyInfoFactory.newKeyInfo(CollectionUtils.wrap(keyValuePair));
            val w3cElement = toDom(element);

            val dsc = new DOMSignContext(privKey, w3cElement);

            val xmlSigInsertionPoint = getXmlSignatureInsertLocation(w3cElement);
            dsc.setNextSibling(xmlSigInsertionPoint);

            val signature = sigFactory.newXMLSignature(signedInfo, keyInfo);
            signature.sign(dsc);

            return toJdom(w3cElement);

        } catch (final Exception e) {
            throw new IllegalArgumentException("Error signing SAML element: " + e.getMessage(), e);
        }
    }
1221233
def sign_data(args):
    
    sk = _load_ecdsa_signing_key(args)

    # calculate signature of binary data
    binary_content = args.datafile.read()
    signature = sk.sign_deterministic(binary_content, hashlib.sha256)

    # back-verify signature
    vk = sk.get_verifying_key()
    vk.verify(signature, binary_content, hashlib.sha256)  # throws exception on failure

    if args.output is None or os.path.abspath(args.output) == os.path.abspath(args.datafile.name):  # append signature to input file
        args.datafile.close()
        outfile = open(args.datafile.name, "ab")
    else:  # write file & signature to new file
        outfile = open(args.output, "wb")
        outfile.write(binary_content)
    outfile.write(struct.pack("I", 0))  # Version indicator, allow for different curves/formats later
    outfile.write(signature)
    outfile.close()
    print("Signed %d bytes of data from %s with key %s" % (len(binary_content), args.datafile.name, args.keyfile.name))
888880
@SneakyThrows
    public static byte[] verifyJwsSignature(final Key signingKey, final String asString) {
        val jws = new JsonWebSignature();
        jws.setCompactSerialization(asString);
        jws.setKey(signingKey);

        val verified = jws.verifySignature();
        if (verified) {
            val payload = jws.getEncodedPayload();
            LOGGER.trace("Successfully decoded value. Result in Base64-encoding is [{}]", payload);
            return EncodingUtils.decodeBase64(payload);
        }
        return null;
    }
430351
public function verifyTokenSignature($signature, $data, PublicKey $publicKey)
    {
        if (!$publicKey instanceof VirgilPublicKey) {
            throw new VirgilCryptoException("instance of VirgilPublicKey expected");
        }

        return $this->virgilCrypto->verifySignature($data, $signature, $publicKey);
    }
811411
@Override
    public boolean checkSign(byte[] content, byte[] data) {
        try (PooledObject<SignatureHolder> holder = CACHE.get(id).get()) {
            Signature signature = holder.get().getVerify();
            signature.update(content);
            return signature.verify(BASE_64.decrypt(data));
        } catch (Exception e) {
            throw new SecureException("加密失败", e);
        }
    }
133378
def verify_ticket_signature(self, data, sig):
        
        try:
            signature = base64.b64decode(sig)
        except TypeError as e:
            if hasattr(self, "debug"):
                    print("Exception in function base64.b64decode. File %s" % (__file__))
                    print("%s" % e)
            return False
        if six.PY3:
            # To avoid "TypeError: Unicode-objects must be encoded before hashing'
            data = data.encode('utf-8')
        digest = hashlib.sha1(data).digest()
        if isinstance(self.pub_key, RSA.RSA_pub):
            try:
                self.pub_key.verify(digest, signature, 'sha1')
            except RSA.RSAError:
                return False
            return True
        if isinstance(self.pub_key, DSA.DSA_pub):
            try:
                return self.pub_key.verify_asn1(digest, signature)
            except DSA.DSAError as e:
                if hasattr(self, "debug"):
                    print("Exception in function self.pub_key.verify_asn1(digest, signature). File %s" % (__file__))
                    print("%s" % e)
                return False
        # Unknown key type
        return False
119678
public static synchronized byte[] addressHash(byte[] pubkeyBytes) {
      try {
         byte[] sha256 = MessageDigest.getInstance(SHA256).digest(pubkeyBytes);
         byte[] out = new byte[20];
         ripeMD160.update(sha256, 0, sha256.length);
         ripeMD160.doFinal(out, 0); // This also resets the hash function for
                                    // next use
         return out;
      } catch (NoSuchAlgorithmException e) {
         throw new RuntimeException(e); // Cannot happen.
      }
   }
179577
public static String encryptByPrivateKey(String data, String privateKey) throws Exception {
		PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(base64.decode(privateKey));
		KeyFactory keyf = KeyFactory.getInstance("RSA");
		PrivateKey priKey = keyf.generatePrivate(priPKCS8);
		java.security.Signature signature = java.security.Signature.getInstance("SHA256WithRSA");

		signature.initSign(priKey);
		signature.update(data.getBytes("UTf-8"));
		byte[] signed = signature.sign();
		return base64.encodeToString(signed);
	}
583444
def fully_valid_pubkey?
      return false unless valid_pubkey?
      point = ECDSA::Format::PointOctetString.decode(pubkey.htb, ECDSA::Group::Secp256k1)
      ECDSA::Group::Secp256k1.valid_public_key?(point)
    end
125662
public static Map<String, Object> verify(String token, final RSAPublicKey pk) throws InvalidTokenException {
        // RS256签名验证器
        Verifier verifier = new Verifier() {
            @Override
            public boolean verifySignature(String content, String payload, String signature) {
                return JWT.verifySignature(content,signature,pk);
            }
        };
        return verify(token, verifier);
    }
1307135
def verify_signature(self, signature, nonce, timestamp, signed_id):
        
        message = "%s%s%s%s" % (self.api_key, nonce, timestamp, signed_id)

        if self._pub_key is None:
            warnings.warn("Skipping RSA signature verification. Please pass public key on class initialization to ensure highest level of security!")
            return True

        try:
            rsa.verify(message.encode('utf-8'), signature, self._pub_key)
        except rsa.VerificationError:
            return False

        return True
1233995
public boolean verify() throws SignatureException {
        if (verified)
            return verifyResult;
        if (sigAttr != null) {
            sig.update(sigAttr);
            if (RSAdata != null) {
                byte msd[] = messageDigest.digest();
                messageDigest.update(msd);
            }
            verifyResult = (Arrays.equals(messageDigest.digest(), digestAttr) && sig.verify(digest));
        }
        else {
            if (RSAdata != null)
                sig.update(messageDigest.digest());
            verifyResult = sig.verify(digest);
        }
        verified = true;
        return verifyResult;
    }
293058
function( input, key ) {

    if( !Buffer.isBuffer( input ) )
      throw new TypeError( 'Input must be a buffer' )

    if( this.type === 'PLAIN' )
      return Buffer.allocUnsafe(0)

    if( !Buffer.isBuffer( key ) )
      throw new TypeError( 'Key must be a buffer' )

    var signature = this.type === 'HS' ?
      crypto.createHmac( this.algorithm + this.bits, key ) :
      crypto.createSign( this.algorithm + this.bits )

    signature.update( input )

    var digest = this.type === 'HS' ?
      signature.digest() :
      signature.sign( key )

    if( this.type === 'ES' )
      digest = this._signECDSA( digest )

    return digest

  }
1034239
def ecdsa_signature(hash, privkey, normalized: true)
      raise ArgumentError, "Hash is missing" if !hash
      raise ArgumentError, "Private key is missing" if !privkey

      # ECDSA signature is a pair of numbers: (Kx, s)
      # Where Kx = x coordinate of k*G mod n (n is the order of secp256k1).
      # And s = (k^-1)*(h + Kx*privkey).
      # By default, k is chosen randomly on interval [0, n - 1].
      # But this makes signatures harder to test and allows faulty or
      # backdoored RNGs to leak private keys from ECDSA signatures.
      # To avoid these issues, we'll generate k = Hash256(hash || privatekey)
      # and make all computations by hand.

      autorelease do |pool|

        # Order of our curve
        n = self.group_order
        halfn = self.group_half_order

        # Generate k deterministically from private key and message using HMAC-SHA256
        # This is an important point #1.
        kdata = rfc6979_ecdsa_nonce(hash, privkey)
        k = pool.new_bn(kdata)

        # Enforce k within group order: k = k % n
        BN_div(nil, k, k, n, pool.bn_ctx)

        # Compute K = k*G
        #(can't use K variable name because Ruby does not allow
        # constant assignment in methods)
        kG = pool.new_ec_point
        EC_POINT_mul(self.group, kG, k, nil, nil, pool.bn_ctx)

        # Compute r = K.x. This is first half of the signature.
        r = pool.new_bn
        EC_POINT_get_affine_coordinates_GFp(self.group, kG, r, nil, pool.bn_ctx)

        # Compute s = (k^-1)*(h + r*privkey).
        h = pool.new_bn(hash)
        p = pool.new_bn(privkey)
        tmp = pool.new_bn
        s = pool.new_bn
        BN_mod_mul(tmp, r, p, n, pool.bn_ctx) # tmp = r*privkey
        BN_mod_add_quick(s, tmp, h, n)        # s = h + tmp = h + r*privkey
        BN_mod_inverse(k, k, n, pool.bn_ctx)  # k' = k^-1
        BN_mod_mul(s, s, k, n, pool.bn_ctx)   # s = k'*(h + r*privkey)

        # Enforce low S values, by negating the value (modulo the order) if above order/2.
        # This is an important point #2. Not doing that would yield (sometimes)
        # non-canonical signatures that will be rejected by many relaying nodes.
        if normalized
          if BN_cmp(s, halfn) > 0
            BN_sub(s, n, s)
          end
        end

        # Fill in ECDSA_SIG structure so we can convert it into a proper DER format.
        sig = ECDSA_SIG.new
        sig[:r] = r
        sig[:s] = s

        # Encode signature in DER format.

        sig_size = 72 # typical size of a signature (when both numbers are 33 bytes).

        # allocate a bit more memory just in case (cargo cult)
        buffer = FFI::MemoryPointer.new(:uint8, sig_size + 16)
        sig_size = i2d_ECDSA_SIG(sig.pointer, pointer_to_pointer(buffer))

        # read actual number of bytes composed by OpenSSL
        signature = buffer.read_string(sig_size)
        signature
      end
    end
787310
def verify(self, signature, data):
        
        return self._pk.public_key.verify(signature, data)
669745
def ecdh(self, identity, pubkey):
        """"""
        assert pubkey[:1] == b'\x04'
        peer = ecdsa.VerifyingKey.from_string(
            pubkey[1:],
            curve=ecdsa.curves.NIST256p,
            hashfunc=hashlib.sha256)
        shared = ecdsa.VerifyingKey.from_public_point(
            point=(peer.pubkey.point * self.secexp),
            curve=ecdsa.curves.NIST256p,
            hashfunc=hashlib.sha256)
        return shared.to_string()