Extracts the encryption algorithm name from a signature
algorithm name.
176770
public static String getEncAlgFromSigAlg(String signatureAlgorithm) {
        signatureAlgorithm = signatureAlgorithm.toUpperCase(Locale.ENGLISH);
        int with = signatureAlgorithm.indexOf("WITH");
        String keyAlgorithm = null;
        if (with > 0) {
            int and = signatureAlgorithm.indexOf("AND", with + 4);
            if (and > 0) {
                keyAlgorithm = signatureAlgorithm.substring(with + 4, and);
            } else {
                keyAlgorithm = signatureAlgorithm.substring(with + 4);
            }
            if (keyAlgorithm.equalsIgnoreCase("ECDSA")) {
                keyAlgorithm = "EC";
            }
        }
        return keyAlgorithm;
    }
726146
public static SignatureUtil buildInstance(String privateKey, String publicKey,
                                              Algorithms algorithms) {
        return new SignatureUtilImpl(privateKey, publicKey, algorithms);
    }
26751
def get_signing_key(self, algorithm, service_context):
        
        return service_context.keyjar.get_signing_key(
            alg2keytype(algorithm), alg=algorithm)
1069768
private String generateDigest(String algorithmName, X509Certificate cert) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithmName);
            md.update(cert.getEncoded());
            byte data[] = md.digest();

            StringBuilder buffer = new StringBuilder(3 * data.length);
            int i = 0;
            buffer.append(HEX_CHARS[(data[i] >> 4) & 0xF]);
            buffer.append(HEX_CHARS[(data[i] % 16) & 0xF]);
            for (++i; i < data.length; i++) {
                buffer.append(':');
                buffer.append(HEX_CHARS[(data[i] >> 4) & 0xF]);
                buffer.append(HEX_CHARS[(data[i] % 16) & 0xF]);
            }

            return buffer.toString();
        } catch (NoClassDefFoundError e) {
            return getMessage("sslTrust.genDigestError", algorithmName, e.getMessage());
        } catch (Exception e) {
            return getMessage("sslTrust.genDigestError", algorithmName, e.getMessage());
        }
    }
793990
public static byte[] sign(byte[] text, PrivateKey key, String algorithm) throws SignatureException {
        Signature signature;
        try {
            signature = Signature.getInstance(algorithm);
            signature.initSign(key);
        } catch (GeneralSecurityException e) {
            throw new IllegalArgumentException("cannot initialize signature for algorithm " + algorithm, e);
        }
        signature.update(text);
        return signature.sign();
    }
82098
def get_extension_name(ext):
    """"""

    # In cryptography 2.2, SCTs return "Unknown OID"
    if ext.oid == ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS:
        return 'SignedCertificateTimestampList'

    # Until at least cryptography 2.6.1, PrecertPoison has no name
    #   https://github.com/pyca/cryptography/issues/4817
    elif ca_settings.CRYPTOGRAPHY_HAS_PRECERT_POISON:  # pragma: no branch, pragma: only cryptography>=2.4
        if ext.oid == ExtensionOID.PRECERT_POISON:
            return 'PrecertPoison'

    # uppercase the FIRST letter only ("keyUsage" -> "KeyUsage")
    return re.sub('^([a-z])', lambda x: x.groups()[0].upper(), ext.oid._name)
1131975
def getSignature(self, signatureKey, serialized):
        
        try:
            return Curve.calculateSignature(signatureKey, serialized)
        except InvalidKeyException as e:
            raise AssertionError(e)
362367
def unwrap(self):
        

        if self.algorithm == 'rsa':
            return self['public_key'].parsed

        key_type = self.algorithm.upper()
        a_an = 'an' if key_type == 'EC' else 'a'
        raise ValueError(unwrap(
            '''
            Only RSA public keys may be unwrapped - this key is %s %s public
            key
            ''',
            a_an,
            key_type
        ))
1055586
public static function fromSignatureData(string $data,
        AlgorithmIdentifierType $algo): Signature
    {
        if ($algo instanceof RSASignatureAlgorithmIdentifier) {
            return RSASignature::fromSignatureString($data);
        }
        if ($algo instanceof ECSignatureAlgorithmIdentifier) {
            return ECSignature::fromDER($data);
        }
        return new GenericSignature(new BitString($data), $algo);
    }
718945
public static byte[] encipher(byte[] decrypted_bytes, String crypto_algorithm)
                    throws InvalidPasswordCipherException, UnsupportedCryptoAlgorithmException {
        EncryptedInfo info = encipher_internal(decrypted_bytes, crypto_algorithm, (String) null); // TODO check null
        return info.getEncryptedBytes();
    }
881045
def make_hasher(algorithm_id):
    """"""
    if algorithm_id == 1:
        return hashes.Hash(hashes.SHA1(), default_backend())
    elif algorithm_id == 2:
        return hashes.Hash(hashes.SHA384(), default_backend())
    else:
        raise ValueError("Unsupported signing algorithm: %s" % algorithm_id)
