Adds a leading 0x to the byte signature if it's not already there.

        :param byte_sig: 4-byte signature string
        :return: normalized byte signature string
964348
def _normalize_byte_sig(byte_sig: str) -> str:
        
        if not byte_sig.startswith("0x"):
            byte_sig = "0x" + byte_sig
        if not len(byte_sig) == 10:
            raise ValueError(
                "Invalid byte signature %s, must have 10 characters", byte_sig
            )
        return byte_sig
716518
def sigfig_str(number, sigfig):
    
    assert(sigfig > 0)
    try:
        d = decimal.Decimal(number)
    except TypeError:
        d = float_to_decimal(float(number))
    sign, digits, exponent = d.as_tuple()
    if len(digits) < sigfig:
        digits = list(digits)
        digits.extend([0] * (sigfig - len(digits)))
    shift = d.adjusted()
    result = int(''.join(map(str, digits[:sigfig])))
    # Round the result
    if len(digits) > sigfig and digits[sigfig] >= 5:
        result += 1
    result = list(str(result))
    # Rounding can change the length of result
    # If so, adjust shift
    shift += len(result) - sigfig
    # reset len of result to sigfig
    result = result[:sigfig]
    if shift >= sigfig - 1:
        # Tack more zeros on the end
        result += ['0'] * (shift - sigfig + 1)
    elif 0 <= shift:
        # Place the decimal point in between digits
        result.insert(shift + 1, '.')
    else:
        # Tack zeros on the front
        assert(shift < 0)
        result = ['0.'] + ['0'] * (-shift - 1) + result
    if sign:
        result.insert(0, '-')
    return ''.join(result)
204467
def parse_param_signature(sig):
    
    match = PARAM_SIG_RE.match(sig.strip())
    if not match:
        raise RuntimeError('Parameter signature invalid, got ' + sig)
    groups = match.groups()
    modifiers = groups[0].split()
    typ, name, _, default = groups[-4:]
    return ParamTuple(name=name, typ=typ,
                      default=default, modifiers=modifiers)
983359
private byte[] bytesForBig(BigInteger big, int sigbytes, boolean remainder)
    {
        byte[] bytes = new byte[sigbytes + (remainder ? 1 : 0)];
        if (remainder)
        {
            // remaining bit is the most significant in the last byte
            bytes[sigbytes] |= 0x80;
        }
        // bitmask for a single byte
        for (int i = 0; i < sigbytes; i++)
        {
            int maskpos = 8 * (sigbytes - (i + 1));
            // apply bitmask and get byte value
            bytes[i] = (byte)(big.and(BYTE_MASK.shiftLeft(maskpos)).shiftRight(maskpos).intValue() & 0xFF);
        }
        return bytes;
    }
428035
def verify(self, h, sig, sig_fmt=SER_BINARY):
        
        s = deserialize_number(sig, sig_fmt)
        return self.p._ECDSA_verify(h, s)
922261
def checkMessageSignature(self, message):
        
        message_sig = message.getArg(OPENID_NS, 'sig')
        if not message_sig:
            raise ValueError("%s has no sig." % (message,))
        calculated_sig = self.getMessageSignature(message)
        return cryptutil.const_eq(calculated_sig, message_sig)
161671
public static byte []
toDNS(DSAParams params, byte [] sig)
throws SignatureException
{
	int rLength, sLength;
	int rOffset, sOffset;
	if ((sig[0] != ASN1_SEQ) || (sig[2] != ASN1_INT))
		throw new SignatureException("Expected SEQ, INT");
	rLength = sig[3];
	rOffset = 4;
	if (sig[rOffset] == 0) {
		rLength--;
		rOffset++;
	}
	if (sig[rOffset+rLength] != ASN1_INT)
		throw new SignatureException("Expected INT");
	sLength = sig[rOffset + rLength + 1];
	sOffset = rOffset + rLength + 2;
	if (sig[sOffset] == 0) {
		sLength--;
		sOffset++;
	}

	if ((rLength > 20) || (sLength > 20))
		throw new SignatureException("DSA R/S too long");

	byte[] newSig = new byte[41];
	Arrays.fill(newSig, (byte) 0);
	newSig[0] = (byte) ((params.getP().bitLength() - 512)/64);
	System.arraycopy(sig, rOffset, newSig, 1 + (20 - rLength), rLength);
	System.arraycopy(sig, sOffset, newSig, 21 + (20 - sLength), sLength);
	return newSig;
}
1229542
def _parse_to_recoverable_signature(sig):
    
    # Buffer for getting values of signature object
    assert isinstance(sig, bytes)
    assert len(sig) == 65

    # Make a recoverable signature of 65 bytes
    rec_sig = ffi.new("secp256k1_ecdsa_recoverable_signature *")
    # Retrieving the recid from the last byte of the signed key
    recid = ord(sig[64:65])

    # Parse a revoverable signature
    parsable_sig = lib.secp256k1_ecdsa_recoverable_signature_parse_compact(
        ctx,
        rec_sig,
        sig,
        recid
    )
    # Verify that the signature is parsable
    if not parsable_sig:
        raise InvalidSignatureError()

    return rec_sig
