/*
the following methods are based off code to compute the subject
name hash from:
http://blog.piefox.com/2008/10/javaopenssl-ca-generation.html
436545
protected static String opensslHash(X509Certificate cert) {
        try {
            return openssl_X509_NAME_hash(cert.getSubjectX500Principal());
        }
        catch (Exception e) {
            throw new Error("MD5 isn't available!", e);
        }
    }
1237143
@ShellMethod(key = "generate-anonymous-user", value = "Generate an anonymous (persistent) username identifier")
    public void generateUsername(
        @ShellOption(value = {"username"},
            help = "Authenticated username") final String username,
        @ShellOption(value = {"service"},
            help = "Service application URL for which CAS may generate the identifier") final String service,
        @ShellOption(value = {"salt"},
            help = "Salt used to generate and encode the anonymous identifier") final String salt) {
        val generator = new ShibbolethCompatiblePersistentIdGenerator(salt);
        val id = generator.generate(username, service);
        LOGGER.info("Generated identifier:\n[{}]", id);
    }
811326
function generateHash( module, testName ) {
	var hex,
		i = 0,
		hash = 0,
		str = module + "\x1C" + testName,
		len = str.length;

	for ( ; i < len; i++ ) {
		hash  = ( ( hash << 5 ) - hash ) + str.charCodeAt( i );
		hash |= 0;
	}

	// Convert the possibly negative integer hash code into an 8 character hex string, which isn't
	// strictly necessary but increases user understanding that the id is a SHA-like hash
	hex = ( 0x100000000 + hash ).toString( 16 );
	if ( hex.length < 8 ) {
		hex = "0000000" + hex;
	}

	return hex.slice( -8 );
}
1301534
function (cert, cb) {
    var infoObject = {},
        subjectElements = [],
        err;

  	var openssl = spawn('openssl', ['req', '-noout', '-subject', '-nameopt', 'RFC2253']);

    // Catch stderr
    openssl.stderr.on('data', function (out) {
      err = new Error(out);

      // Callback and return array
  		return cb(err, infoObject);
    });

    openssl.stdout.on('data', function (out) {
      var data = out.toString();

      // Put each line into an array
      var lineArray = data.split('\n');

      // Filter out empty ones
      lineArray = lineArray.filter(function(n){ return n !== undefined && n !== '' });

      /* Construct infoObject */

      // Certificate
      infoObject.certificate = cert;

      // Subject
      infoObject.subject = {};
      // Split by "/" prefix
      subjectElements = lineArray[0].replace('subject=', '').split(',');
      // For each elements
      for (var iS = 0; iS < subjectElements.length; iS++) {
        // Split keys and values by "=" separator
        var subjectKeyValue = subjectElements[iS].split('=');
        infoObject.subject[subjectKeyValue[0]] = subjectKeyValue[1];
      }

      // Callback and return array
  		return cb(err, infoObject);
  	});

  	openssl.stdin.write(cert);
  	openssl.stdin.end();
  }
647624
private Hashtable<String, ?> getUniqueIdAndSecurityNameHashtableFromSubject(final Subject subject) {
        final String[] properties = { AttributeNameConstants.WSCREDENTIAL_UNIQUEID,
                                      AttributeNameConstants.WSCREDENTIAL_SECURITYNAME };
        SubjectHelper subjectHelper = new SubjectHelper();
        return subjectHelper.getHashtableFromSubject(subject, properties);
    }
1212442
function () {
		let name = '';
		const scount = randomizer.getWeightedRandom(namedata.holmesian_scount.values, namedata.holmesian_scount.weights);
	
		for (let i = 1; i <= scount; i++) {
			name += randomizer.rollRandom(namedata.holmesian_syllables); // array
			if (i < scount) {
				name += randomizer.getWeightedRandom(['', ' ', '-'], [3, 2, 2]);
			}
		}
		name = name.toLowerCase() + ' ' + randomizer.rollRandom(namedata.holmesian_title);
		
		name = randomizer.findToken(name);
		
		name = name.replace(/[\s\-]([a-z]{1})/g, (match) => {
			return match.toUpperCase();
		});
		return name;
	}
916232
public static int hashIgnoreCase(int hash, String s) {
    if (s == null) {
      return hash;
    }
    int length = s.length();
    for (int i = 0; i < length; i++) {
      hash = 31 * hash + URIUtils.toLower(s.charAt(i));
    }
    return hash;
  }
1231566
public String getUserName(Subject subject) {
		// Subject subject = null;
		try {
			// subject = WSSubject.getRunAsSubject();
			WSCredential wsCred = getWSCredential(subject);
			if (wsCred == null) {
				wsCred = getPrivateWSCredential(subject);
			}
			return wsCred != null ? wsCred.getSecurityName() : null;
		} catch (Exception e) {
			// ffdc
			return null;
		}
	}
