Converts the signature generated by DSA signature routines to
the one expected inside an RRSIG/SIG record.
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;
}
314416
def sig_encode(r, s):
    """"""
    r = util.assuan_serialize(util.num2bytes(r, 32))
    s = util.assuan_serialize(util.num2bytes(s, 32))
    return b'(7:sig-val(5:ecdsa(1:r32:' + r + b')(1:s32:' + s + b')))'
1126776
public static Map<String, String> deserializeCatalogSignature(String signature) {
        Map<String, String> tableSignatures = Maps.newHashMap();
        for (String oneSig : signature.split(Pattern.quote(SIGNATURE_DELIMITER))) {
            if (!oneSig.isEmpty()) {
                final String[] parts = oneSig.split(Pattern.quote(SIGNATURE_TABLE_NAME_SEPARATOR), 2);
                tableSignatures.put(parts[0], parts[1]);
            }
        }
        return tableSignatures;
    }
1034616
public static String convertMethodSignature(InvokeInstruction inv, ConstantPoolGen cpg) {
        return convertMethodSignature(inv.getClassName(cpg), inv.getName(cpg), inv.getSignature(cpg));
    }
98662
function genOAuthSig (options) {

    log(options.verbose,"Now generating OAuth sig ...");

    // Build an array of all the parameters we need to include in the signature.
    // Signature parameters are in the format {key,value}, both the key and the
    // value need to be RFC3986 percent encoded.

    var sigParams  = [];

    if ( options.queryParams ) {
        Object.keys(options.queryParams).forEach(function (key) {
            sigParams.push(createEncodedParam(key,options.queryParams[key]));
        });
    }

    sigParams.push(createEncodedParam("oauth_consumer_key",options.oAuthConsumerKey));
    sigParams.push(createEncodedParam("oauth_nonce",options.oAuthNonce));
    sigParams.push(createEncodedParam("oauth_signature_method",options.oAuthSignatureMethod));
    sigParams.push(createEncodedParam("oauth_timestamp",options.oAuthTimestamp));
    sigParams.push(createEncodedParam("oauth_token",options.oAuthToken));
    sigParams.push(createEncodedParam("oauth_version",options.oAuthVersion));

    // Parameters need to be sorted alphabetically based on the encoded key.

    sigParams.sort(function (a,b) {
        if ( a.key < b.key ) {
            return -1;
        } else if ( a.key > b.key ) {
            return 1;
        } else {
            return 0;
        }
    });

    // Build the signature parameter string from the sorted array.

    var sigParamsString = "";

    log(options.verbose,"Ordered percent encoded sig params are:");

    for ( var i=0; i<sigParams.length; i++ ) {
        sigParamsString += sigParams[i].key+"="+sigParams[i].value;
        log(options.verbose,"  "+sigParams[i].key+"="+sigParams[i].value);
        if ( sigParams[i+1] ) {
            sigParamsString += "&";
        }
    }

    log(options.verbose,"Generated sig params string: "+sigParamsString);

    // Build the base signature string from the HTTP method, base URL and signature
    // parameter string.

    var sigBaseString = options.method.toUpperCase()+"&";
    sigBaseString += percentEncode(options.baseURL)+"&";
    sigBaseString += percentEncode(sigParamsString);

    log(options.verbose,"Generated base sig string: "+sigBaseString);

    // Generate the signing key from the consumer secret and oAuth token secret.

    var signingKey = options.oAuthConsumerSecret+"&"+options.oAuthTokenSecret;

    log(options.verbose,"Generated HMAC-SHA1 signing key: "+signingKey);

    // The final value for the OAuth signature is the HMAC-SHA1 hash of the
    // signing key and the base sig string, all base64 encoded.

    var oAuthSig = crypto.createHmac("sha1",signingKey).update(sigBaseString).digest("base64");

    log(options.verbose,"OAuth sig is: "+oAuthSig);

    return oAuthSig;
}
351529
def _parse_signature(stream):
    """"""
    p = {'type': 'signature'}

    to_hash = io.BytesIO()
    with stream.capture(to_hash):
        p['version'] = stream.readfmt('B')
        p['sig_type'] = stream.readfmt('B')
        p['pubkey_alg'] = stream.readfmt('B')
        p['hash_alg'] = stream.readfmt('B')
        p['hashed_subpackets'] = parse_subpackets(stream)

    # https://tools.ietf.org/html/rfc4880#section-5.2.4
    tail_to_hash = b'\x04\xff' + struct.pack('>L', to_hash.tell())

    p['_to_hash'] = to_hash.getvalue() + tail_to_hash

    p['unhashed_subpackets'] = parse_subpackets(stream)
    embedded = list(_parse_embedded_signatures(p['unhashed_subpackets']))
    if embedded:
        log.debug('embedded sigs: %s', embedded)
        p['embedded'] = embedded

    p['hash_prefix'] = stream.readfmt('2s')
    if p['pubkey_alg'] in ECDSA_ALGO_IDS:
        p['sig'] = (parse_mpi(stream), parse_mpi(stream))
    elif p['pubkey_alg'] in RSA_ALGO_IDS:  # RSA
        p['sig'] = (parse_mpi(stream),)
    elif p['pubkey_alg'] == DSA_ALGO_ID:
        p['sig'] = (parse_mpi(stream), parse_mpi(stream))
    else:
        log.error('unsupported public key algo: %d', p['pubkey_alg'])

    assert not stream.read()
    return p
