decode legacy pre-EIP-8 auth message format
762825
def decode_auth_plain(ciphertext)
      message = begin
                  @ecc.ecies_decrypt ciphertext[0,307]
                rescue
                  raise AuthenticationError, $!
                end
      raise RLPxSessionError, 'invalid message length' unless message.size == 194

      sig = message[0,65]
      pubkey = message[65+32,64]
      raise InvalidKeyError, 'invalid initiator pubkey' unless Crypto::ECCx.valid_key?(pubkey)

      nonce = message[65+32+64,32]
      flag = message[(65+32+64+32)..-1].ord
      raise RLPxSessionError, 'invalid flag' unless flag == 0

      [307, sig, pubkey, nonce, 4]
    end
924215
def decode(slug):
    
    if sys.version_info.major != 2 and isinstance(slug, bytes):
        slug = slug.decode('ascii')
    slug = slug + '=='  # base64 padding
    return uuid.UUID(bytes=base64.urlsafe_b64decode(slug))
173440
def process_auth_plain(session, encoded_auth_response)
      begin
        # extract auth id (and password)
        @auth_values = Base64.decode64(encoded_auth_response).split("\x00")
        # check for valid credentials parameters
        raise Smtpd500Exception unless @auth_values.length == 3
        # call event function to test credentials
        return_value = on_auth_event(session[:ctx], @auth_values[0], @auth_values[1], @auth_values[2])
        if return_value
          # overwrite data with returned value as authorization id
          @auth_values[0] = return_value
        end
        # save authentication information to ctx
        session[:ctx][:server][:authorization_id] = @auth_values[0].to_s.empty? ? @auth_values[1] : @auth_values[0]
        session[:ctx][:server][:authentication_id] = @auth_values[1]
        session[:ctx][:server][:authenticated] = Time.now.utc
        # response code
        return '235 OK'

      ensure
        # whatever happens in this check, reset next sequence
        session[:cmd_sequence] = :CMD_RSET
      end
    end
1102771
def decrypt_message_data(self, body):
        
        if len(body) < 8:
            raise InvalidBufferError(body)

        # TODO Check salt, session_id and sequence_number
        key_id = struct.unpack('<Q', body[:8])[0]
        if key_id != self.auth_key.key_id:
            raise SecurityError('Server replied with an invalid auth key')

        msg_key = body[8:24]
        aes_key, aes_iv = self._calc_key(self.auth_key.key, msg_key, False)
        body = AES.decrypt_ige(body[24:], aes_key, aes_iv)

        # https://core.telegram.org/mtproto/security_guidelines
        # Sections "checking sha256 hash" and "message length"
        our_key = sha256(self.auth_key.key[96:96 + 32] + body)
        if msg_key != our_key.digest()[8:24]:
            raise SecurityError(
                "Received msg_key doesn't match with expected one")

        reader = BinaryReader(body)
        reader.read_long()  # remote_salt
        if reader.read_long() != self.id:
            raise SecurityError('Server replied with a wrong session ID')

        remote_msg_id = reader.read_long()
        remote_sequence = reader.read_int()
        reader.read_int()  # msg_len for the inner object, padding ignored

        # We could read msg_len bytes and use those in a new reader to read
        # the next TLObject without including the padding, but since the
        # reader isn't used for anything else after this, it's unnecessary.
        obj = reader.tgread_object()

        return TLMessage(remote_msg_id, remote_sequence, obj)
258987
function getAuthenticationObject () {
    const authString = url.parse(parts[0]).auth;

    if (authString) {
      return {
        source: getName(),
        user: authString.split(':')[0],
        pass: authString.split(':')[1]
      };
    } else {
      return {};
    }
  }
213121
def parse_auth(header):
    
    try:
        method, data = header.split(None, 1)
        if method.lower() == 'basic':
            data = base64.b64decode(uniorbytes(data, bytes))
            user, pwd = uniorbytes(data).split(':', 1)
            return user, pwd
    except (KeyError, AttributeError, ValueError):
        return (None, None)
493994
def _parse_auth_message(self, auth_message):
        
        result = {}

        has_matched = False

        for regex in REGEXES_INVALID_USER:
            # Check for the invalid user/ip messages
            m = re.search(regex, auth_message)

            if m and not has_matched:
                has_matched = True

                # Save the username and IP
                result['username'] = m.group('user')
                result['ip'] = m.group('ip')

        for regex in REGEXES_INVALID_IP:
            # Check for the invalid ip messages
            m = re.search(regex, auth_message)

            if m and not has_matched:
                has_matched = True

                # Save the IP
                result['ip'] = m.group('ip')                        

        for regex in REGEXES_IGNORE:
            # Check for messages we want to ignore
            m = re.search(regex, auth_message)

            if m and not has_matched:
                has_matched = True

        # If it's an ssh log and we don't know what it is, handle that
        if not has_matched:
            sys.stderr.write("Unhandled auth message: %s\n" % auth_message)

        return result