571687
def calculate_signature(self, node, sign=True):
        
        signed_info_xml = node.find('ds:SignedInfo',
                                    namespaces=constants.NS_MAP)
        canonicalization_method = signed_info_xml.find(
            'ds:CanonicalizationMethod', namespaces=constants.NS_MAP
        ).get('Algorithm')
        signature_method = signed_info_xml.find(
            'ds:SignatureMethod', namespaces=constants.NS_MAP
        ).get('Algorithm')
        if signature_method not in constants.TransformUsageSignatureMethod:
            raise Exception('Method ' + signature_method + ' not accepted')
        signature = constants.TransformUsageSignatureMethod[signature_method]
        signed_info = self.canonicalization(
            canonicalization_method, signed_info_xml
        )
        if not sign:
            signature_value = node.find('ds:SignatureValue',
                                        namespaces=constants.NS_MAP).text
            public_key = signature['method'].get_public_key(node, self)
            signature['method'].verify(
                signature_value,
                signed_info,
                public_key,
                signature['digest']
            )
        else:
            node.find(
                'ds:SignatureValue', namespaces=constants.NS_MAP
            ).text = b64_print(base64.b64encode(
                signature['method'].sign(
                    signed_info,
                    self.private_key,
                    signature['digest']
                )
            ))
900164
def key_sign(rsakey, message, digest):
    """"""
    padding = _asymmetric.padding.PKCS1v15()
    signature = rsakey.sign(message, padding, digest)
    return signature
1021974
def pair_for_message_hash(self, signature, msg_hash):
        

        # Decode base64 and a bitmask in first byte.
        is_compressed, recid, r, s = self._decode_signature(signature)

        # Calculate the specific public key used to sign this message.
        y_parity = recid & 1
        q = self._generator.possible_public_pairs_for_signature(msg_hash, (r, s), y_parity=y_parity)[0]
        if recid > 1:
            order = self._generator.order()
            q = self._generator.Point(q[0] + order, q[1])
        return q, is_compressed
1017836
public static String getDigAlgFromSigAlg(String signatureAlgorithm) {
        signatureAlgorithm = signatureAlgorithm.toUpperCase(Locale.ENGLISH);
        int with = signatureAlgorithm.indexOf("WITH");
        if (with > 0) {
            return signatureAlgorithm.substring(0, with);
        }
        return null;
    }
122001
def hmac_signature(string, shared_secret, challenge_hmac):
    '''
    
    '''
    msg = salt.utils.stringutils.to_bytes(string)
    key = salt.utils.stringutils.to_bytes(shared_secret)
    challenge = salt.utils.stringutils.to_bytes(challenge_hmac)
    hmac_hash = hmac.new(key, msg, hashlib.sha256)
    valid_hmac = base64.b64encode(hmac_hash.digest())
    return valid_hmac == challenge
540307
def get_algs_from_ciphersuite_name(ciphersuite_name):
    
    tls1_3 = False
    if ciphersuite_name.startswith("TLS"):
        s = ciphersuite_name[4:]

        if s.endswith("CCM") or s.endswith("CCM_8"):
            kx_name, s = s.split("_WITH_")
            kx_alg = _tls_kx_algs.get(kx_name)
            hash_alg = _tls_hash_algs.get("SHA256")
            cipher_alg = _tls_cipher_algs.get(s)
            hmac_alg = None

        else:
            if "WITH" in s:
                kx_name, s = s.split("_WITH_")
                kx_alg = _tls_kx_algs.get(kx_name)
            else:
                tls1_3 = True
                kx_alg = _tls_kx_algs.get("TLS13")

            hash_name = s.split('_')[-1]
            hash_alg = _tls_hash_algs.get(hash_name)

            cipher_name = s[:-(len(hash_name) + 1)]
            if tls1_3:
                cipher_name += "_TLS13"
            cipher_alg = _tls_cipher_algs.get(cipher_name)

            hmac_alg = None
            if cipher_alg is not None and cipher_alg.type != "aead":
                hmac_name = "HMAC-%s" % hash_name
                hmac_alg = _tls_hmac_algs.get(hmac_name)

    elif ciphersuite_name.startswith("SSL"):
        s = ciphersuite_name[7:]
        kx_alg = _tls_kx_algs.get("SSLv2")
        cipher_name, hash_name = s.split("_WITH_")
        cipher_alg = _tls_cipher_algs.get(cipher_name.rstrip("_EXPORT40"))
        kx_alg.export = cipher_name.endswith("_EXPORT40")
        hmac_alg = _tls_hmac_algs.get("HMAC-NULL")
        hash_alg = _tls_hash_algs.get(hash_name)

    return kx_alg, cipher_alg, hmac_alg, hash_alg, tls1_3