Security code for subject-security going forward
424831
void securityMessageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
        final boolean loggerIsEnabled = logger != null && logger.isTraceEnabled();

        if (! httpRequestMessageReceived(nextFilter, session, message)) return;

        HttpRequestMessage httpRequest = (HttpRequestMessage) message;
        ResourceAddress httpAddress = httpRequest.getLocalAddress();
        
        if (alreadyLoggedIn(httpRequest)) {
            // KG-3232, KG-3267: we should never leave the login context unset
            // for unprotected services.
            if (httpRequest.getLoginContext() == null) {
                setUnprotectedLoginContext(httpRequest);
            }
            if (loggerIsEnabled) {
                logger.trace("HttpSubjectSecurityFilter skipped because we are already allowed or logged in.");
            }

            super.doMessageReceived(nextFilter, session, message);
            return;
        }

        HttpRealmInfo[] realms = httpAddress.getOption(HttpResourceAddress.REALMS);
        if (realms.length == 0) {
            setUnprotectedLoginContext(httpRequest);
            if (loggerIsEnabled) {
                logger.trace("HttpSecurityStandardFilter skipped because no realm is configured.");
            }
            super.doMessageReceived(nextFilter, session, message);
            return;
        }
        
        String challengeIdentity = httpRequest.getHeader(HEADER_SEC_CHALLENGE_IDENTITY);
        LoginContext[] loginContexts = getLoginContexts(challengeIdentity);
        int realmIndex = findCurrentRealm(loginContexts);
        HttpRealmInfo realm = realms[realmIndex];

        AuthenticationTokenExtractor tokenExtractor = DefaultAuthenticationTokenExtractor.INSTANCE;

        //
        // Login using the token; if login fails, the appropriate reply has already been sent from this filter
        // so stop the filter chain here.
        //

        DefaultAuthenticationToken authToken = (DefaultAuthenticationToken) tokenExtractor.extract(httpRequest, realm);

        String expectedChallengeScheme = getBaseAuthScheme(realm.getChallengeScheme());

        // Now set the expected challenge scheme on the AuthToken.  If the
        // client provided a scheme, the above check ensures that the
        // provided scheme matches our expected scheme, so calling setScheme()
        // does not harm anything.  If the client did NOT provide a scheme,
        // this properly sets one, for the benefit of login modules which
        // check for such things.
        if(authToken.getScheme() == null) {
            authToken.setScheme(expectedChallengeScheme);
        }

        // Suspend incoming events into this filter. Will resume after LoginContext.login() completion
        suspendIncoming(session);

        TypedCallbackHandlerMap additionalCallbacks = null;
        if (realmIndex > 0) {
            additionalCallbacks = new TypedCallbackHandlerMap();
            Function<String, Subject> subjects = name -> findNamedSubject(name, realms, realmIndex, loginContexts);
            NamedSubjectCallbackHandler callbackHandler = new NamedSubjectCallbackHandler(subjects);
            additionalCallbacks.put(NamedSubjectCallback.class, callbackHandler);
        }

        // Schedule LoginContext.login() execution using a separate thread
        LoginContextTask loginContextTask = new LoginContextTask(nextFilter, session, httpRequest, authToken, additionalCallbacks, realms, realmIndex, loginContexts);
        scheduler.execute(loginContextTask);
    }
793657
public static boolean isUnauthenticated(Subject subject) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            SibTr.entry(tc, CLASS_NAME + "isUnauthenticated", subject);
        }
        boolean result = subjectHelper.isUnauthenticated(subject);
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            SibTr.exit(tc, CLASS_NAME + "isUnauthenticated", result);
        }
        return result;
    }