99006
private void decodeAuthorizationHeader(String authString, StringBuilder userID, StringBuilder password) {
        userID.setLength(0);
        password.setLength(0);
        if (!Utils.isEmpty(authString) && authString.toLowerCase().startsWith("basic ")) {
            String decoded = Utils.base64ToString(authString.substring("basic ".length()));
            int inx = decoded.indexOf(':');
            if (inx < 0) {
                userID.append(decoded);
            } else {
                userID.append(decoded.substring(0, inx));
                password.append(decoded.substring(inx + 1));
            }
        }
    }
947954
def sig2(method, endpoint, params, provider, aws_api_version):
    '''
    
    '''
    timenow = datetime.utcnow()
    timestamp = timenow.strftime('%Y-%m-%dT%H:%M:%SZ')

    # Retrieve access credentials from meta-data, or use provided
    access_key_id, secret_access_key, token = creds(provider)

    params_with_headers = params.copy()
    params_with_headers['AWSAccessKeyId'] = access_key_id
    params_with_headers['SignatureVersion'] = '2'
    params_with_headers['SignatureMethod'] = 'HmacSHA256'
    params_with_headers['Timestamp'] = '{0}'.format(timestamp)
    params_with_headers['Version'] = aws_api_version
    keys = sorted(params_with_headers.keys())
    values = list(list(map(params_with_headers.get, keys)))
    querystring = urlencode(list(zip(keys, values)))

    canonical = '{0}\n{1}\n/\n{2}'.format(
        method.encode('utf-8'),
        endpoint.encode('utf-8'),
        querystring.encode('utf-8'),
    )

    hashed = hmac.new(secret_access_key, canonical, hashlib.sha256)
    sig = binascii.b2a_base64(hashed.digest())
    params_with_headers['Signature'] = sig.strip()

    # Add in security token if we have one
    if token != '':
        params_with_headers['SecurityToken'] = token

    return params_with_headers
569584
def _parse_user_id(stream, packet_type='user_id'):
    """"""
    value = stream.read()
    to_hash = b'\xb4' + util.prefix_len('>L', value)
    return {'type': packet_type, 'value': value, '_to_hash': to_hash}
965670
def defaultDecoder(self, message, server):
        
        mode = message.getArg(OPENID_NS, 'mode')
        fmt = "Unrecognized OpenID mode %r"
        raise ProtocolError(message, text=fmt % (mode,))
706613
function decodeBase64($info) {
         $keysNoEncode = array("lti_version", "lti_message_type", "tool_consumer_instance_description", "tool_consumer_instance_guid", "oauth_consumer_key", "custom_lti_message_encoded_base64", "oauth_nonce", "oauth_version", "oauth_callback", "oauth_timestamp", "basiclti_submit", "oauth_signature_method", "ext_ims_lis_memberships_id", "ext_ims_lis_memberships_url");
         foreach ($info as $key => $item){
             if (!in_array($key, $keysNoEncode))
                $info[$key] = base64_decode($item);
         }
        return $info;
     }
