// calcSignatureHash will, given a script and hash type for the current script
// engine instance, calculate the signature hash to be used for signing and
// verification.
437035
func calcSignatureHash(script []parsedOpcode, hashType SigHashType, tx *wire.MsgTx, idx int) []byte {
	// The SigHashSingle signature type signs only the corresponding input
	// and output (the output with the same index number as the input).
	//
	// Since transactions can have more inputs than outputs, this means it
	// is improper to use SigHashSingle on input indices that don't have a
	// corresponding output.
	//
	// A bug in the original Satoshi client implementation means specifying
	// an index that is out of range results in a signature hash of 1 (as a
	// uint256 little endian).  The original intent appeared to be to
	// indicate failure, but unfortunately, it was never checked and thus is
	// treated as the actual signature hash.  This buggy behavior is now
	// part of the consensus and a hard fork would be required to fix it.
	//
	// Due to this, care must be taken by software that creates transactions
	// which make use of SigHashSingle because it can lead to an extremely
	// dangerous situation where the invalid inputs will end up signing a
	// hash of 1.  This in turn presents an opportunity for attackers to
	// cleverly construct transactions which can steal those coins provided
	// they can reuse signatures.
	if hashType&sigHashMask == SigHashSingle && idx >= len(tx.TxOut) {
		var hash chainhash.Hash
		hash[0] = 0x01
		return hash[:]
	}

	// Remove all instances of OP_CODESEPARATOR from the script.
	script = removeOpcode(script, OP_CODESEPARATOR)

	// Make a shallow copy of the transaction, zeroing out the script for
	// all inputs that are not currently being processed.
	txCopy := shallowCopyTx(tx)
	for i := range txCopy.TxIn {
		if i == idx {
			// UnparseScript cannot fail here because removeOpcode
			// above only returns a valid script.
			sigScript, _ := unparseScript(script)
			txCopy.TxIn[idx].SignatureScript = sigScript
		} else {
			txCopy.TxIn[i].SignatureScript = nil
		}
	}

	switch hashType & sigHashMask {
	case SigHashNone:
		txCopy.TxOut = txCopy.TxOut[0:0] // Empty slice.
		for i := range txCopy.TxIn {
			if i != idx {
				txCopy.TxIn[i].Sequence = 0
			}
		}

	case SigHashSingle:
		// Resize output array to up to and including requested index.
		txCopy.TxOut = txCopy.TxOut[:idx+1]

		// All but current output get zeroed out.
		for i := 0; i < idx; i++ {
			txCopy.TxOut[i].Value = -1
			txCopy.TxOut[i].PkScript = nil
		}

		// Sequence on all other inputs is 0, too.
		for i := range txCopy.TxIn {
			if i != idx {
				txCopy.TxIn[i].Sequence = 0
			}
		}

	default:
		// Consensus treats undefined hashtypes like normal SigHashAll
		// for purposes of hash generation.
		fallthrough
	case SigHashOld:
		fallthrough
	case SigHashAll:
		// Nothing special here.
	}
	if hashType&SigHashAnyOneCanPay != 0 {
		txCopy.TxIn = txCopy.TxIn[idx : idx+1]
	}

	// The final hash is the double sha256 of both the serialized modified
	// transaction and the hash type (encoded as a 4-byte little-endian
	// value) appended.
	wbuf := bytes.NewBuffer(make([]byte, 0, txCopy.SerializeSizeStripped()+4))
	txCopy.SerializeNoWitness(wbuf)
	binary.Write(wbuf, binary.LittleEndian, hashType)
	return chainhash.DoubleHashB(wbuf.Bytes())
}
466214
func (s *SigningManager) ValidateSignature(keyringFiles []string, signedFile string, signature []byte) error {
	var signedby string
	var e error
	var checked *openpgp.Entity

	signed, err := os.Open(signedFile)
	if err != nil {
		return fmt.Errorf("%v: %v\n%v", ErrSignedFileNotFound, signedFile, err)
	}
	defer signed.Close()

	//Go through all the keyrings til either signature is valid or end of keyrings
	for _, keyringFile := range keyringFiles {
		keyringf, err := os.Open(keyringFile)
		if err != nil {
			return fmt.Errorf("%v: %v\n%v", ErrKeyringFileNotFound, keyringFile, err)
		}
		defer keyringf.Close()

		//Read both armored and unarmored keyrings
		keyring, err := openpgp.ReadArmoredKeyRing(keyringf)
		if err != nil {
			keyringf.Seek(0, 0)
			keyring, err = openpgp.ReadKeyRing(keyringf)
			if err != nil {
				return fmt.Errorf("%v: %v\n%v", ErrUnableToReadKeyring, keyringFile, err)
			}
		}

		//Check the armored detached signature
		checked, e = openpgp.CheckArmoredDetachedSignature(keyring, signed, bytes.NewReader(signature))
		if e == nil {
			for k := range checked.Identities {
				signedby = signedby + k
			}
			fmt.Printf("Signature made %v using RSA key ID %v\nGood signature from %v\n", time.Now().Format(time.RFC1123), checked.PrimaryKey.KeyIdShortString(), signedby)
			return nil
		}
		signed.Seek(0, 0)
	}
	return fmt.Errorf("%v\n%v", ErrCheckSignature, e)
}
660464
func parseSignatureSubpackets(sig *Signature, subpackets []byte, isHashed bool) (err error) {
	for len(subpackets) > 0 {
		subpackets, err = parseSignatureSubpacket(sig, subpackets, isHashed)
		if err != nil {
			return
		}
	}

	if sig.CreationTime.IsZero() {
		err = errors.StructuralError("no creation time in signature")
	}

	return
}
1349780
func (j *RS256JWTStrategy) GetSignature(ctx context.Context, token string) (string, error) {
	split := strings.Split(token, ".")
	if len(split) != 3 {
		return "", errors.New("Header, body and signature must all be set")
	}
	return split[2], nil
}
573872
func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey) (err error) {
	var hashType Hash
	switch algo {
	case SHA1WithRSA, DSAWithSHA1, ECDSAWithSHA1, SM2WithSHA1:
		hashType = SHA1
	case SHA256WithRSA, SHA256WithRSAPSS, DSAWithSHA256, ECDSAWithSHA256, SM2WithSHA256:
		hashType = SHA256
	case SHA384WithRSA, SHA384WithRSAPSS, ECDSAWithSHA384:
		hashType = SHA384
	case SHA512WithRSA, SHA512WithRSAPSS, ECDSAWithSHA512:
		hashType = SHA512
	case MD2WithRSA, MD5WithRSA:
		return InsecureAlgorithmError(algo)
	case SM2WithSM3: // SM3WithRSA reserve
		hashType = SM3
	default:
		return ErrUnsupportedAlgorithm
	}

	if !hashType.Available() {
		return ErrUnsupportedAlgorithm
	}
	fnHash := func() []byte {
		h := hashType.New()
		h.Write(signed)
		return h.Sum(nil)
	}
	switch pub := publicKey.(type) {
	case *rsa.PublicKey:
		if algo.isRSAPSS() {
			return rsa.VerifyPSS(pub, crypto.Hash(hashType), fnHash(), signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
		} else {
			return rsa.VerifyPKCS1v15(pub, crypto.Hash(hashType), fnHash(), signature)
		}
	case *dsa.PublicKey:
		dsaSig := new(dsaSignature)
		if rest, err := asn1.Unmarshal(signature, dsaSig); err != nil {
			return err
		} else if len(rest) != 0 {
			return errors.New("x509: trailing data after DSA signature")
		}
		if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
			return errors.New("x509: DSA signature contained zero or negative values")
		}
		if !dsa.Verify(pub, fnHash(), dsaSig.R, dsaSig.S) {
			return errors.New("x509: DSA verification failure")
		}
		return
	case *ecdsa.PublicKey:
		ecdsaSig := new(ecdsaSignature)
		if rest, err := asn1.Unmarshal(signature, ecdsaSig); err != nil {
			return err
		} else if len(rest) != 0 {
			return errors.New("x509: trailing data after ECDSA signature")
		}
		if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
			return errors.New("x509: ECDSA signature contained zero or negative values")
		}
		switch pub.Curve {
		case P256Sm2():
			sm2pub := &PublicKey{
				Curve: pub.Curve,
				X:     pub.X,
				Y:     pub.Y,
			}
			if !Sm2Verify(sm2pub, signed, nil, ecdsaSig.R, ecdsaSig.S) {
				return errors.New("x509: SM2 verification failure")
			}
		default:
			if !ecdsa.Verify(pub, fnHash(), ecdsaSig.R, ecdsaSig.S) {
				return errors.New("x509: ECDSA verification failure")
			}
		}
		return
	}
	return ErrUnsupportedAlgorithm
}
483616
func (ctx *Context) CreateSignature(cctx context.Context, fileIndex int64, fileReader io.Reader, writeHash SignatureWriter) error {
	s := bufio.NewScanner(fileReader)
	s.Buffer(make([]byte, ctx.blockSize), 0)
	s.Split(splitfunc.New(ctx.blockSize))

	blockIndex := int64(0)

	hashBlock := func(block []byte) error {
		weakHash, _, _ := βhash(block)
		strongHash := ctx.uniqueHash(block)

		blockHash := BlockHash{
			FileIndex:  fileIndex,
			BlockIndex: blockIndex,
			WeakHash:   weakHash,
			StrongHash: strongHash,
		}

		if len(block) < ctx.blockSize {
			blockHash.ShortSize = int32(len(block))
		}

		err := writeHash(blockHash)
		if err != nil {
			return errors.WithStack(err)
		}
		blockIndex++
		return nil
	}

	cancelCounter := 0
	for s.Scan() {
		err := hashBlock(s.Bytes())
		if err != nil {
			return errors.WithStack(err)
		}

		cancelCounter++
		if cancelCounter > 128 {
			cancelCounter = 0
			select {
			case <-cctx.Done():
				return werrors.ErrCancelled
			default:
				// keep going
			}
		}
	}

	err := s.Err()
	if err != nil {
		return errors.WithStack(err)
	}

	// let empty files have a 0-length shortblock
	if blockIndex == 0 {
		err := hashBlock([]byte{})
		if err != nil {
			return errors.WithStack(err)
		}
	}

	return nil
}
16548
func CreateSignature(stringToSignature, accessKeySecret string) string {
	// Crypto by HMAC-SHA1
	hmacSha1 := hmac.New(sha1.New, []byte(accessKeySecret))
	hmacSha1.Write([]byte(stringToSignature))
	sign := hmacSha1.Sum(nil)

	// Encode to Base64
	base64Sign := base64.StdEncoding.EncodeToString(sign)

	return base64Sign
}
664557
func (typedData *TypedData) TypeHash(primaryType string) hexutil.Bytes {
	return crypto.Keccak256(typedData.EncodeType(primaryType))
}
618196
func hash(s string) uint32 {
	h := fnv.New32a()
	if _, err := h.Write([]byte(s)); err != nil {
		log.Println("[ERROR] failed to write bytes: ", err)
	}
	return h.Sum32()
}
915573
func (c *CertificateSigningRequest) CheckSignature() error {
	if err := c.buildPKCS10CertificateSigningRequest(); err != nil {
		return err
	}
	return checkSignature(c.cr, c.cr.SignatureAlgorithm, c.cr.RawTBSCertificateRequest, c.cr.Signature)
}
545414
func isScriptHash(pops []parsedOpcode) bool {
	return len(pops) == 3 &&
		pops[0].opcode.value == OP_HASH160 &&
		pops[1].opcode.value == OP_DATA_20 &&
		pops[2].opcode.value == OP_EQUAL
}
47360
func RegisterHash(h Hash, f func() hash.Hash) {
	if h >= maxHash {
		panic("crypto: RegisterHash of unknown hash function")
	}
	hashes[h] = f
}
479448
func (ks *KeyStore) SignHash(address *Address, hash []byte) (signature []byte, _ error) {
	return ks.keystore.SignHash(accounts.Account{Address: address.address}, common.CopyBytes(hash))
}
636212
func hash(rrs []dns.RR) uint32 {
	h := fnv.New32()
	buf := make([]byte, 256)
	for _, r := range rrs {
		off, err := dns.PackRR(r, buf, 0, nil, false)
		if err == nil {
			h.Write(buf[:off])
		}
	}

	i := h.Sum32()
	return i
}
599504
func (w *wallet) signHash(account accounts.Account, hash []byte) ([]byte, error) {
	return nil, accounts.ErrNotSupported
}
301379
func ValidateSignatures(expectedAddress Hash, fragments Trytes, bundleHash Hash, spongeFunc ...SpongeFunction) (bool, error) {
	bundleHashTrits, err := TrytesToTrits(bundleHash)
	if err != nil {
		return false, err
	}

	fragmentsTrits, err := TrytesToTrits(fragments)
	if err != nil {
		return false, err
	}

	digest, err := Digest(bundleHashTrits, fragmentsTrits, 0, spongeFunc...)
	if err != nil {
		return false, err
	}

	addressTrits, err := Address(digest, spongeFunc...)
	if err != nil {
		return false, err
	}

	trytes, err := TritsToTrytes(addressTrits)
	if err != nil {
		return false, err
	}

	return expectedAddress == trytes, nil
}
455295
func (si SignerInfo) Hash() (crypto.Hash, error) {
	algo := si.DigestAlgorithm.Algorithm.String()
	hash := oid.DigestAlgorithmToCryptoHash[algo]
	if hash == 0 || !hash.Available() {
		return 0, ErrUnsupported
	}

	return hash, nil
}