1329826
private void configureSecurity(ServletContextHandler context, String realmName, String authMethod,
								   String formLoginPage, String formErrorPage) {
		final SecurityHandler securityHandler = context.getSecurityHandler();

		Authenticator authenticator = null;
		if (authMethod == null) {
			LOG.warn("UNKNOWN AUTH METHOD: " + authMethod);
		} else {
			switch (authMethod) {
				case Constraint.__FORM_AUTH:
					authenticator = new FormAuthenticator();
					securityHandler.setInitParameter(FormAuthenticator.__FORM_LOGIN_PAGE, formLoginPage);
					securityHandler.setInitParameter(FormAuthenticator.__FORM_ERROR_PAGE, formErrorPage);
					break;
				case Constraint.__BASIC_AUTH:
					authenticator = new BasicAuthenticator();
					break;
				case Constraint.__DIGEST_AUTH:
					authenticator = new DigestAuthenticator();
					break;
				case Constraint.__CERT_AUTH:
					authenticator = new ClientCertAuthenticator();
					break;
				case Constraint.__CERT_AUTH2:
					authenticator = new ClientCertAuthenticator();
					break;
				case Constraint.__SPNEGO_AUTH:
					authenticator = new SpnegoAuthenticator();
					break;
				default:
					authenticator = getAuthenticator(authMethod);
					break;
			}
		}

		securityHandler.setAuthenticator(authenticator);

		securityHandler.setRealmName(realmName);

	}
308940
protected final int computeHashCode(Subject subject, ConnectionRequestInfo cri) {

        final boolean isTracingEnabled = TraceComponent.isAnyTracingEnabled();

        if (isTracingEnabled && tc.isEntryEnabled()) {
            Tr.entry(this, tc, "computeHashCode");
        }

        if (isTracingEnabled && tc.isDebugEnabled()) {

            StringBuffer sbuff = new StringBuffer();
            sbuff.append("computeHashCode for Subject ");
            if (subject == null) {
                sbuff.append("null");
            } else {
                // synchronized (this) {
                SubjectToString subjectToString = new SubjectToString();
                subjectToString.setSubject(subject);
                sbuff.append(AccessController.doPrivileged(subjectToString));
                // }
            }
            if (cri == null) {
                sbuff.append(" and CRI null");
            } else {
                sbuff.append(" and CRI " + cri.toString());
            }
            Tr.debug(this, tc, sbuff.toString());

        }
        /*
         * Future improvement can be if we may
         * want to check subject a cri before
         * computing hashcode again
         */

        int sHash, cHash, hashCode;

        if (subject != null) {

            // RRA currently returns false for re-authentication support
            if (!gConfigProps.raSupportsReauthentication) {
                /*
                 * If we are the rra or re-authentication is not supported,
                 * get the subjects hash code and use it in the computed
                 * hash code value.
                 */
                SubjectHashCode subjectHashCode = new SubjectHashCode();
                subjectHashCode.setSubject(subject);
                sHash = AccessController.doPrivileged(subjectHashCode);
            } else {
                /*
                 * If re-authentication is supported, do
                 * not use the subjects hash code in the computed hash code value.
                 * Use the default value of 1.
                 */
                sHash = 1;
            }

        } else {
            sHash = 1;
        }

        if (cri != null) {
            cHash = cri.hashCode();
        } else {
            cHash = 1;
        }

        hashCode = Math.abs((sHash / 2) + (cHash / 2));

        if (isTracingEnabled && tc.isDebugEnabled()) {
            Tr.debug(this, tc, "Subject's hash code is " + sHash + " and the CRI's hash code is " + cHash);
            Tr.debug(this, tc, "computeHashCode, hashCode is " + hashCode);
        }

        if (isTracingEnabled && tc.isEntryEnabled()) {
            Tr.exit(this, tc, "computeHashCode");
        }

        return hashCode;

    }
517204
function createCsrSubject(subjectObj) {
    return Object.entries(subjectObj).reduce((result, [shortName, value]) => {
        if (value) {
            result.push({ shortName, value });
        }

        return result;
    }, []);
}
531594
function(apiKey, contactList, fromAddress,
        toAddress, ccAddresses, bccAddresses, contentType, subject, htmlBody,
        textBody, _templateId) {}
69349
def register_subject_version(self, subject, schema):
        
        data = json.dumps({'schema': json.dumps(schema)})
        res = requests.post(self._url('/subjects/{}/versions', subject), data=data, headers=HEADERS)
        raise_if_failed(res)
        return res.json()['id']
666784
def add_authenticated_read(self):
        
        self.remove_perm(d1_common.const.SUBJECT_PUBLIC, 'read')
        self.add_perm(d1_common.const.SUBJECT_AUTHENTICATED, 'read')
273167
def ssl?
      @env[Merb::Const::UPCASE_HTTPS] == 'on' || @env[Merb::Const::HTTP_X_FORWARDED_PROTO] == Merb::Const::HTTPS
    end