1316843
public static String transformMethodSignature(String signature) {
        StringBuilder buf = new StringBuilder();

        buf.append('(');

        SignatureParser parser = new SignatureParser(signature);
        for (Iterator<String> i = parser.parameterSignatureIterator(); i.hasNext();) {
            String param = i.next();
            param = transformSignature(param);
            buf.append(param);
        }

        buf.append(')');

        return buf.toString();
    }
469441
def from_signed_raw(cls: Type[TransactionType], raw: str) -> TransactionType:
        
        lines = raw.splitlines(True)
        n = 0

        version = int(Transaction.parse_field("Version", lines[n]))
        n += 1

        Transaction.parse_field("Type", lines[n])
        n += 1

        currency = Transaction.parse_field("Currency", lines[n])
        n += 1

        blockstamp = None  # type: Optional[BlockUID]
        if version >= 3:
            blockstamp = BlockUID.from_str(Transaction.parse_field("Blockstamp", lines[n]))
            n += 1

        locktime = Transaction.parse_field("Locktime", lines[n])
        n += 1

        issuers = []
        inputs = []
        unlocks = []
        outputs = []
        signatures = []

        if Transaction.re_issuers.match(lines[n]):
            n += 1
            while Transaction.re_inputs.match(lines[n]) is None:
                issuer = Transaction.parse_field("Pubkey", lines[n])
                issuers.append(issuer)
                n += 1

        if Transaction.re_inputs.match(lines[n]):
            n += 1
            while Transaction.re_unlocks.match(lines[n]) is None:
                input_source = InputSource.from_inline(version, lines[n])
                inputs.append(input_source)
                n += 1

        if Transaction.re_unlocks.match(lines[n]):
            n += 1
            while Transaction.re_outputs.match(lines[n]) is None:
                unlock = Unlock.from_inline(lines[n])
                unlocks.append(unlock)
                n += 1

        if Transaction.re_outputs.match(lines[n]) is not None:
            n += 1
            while not Transaction.re_comment.match(lines[n]):
                _output = OutputSource.from_inline(lines[n])
                outputs.append(_output)
                n += 1

        comment = Transaction.parse_field("Comment", lines[n])
        n += 1

        if Transaction.re_signature.match(lines[n]) is not None:
            while n < len(lines):
                sign = Transaction.parse_field("Signature", lines[n])
                signatures.append(sign)
                n += 1

        return cls(version, currency, blockstamp, locktime, issuers, inputs, unlocks, outputs,
                   comment, signatures)