333407
def sign(self, msg):
        '''
        
        '''
        if self.__signingkey is None:
            raise KeyTypeError('Wrong key type for operation')
        sig = ffi.new(C_SIGNATURE)
        lib.ed25519_SignMessage(
            sig, self.__signingkey, ffi.NULL, msg, len(msg))
        return ffi.get_bytes(sig)
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
489058
def sign_raw_data(raw_data, privatekey_hex):
    
    if not isinstance(raw_data, (str, unicode)):
        raise ValueError("Data is not a string")

    raw_data = str(raw_data)

    si = ECSigner(privatekey_hex)
    si.update(raw_data)
    return si.finalize()
862230
def _validate_signal(self, sig):
        
        if not isinstance(sig, int):
            raise TypeError('sig must be an int, not {!r}'.format(sig))
        if signal is None:
            raise RuntimeError('Signals are not supported')
        if not (1 <= sig < signal.NSIG):
            raise ValueError('sig {} out of range(1, {})'.format(sig, signal.NSIG))
        if sys.platform == 'win32':
            raise RuntimeError('Signals are not really supported on Windows')
184074
public KeyVerifyParameters withSignature(byte[] signature) {
        if (signature == null) {
            this.signature = null;
        } else {
            this.signature = Base64Url.encode(signature);
        }
        return this;
    }
1324660
def byte_str(nBytes, unit='bytes', precision=2):
    
    #return (nBytes * ureg.byte).to(unit.upper())
    if unit.lower().startswith('b'):
        nUnit = nBytes
    elif unit.lower().startswith('k'):
        nUnit =  nBytes / (2.0 ** 10)
    elif unit.lower().startswith('m'):
        nUnit =  nBytes / (2.0 ** 20)
    elif unit.lower().startswith('g'):
        nUnit = nBytes / (2.0 ** 30)
    elif unit.lower().startswith('t'):
        nUnit = nBytes / (2.0 ** 40)
    else:
        raise NotImplementedError('unknown nBytes=%r unit=%r' % (nBytes, unit))
    return repr2(nUnit, precision=precision) + ' ' + unit
292050
private static BigInteger[] decodeECDSASignature(byte[] signature) throws Exception {

        try (ByteArrayInputStream inStream = new ByteArrayInputStream(signature)) {
            ASN1InputStream asnInputStream = new ASN1InputStream(inStream);
            ASN1Primitive asn1 = asnInputStream.readObject();

            BigInteger[] sigs = new BigInteger[2];
            int count = 0;
            if (asn1 instanceof ASN1Sequence) {
                ASN1Sequence asn1Sequence = (ASN1Sequence) asn1;
                ASN1Encodable[] asn1Encodables = asn1Sequence.toArray();
                for (ASN1Encodable asn1Encodable : asn1Encodables) {
                    ASN1Primitive asn1Primitive = asn1Encodable.toASN1Primitive();
                    if (asn1Primitive instanceof ASN1Integer) {
                        ASN1Integer asn1Integer = (ASN1Integer) asn1Primitive;
                        BigInteger integer = asn1Integer.getValue();
                        if (count < 2) {
                            sigs[count] = integer;
                        }
                        count++;
                    }
                }
            }
            if (count != 2) {
                throw new CryptoException(format("Invalid ECDSA signature. Expected count of 2 but got: %d. Signature is: %s", count,
                        DatatypeConverter.printHexBinary(signature)));
            }
            return sigs;
        }

    }
603766
def _sign_single(self, payload, signing_key):
        
        if not isinstance(payload, Mapping):
            raise TypeError('Expecting a mapping object, as only '
                            'JSON objects can be used as payloads.')

        token_segments = []

        signing_key = load_signing_key(signing_key, self.crypto_backend)

        header = self._make_header()
        header_b64 = base64url_encode(json_encode(header))
        payload_b64 = base64url_encode(json_encode(payload))
        signature_b64 = self._make_signature(header_b64, payload_b64, signing_key)

        token_segments = [header_b64, payload_b64, signature_b64]

        # combine the header, payload, and signature into a token and return it
        token = b'.'.join(token_segments)
        return token
1297013
def _get_sig_prefix(self, sig):
        
        if self._is_proc_like():
            return self._get_proc_like_prefix(sig)
        elif self._is_attr_like():
            return self._get_attr_like_prefix(sig)
        else:
            return ChapelObject.get_signature_prefix(self, sig)