990249
@Sensitive
    public Hashtable<String, ?> getSensitiveHashtableFromSubject(@Sensitive final Subject subject, @Sensitive final String[] properties) {
        return AccessController.doPrivileged(new PrivilegedAction<Hashtable<String, ?>>() {
            @Override
            public Hashtable<String, ?> run() {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Looking for custom properties in public cred list.");
                }
                Set<Object> list_public = subject.getPublicCredentials();
                Hashtable<String, ?> hashtableFromPublic = getSensitiveHashtable(list_public, properties);
                if (hashtableFromPublic != null) {
                    return hashtableFromPublic;
                }

                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Looking for custom properties in private cred list.");
                }
                Set<Object> list_private = subject.getPrivateCredentials();
                Hashtable<String, ?> hashtableFromPrivate = getSensitiveHashtable(list_private, properties);
                if (hashtableFromPrivate != null) {
                    return hashtableFromPrivate;
                }

                return null;
            }
        });
    }
1062084
@POST
    @Consumes("application/x.json-create-api-key")
    public Response createApiKey(CreateEmoApiKeyRequest request, @QueryParam("key") String key,
                                 @Authenticated Subject subject) {
        if (key != null) {
            request.setCustomRequestParameter("key", key);
        }
        CreateEmoApiKeyResponse response = _uac.createApiKey(subject, request);

        return Response.created(URI.create(response.getId()))
                .entity(response)
                .build();
    }
209566
@Override
	public String getJwtSSOToken(Subject subject) {
		// TODO Auto-generated method stub
		String encodedjwtprincipal = null;
		Set<JsonWebToken> jsonWebTokenPrincipalSet = getJwtPrincipals(subject);
		if (jsonWebTokenPrincipalSet != null && !jsonWebTokenPrincipalSet.isEmpty()) {
			if (hasMultiplePrincipals(jsonWebTokenPrincipalSet)) {
				// TODO error
			} else {
				encodedjwtprincipal = convertToEncoded(jsonWebTokenPrincipalSet.iterator().next());
			}
		}
		return encodedjwtprincipal;
	}
1201997
function(hash){
    var params = {},
        regex = /([^&=]+)=([^&]*)/g,
        m;

    while ((m = regex.exec(hash)) !== null) {
      params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
    }

    // OpenID Connect
    if (params.id_token && !params.error) {
      IdToken.validateTokensAndPopulateClaims(params);
      return params;
    }

    // Oauth2
    if(params.access_token || params.error){
      return params;
    }
  }
344030
static String toJavaName(String opensslName) {
        if (opensslName == null) {
            return null;
        }
        Matcher matcher = PATTERN.matcher(opensslName);
        if (matcher.matches()) {
            String group1 = matcher.group(1);
            if (group1 != null) {
                return group1.toUpperCase(Locale.ROOT) + "with" + matcher.group(2).toUpperCase(Locale.ROOT);
            }
            if (matcher.group(3) != null) {
                return matcher.group(4).toUpperCase(Locale.ROOT) + "with" + matcher.group(3).toUpperCase(Locale.ROOT);
            }

            if (matcher.group(5) != null) {
                return matcher.group(6).toUpperCase(Locale.ROOT) + "with" + matcher.group(5).toUpperCase(Locale.ROOT);
            }
        }
        return null;
    }
1169392
private String getSignature(String str) {
    try {
      MessageDigest md = MessageDigest.getInstance(SHA_STRING);
      md.update(str.getBytes());
      md.update(secretBytes);
      byte[] digest = md.digest();
      return new Base64(0).encodeToString(digest);
    } catch (NoSuchAlgorithmException ex) {
      throw new RuntimeException("Invalid SHA digest String: " + SHA_STRING +
        " " + ex.getMessage(), ex);
    }
  }
38036
function hashString(string) {
  // This is the hash from JVM
  // The hash code for a string is computed as
  // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],
  // where s[i] is the ith character of the string and n is the length of
  // the string. We "mod" the result to make it between 0 (inclusive) and 2^31
  // (exclusive) by dropping high bits.
  let hashed = 0;
  for (let ii = 0; ii < string.length; ii++) {
    hashed = (31 * hashed + string.charCodeAt(ii)) | 0;
  }
  return smi(hashed);
}
1080687
private String generateHash(String secret) {

		//check for any null values and set them to empty string for hashing
		String timeStamp = null == this.timeStamp ? "" : this.timeStamp;
		String merchantId = null == this.merchantId ? "" : this.merchantId;
		String orderId = null == this.orderId ? "" : this.orderId;
		String result = null == this.result ? "" : this.result;
		String message = null == this.message ? "" : this.message;
		String pasRef = null == this.pasRef ? "" : this.pasRef;
		String authCode = null == this.authCode ? "" : this.authCode;

		//create String to hash
		String toHash = new StringBuilder().append(timeStamp)
				.append(".")
				.append(merchantId)
				.append(".")
				.append(orderId)
				.append(".")
				.append(result)
				.append(".")
				.append(message)
				.append(".")
				.append(pasRef)
				.append(".")
				.append(authCode)
				.toString();

		return GenerationUtils.generateHash(toHash, secret);
	}
857774
function getName(name) {
    const ext = path.extname(name);
    
    const nameCrypt = crypto.createHash('sha1')
        .update(name)
        .digest('hex') + ext;
    
    return getDir() + nameCrypt;
}