2181
def decode(self, packet):
        """"""

        ssu=packet.retrieve("Complete uuids")
        found=False
        for x in ssu:
            if EDDY_UUID in x:
                found=True
                break
        if not found:
            return None

        found=False
        adv=packet.retrieve("Advertised Data")
        for x in adv:
            luuid=x.retrieve("Service Data uuid")
            for uuid in luuid:
                if EDDY_UUID == uuid:
                    found=x
                    break
            if found:
                break


        if not found:
            return None

        try:
            top=found.retrieve("Adv Payload")[0]
        except:
            return None
        #Rebuild that part of the structure
        found.payload.remove(top)
        #Now decode
        result={}
        data=top.val
        etype = aios.EnumByte("type",self.type.val,{ESType.uid.value:"Eddystone-UID",
                                                ESType.url.value:"Eddystone-URL",
                                                ESType.tlm.value:"Eddystone-TLM",
                                                ESType.eid.value:"Eddystone-EID"})
        data=etype.decode(data)
        found.payload.append(etype)
        if etype.val== ESType.uid.value:
            power=aios.IntByte("tx_power")
            data=power.decode(data)
            found.payload.append(power)
            result["tx_power"]=power.val

            nspace=aios.Itself("namespace")
            xx=nspace.decode(data[:10])  #According to https://github.com/google/eddystone/tree/master/eddystone-uid
            data=data[10:]
            found.payload.append(nspace)
            result["name space"]=nspace.val

            nspace=aios.Itself("instance")
            xx=nspace.decode(data[:6])  #According to https://github.com/google/eddystone/tree/master/eddystone-uid
            data=data[6:]
            found.payload.append(nspace)
            result["instance"]=nspace.val

        elif etype.val== ESType.url.value:
            power=aios.IntByte("tx_power")
            data=power.decode(data)
            found.payload.append(power)
            result["tx_power"]=power.val

            url=aios.EnumByte("type",0,{0x00:"http://www.",0x01:"https://www.",0x02:"http://",0x03:"https://"})
            data=url.decode(data)
            result["url"]=url.strval
            for x in data:
                if bytes([x]) == b"\x00":
                    result["url"]+=".com/"
                elif bytes([x]) == b"\x01":
                    result["url"]+=".org/"
                elif bytes([x]) == b"\x02":
                    result["url"]+=".edu/"
                elif bytes([x]) == b"\x03":
                    result["url"]+=".net/"
                elif bytes([x]) == b"\x04":
                    result["url"]+=".info/"
                elif bytes([x]) == b"\x05":
                    result["url"]+=".biz/"
                elif bytes([x]) == b"\x06":
                    result["url"]+=".gov/"
                elif bytes([x]) == b"\x07":
                    result["url"]+=".com"
                elif bytes([x]) == b"\x08":
                    result["url"]+=".org"
                elif bytes([x]) == b"\x09":
                    result["url"]+=".edu"
                elif bytes([x]) == b"\x10":
                    result["url"]+=".net"
                elif bytes([x]) == b"\x11":
                    result["url"]+=".info"
                elif bytes([x]) == b"\x12":
                    result["url"]+=".biz"
                elif bytes([x]) == b"\x13":
                    result["url"]+=".gov"
                else:
                    result["url"]+=chr(x) #x.decode("ascii") #Yep ASCII only
                    url=aios.String("url")
            url.decode(result["url"])
            found.payload.append(url)
        elif etype.val== ESType.tlm.value:
            myinfo=aios.IntByte("version")
            data=myinfo.decode(data)
            found.payload.append(myinfo)
            myinfo=aios.ShortInt("battery")
            data=myinfo.decode(data)
            result["battery"]=myinfo.val
            found.payload.append(myinfo)
            myinfo=aios.Float88("temperature")
            data=myinfo.decode(data)
            found.payload.append(myinfo)
            result["temperature"]=myinfo.val
            myinfo=aios.LongInt("pdu count")
            data=myinfo.decode(data)
            found.payload.append(myinfo)
            result["pdu count"]=myinfo.val
            myinfo=aios.LongInt("uptime")
            data=myinfo.decode(data)
            found.payload.append(myinfo)
            result["uptime"]=myinfo.val*100 #in msecs
            return result
        #elif etype.val== ESType.tlm.eid:
        else:
            result["data"]=data
            xx=Itself("data")
            xx.decode(data)
            found.payload.append(xx)

        rssi=packet.retrieve("rssi")
        if rssi:
            result["rssi"]=rssi[-1].val
        mac=packet.retrieve("peer")
        if mac:
            result["mac address"]=mac[-1].val
        return result
331441
def decode_jwt(input_text, secure_key):
    
    if input_text is None:
        return None

    encoded = (input_text.split(":")[1]).encode('utf-8')
    decoded = jwt.decode(encoded, secure_key)
    return decoded['sub']
647432
private function extractAuthKeyFromPemContent()
    {
        $details = openssl_pkey_get_details(openssl_pkey_get_private($this->pem));
        if (!array_key_exists('key', $details)) {
            return null;
        }

        // Remove BEGIN RSA PRIVATE KEY / END RSA PRIVATE KEY lines
        $KeyStr = trim($details['key']);
        // Support line break on *nix systems, OS, older OS, and Microsoft
        $keyArr = preg_split('/\r\n|\r|\n/', $KeyStr);
        if (strpos($KeyStr, 'BEGIN') !== false) {
            array_shift($keyArr);
            array_pop($keyArr);
        }
        $authKey = implode('', $keyArr);

        // Check auth key is not empty
        if (empty($authKey)) {
            throw new RequestException('Could not retrieve Auth key from PEM content.', 401);
        }

        return $authKey;
    }
559315
def parse_auth(header):
    
    try:
        method, data = header.split(None, 1)
        if method.lower() == 'basic':
            user, pwd = touni(base64.b64decode(tob(data))).split(':',1)
            return user, pwd
    except (KeyError, ValueError):
        return None
1109603
def __get_basic_auth_header(self):
        
        if self.secret_key is None:
            return {}

        # encode/decode for py2/py3 compatibility
        auth_b64 = "%s:%s" % (self.client_id, self.secret_key)
        auth_b64 = base64.b64encode(auth_b64.encode('utf-8'))
        auth_b64 = auth_b64.decode('utf-8')

        return {'Authorization': 'Basic %s' % auth_b64}