475587
def get_subject(self):
        
        assert self.assertion.subject
        subject = self.assertion.subject
        subjconf = []

        if not self.verify_attesting_entity(subject.subject_confirmation):
            raise VerificationError("No valid attesting address")

        for subject_confirmation in subject.subject_confirmation:
            _data = subject_confirmation.subject_confirmation_data

            if subject_confirmation.method == SCM_BEARER:
                if not self._bearer_confirmed(_data):
                    continue
            elif subject_confirmation.method == SCM_HOLDER_OF_KEY:
                if not self._holder_of_key_confirmed(_data):
                    continue
            elif subject_confirmation.method == SCM_SENDER_VOUCHES:
                pass
            else:
                raise ValueError("Unknown subject confirmation method: %s" % (
                    subject_confirmation.method,))

            _recip = _data.recipient
            if not _recip or not self.verify_recipient(_recip):
                raise VerificationError("No valid recipient")

            subjconf.append(subject_confirmation)

        if not subjconf:
            raise VerificationError("No valid subject confirmation")

        subject.subject_confirmation = subjconf

        # The subject may contain a name_id

        if subject.name_id:
            self.name_id = subject.name_id
        elif subject.encrypted_id:
            # decrypt encrypted ID
            _name_id_str = self.sec.decrypt(
                subject.encrypted_id.encrypted_data.to_string())
            _name_id = saml.name_id_from_string(_name_id_str)
            self.name_id = _name_id

        logger.info("Subject NameID: %s", self.name_id)
        return self.name_id
657701
def security_hash(namespace, tag, hash, extra_info = {})
      key = [namespace, tag].compact.join(":")

      sec_hash = {
        "wsse:Security" => {
          key => hash
        },
        :attributes! => { "wsse:Security" => { "xmlns:wsse" => WSE_NAMESPACE } }
      }

      unless extra_info.empty?
        sec_hash["wsse:Security"].merge!(extra_info)
      end

      if signature?
        sec_hash[:attributes!].merge!("soapenv:mustUnderstand" => "1")
      else
        sec_hash["wsse:Security"].merge!(:attributes! => { key => { "wsu:Id" => "#{tag}-#{count}", "xmlns:wsu" => WSU_NAMESPACE } })
      end

      sec_hash
    end
901237
def generate_security_hash(self, content_type, object_pk, timestamp):
        
        info = (content_type, object_pk, timestamp)
        key_salt = "django.contrib.forms.CommentSecurityForm"
        value = "-".join(info)
        return salted_hmac(key_salt, value).hexdigest()
680399
def run_as(self, identifiers):
        
        if (not self.has_identifiers):
            msg = ("This subject does not yet have an identity.  Assuming the "
                   "identity of another Subject is only allowed for Subjects "
                   "with an existing identity.  Try logging this subject in "
                   "first, or using the DelegatingSubject.Builder "
                   "to build ad hoc Subject instances with identities as "
                   "necessary.")
            raise ValueError(msg)
        self.push_identity(identifiers)
579418
private static void setSecurityEnabled( Catalog catalog, SecurityType security) {
        Cluster cluster = catalog.getClusters().get("cluster");
        Database database = cluster.getDatabases().get("database");

        cluster.setSecurityenabled(security.isEnabled());
        database.setSecurityprovider(security.getProvider().value());
    }
1089811
def subject_key_identifier(self):
        """"""
        try:
            ext = self.x509.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_KEY_IDENTIFIER)
        except x509.ExtensionNotFound:
            return None
        return SubjectKeyIdentifier(ext)
19045
def schema_is_registered_for_subject(self, subject, schema):
        
        data = json.dumps({'schema': json.dumps(schema)})
        res = requests.post(self._url('/subjects/{}', subject), data=data, headers=HEADERS)
        if res.status_code == 404:
            return False
        raise_if_failed(res)
        return True
261304
def add_extensions
        ef = OpenSSL::X509::ExtensionFactory.new
        ef.subject_certificate = @ca_cert
        ef.issuer_certificate = @ca_cert

        @ca_cert.add_extension ef.create_extension('subjectKeyIdentifier', 'hash')
        @ca_cert.add_extension ef.create_extension('basicConstraints', 'CA:TRUE', true)
        @ca_cert.add_extension ef.create_extension('keyUsage', 'cRLSign,keyCertSign', true)

      end