1227124
def write_signatures(self, signatures):
        
        self.fileobj.seek(self.signature_offset)
        sig_entries = [dict(algorithm_id=id_,
                            size=len(sig),
                            signature=sig)
                       for (id_, sig) in signatures]

        sigs = sigs_header.build(dict(
            filesize=self.filesize,
            count=len(signatures),
            sigs=sig_entries,
        ))
        self.fileobj.write(sigs)
        signatures_len = len(sigs)
        self.additional_offset = self.signature_offset + signatures_len
        # sanity check; this should never happen
        if not self.additional_offset == self.fileobj.tell():  # pragma: no cover
            raise IOError('ended up at unexpected offset')
356469
def signature(self):
        
        sig_elems = [self.seqid, self.source, self.type, \
                    self.start, self.end, self.strand, \
                    self.phase]
        if re.search("exon|CDS|UTR", self.type):
            parent = self.get_attr("Parent")
            if parent:
                (locus, iso) = atg_name(parent, retval="locus,iso", \
                        trimpad0=False)
                if locus:
                    sig_elems.append(locus)
        else:
            sig_elems.extend([self.accn])

        return ",".join(str(elem) for elem in sig_elems)
222490
def _build_signature(self):
        """"""
        sig_contents = \
            self.payload + "." + \
            b64encode(b"application/xml").decode("ascii") + "." + \
            b64encode(b"base64url").decode("ascii") + "." + \
            b64encode(b"RSA-SHA256").decode("ascii")
        sig_hash = SHA256.new(sig_contents.encode("ascii"))
        cipher = PKCS1_v1_5.new(self.private_key)
        sig = urlsafe_b64encode(cipher.sign(sig_hash))
        key_id = urlsafe_b64encode(bytes(self.author_handle, encoding="utf-8"))
        return sig, key_id
571888
def selfsig(self):
        
        if self.parent is not None:
            return next((sig for sig in reversed(self._signatures) if sig.signer == self.parent.fingerprint.keyid), None)
904224
@VisibleForTesting
    static String generateSignature(Credential signingCredential, String algorithmURI, String input) {
        try {
            final byte[] signature =
                    XMLSigningUtil.signWithURI(signingCredential, algorithmURI,
                                               input.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(signature);
        } catch (SecurityException e) {
            throw new SamlException("failed to generate a signature", e);
        }
    }
833626
def parse_method_signature(sig):
    
    match = METH_SIG_RE.match(sig.strip())
    if not match:
        raise RuntimeError('Method signature invalid: ' + sig)
    modifiers, return_type, name, generic_types, params = match.groups()
    if params.strip() != '':
        params = split_sig(params)
        params = [parse_param_signature(x) for x in params]
    else:
        params = []
    return (modifiers.split(), return_type, name, generic_types, params)
827807
public static String transformSignature(String signature) {
        StringBuilder buf = new StringBuilder();

        int lastBracket = signature.lastIndexOf('[');
        if (lastBracket > 0) {
            buf.append(signature.substring(0, lastBracket + 1));
            signature = signature.substring(lastBracket + 1);
        }

        if (signature.startsWith("L")) {
            signature = signature.substring(1, signature.length() - 1).replace('/', '.');
            signature = transformClassName(signature);
            signature = "L" + signature.replace('.', '/') + ";";
        }
        buf.append(signature);

        return buf.toString();
    }
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;
        }

    }
1203473
def _generate_signature(self, nonce, method, path, data):
        

        data_json = ""
        endpoint = path
        if method == "get":
            if data:
                query_string = self._get_params_for_sig(data)
                endpoint = "{}?{}".format(path, query_string)
        elif data:
            data_json = compact_json_dict(data)
        sig_str = ("{}{}{}{}".format(nonce, method.upper(), endpoint, data_json)).encode('utf-8')
        m = hmac.new(self.API_SECRET.encode('utf-8'), sig_str, hashlib.sha256)
        return base64.b64encode(m.digest())