org.apache.tomcat.util.buf.HexUtils Java Examples

The following examples show how to use org.apache.tomcat.util.buf.HexUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MessageDigestCredentialHandler.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
protected String mutate(String inputCredentials, byte[] salt, int iterations) {
    if (algorithm == null) {
        return inputCredentials;
    } else {
        byte[] userDigest;
        if (salt == null) {
            userDigest = ConcurrentMessageDigest.digest(algorithm, iterations,
                    inputCredentials.getBytes(encoding));
        } else {
            userDigest = ConcurrentMessageDigest.digest(algorithm, iterations,
                    salt, inputCredentials.getBytes(encoding));
        }
        return HexUtils.toHexString(userDigest);
    }
}
 
Example #2
Source File: RealmBase.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Digest password using the algorithm specified and convert the result to a
 * corresponding hex string.
 *
 * @param credentials Password or other credentials to use in authenticating
 *                    this username
 * @param algorithm   Algorithm used to do the digest
 * @param encoding    Character encoding of the string to digest
 *
 * @return The digested credentials as a hex string or the original plain
 *         text credentials if an error occurs.
 *
 * @deprecated  Unused. This will be removed in Tomcat 9.
 */
@Deprecated
public static final String Digest(String credentials, String algorithm,
                                  String encoding) {

    try {
        // Obtain a new message digest with "digest" encryption
        MessageDigest md =
            (MessageDigest) MessageDigest.getInstance(algorithm).clone();

        // encode the credentials
        // Should use the digestEncoding, but that's not a static field
        if (encoding == null) {
            md.update(credentials.getBytes());
        } else {
            md.update(credentials.getBytes(encoding));
        }

        // Digest the credentials and return as hexadecimal
        return (HexUtils.toHexString(md.digest()));
    } catch(Exception ex) {
        log.error(ex);
        return credentials;
    }

}
 
Example #3
Source File: AjpMessage.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Dump the contents of the message, prefixed with the given String.
 */
public void dump(String msg) {
    if (log.isDebugEnabled()) {
        log.debug(msg + ": " + HexUtils.toHexString(buf) + " " + pos +"/" + (len + 4));
    }
    int max = pos;
    if (len + 4 > pos)
        max = len+4;
    if (max > 1000)
        max = 1000;
    if (log.isDebugEnabled()) {
        for (int j = 0; j < max; j += 16) { 
            log.debug(hexLine(buf, j, len));
        }
    }
}
 
Example #4
Source File: RealmBase.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Digest password using the algorithm specified and
 * convert the result to a corresponding hex string.
 * If exception, the plain credentials string is returned
 *
 * @param credentials Password or other credentials to use in
 *  authenticating this username
 * @param algorithm Algorithm used to do the digest
 * @param encoding Character encoding of the string to digest
 */
public static final String Digest(String credentials, String algorithm,
                                  String encoding) {

    try {
        // Obtain a new message digest with "digest" encryption
        MessageDigest md =
            (MessageDigest) MessageDigest.getInstance(algorithm).clone();

        // encode the credentials
        // Should use the digestEncoding, but that's not a static field
        if (encoding == null) {
            md.update(credentials.getBytes());
        } else {
            md.update(credentials.getBytes(encoding));
        }

        // Digest the credentials and return as hexadecimal
        return (HexUtils.toHexString(md.digest()));
    } catch(Exception ex) {
        log.error(ex);
        return credentials;
    }

}
 
Example #5
Source File: AjpMessage.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Dump the contents of the message, prefixed with the given String.
 */
public void dump(String msg) {
    if (log.isDebugEnabled()) {
        log.debug(msg + ": " + HexUtils.toHexString(buf) + " " + pos +"/" + (len + 4));
    }
    int max = pos;
    if (len + 4 > pos)
        max = len+4;
    if (max > 1000)
        max = 1000;
    if (log.isDebugEnabled()) {
        for (int j = 0; j < max; j += 16) { 
            log.debug(hexLine(buf, j, len));
        }
    }
}
 
Example #6
Source File: RealmBase.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Digest password using the algorithm specified and
 * convert the result to a corresponding hex string.
 * If exception, the plain credentials string is returned
 *
 * @param credentials Password or other credentials to use in
 *  authenticating this username
 * @param algorithm Algorithm used to do the digest
 * @param encoding Character encoding of the string to digest
 */
public static final String Digest(String credentials, String algorithm,
                                  String encoding) {

    try {
        // Obtain a new message digest with "digest" encryption
        MessageDigest md =
            (MessageDigest) MessageDigest.getInstance(algorithm).clone();

        // encode the credentials
        // Should use the digestEncoding, but that's not a static field
        if (encoding == null) {
            md.update(credentials.getBytes());
        } else {
            md.update(credentials.getBytes(encoding));                
        }

        // Digest the credentials and return as hexadecimal
        return (HexUtils.toHexString(md.digest()));
    } catch(Exception ex) {
        log.error(ex);
        return credentials;
    }

}
 
Example #7
Source File: DesEncryptProvider.java    From mPass with Apache License 2.0 5 votes vote down vote up
/**
 * 加密
 *
 * @param encryptStr
 * @return
 */
@Override
public String encrypt(String encryptStr) {
    synchronized (this.encryptor) {
        try {
            encryptor.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encodes = Base64.getEncoder().encode(encryptor.doFinal(encryptStr.getBytes(CHARSET_DEFAULT)));
            return HexUtils.toHexString(encodes);
        } catch (Exception e) {
            log.error(ENCRYPT_DES + "加密出错", e);
        }
    }
    return null;
}
 
Example #8
Source File: BaseNCodec.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a String useful for debugging (especially within a debugger.)
 *
 * @return a String useful for debugging.
 */
@SuppressWarnings("boxing") // OK to ignore boxing here
@Override
public String toString() {
    return String.format("%s[buffer=%s, currentLinePos=%s, eof=%s, " +
            "ibitWorkArea=%s, lbitWorkArea=%s, modulus=%s, pos=%s, " +
            "readPos=%s]", this.getClass().getSimpleName(),
            HexUtils.toHexString(buffer), currentLinePos, eof,
            ibitWorkArea, lbitWorkArea, modulus, pos, readPos);
}
 
Example #9
Source File: ChunkedOutputFilter.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Write some bytes.
 * 
 * @return number of bytes written by the filter
 */
@Override
public int doWrite(ByteChunk chunk, Response res)
    throws IOException {

    int result = chunk.getLength();

    if (result <= 0) {
        return 0;
    }

    // Calculate chunk header
    int pos = 7;
    int current = result;
    while (current > 0) {
        int digit = current % 16;
        current = current / 16;
        chunkLength[pos--] = HexUtils.getHex(digit);
    }
    chunkHeader.setBytes(chunkLength, pos + 1, 9 - pos);
    buffer.doWrite(chunkHeader, res);

    buffer.doWrite(chunk, res);

    chunkHeader.setBytes(chunkLength, 8, 2);
    buffer.doWrite(chunkHeader, res);

    return result;

}
 
Example #10
Source File: RealmBase.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Digest the password using the specified algorithm and
 * convert the result to a corresponding hexadecimal string.
 * If exception, the plain credentials string is returned.
 *
 * @param credentials Password or other credentials to use in
 *  authenticating this username
 */
protected String digest(String credentials)  {

    // If no MessageDigest instance is specified, return unchanged
    if (hasMessageDigest() == false)
        return (credentials);

    // Digest the user credentials and return as hexadecimal
    synchronized (this) {
        try {
            md.reset();

            byte[] bytes = null;
            try {
                bytes = credentials.getBytes(getDigestCharset());
            } catch (UnsupportedEncodingException uee) {
                log.error("Illegal digestEncoding: " + getDigestEncoding(), uee);
                throw new IllegalArgumentException(uee.getMessage());
            }
            md.update(bytes);

            return (HexUtils.toHexString(md.digest()));
        } catch (Exception e) {
            log.error(sm.getString("realmBase.digest"), e);
            return (credentials);
        }
    }

}
 
Example #11
Source File: ChunkedOutputFilter.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Write some bytes.
 * 
 * @return number of bytes written by the filter
 */
@Override
public int doWrite(ByteChunk chunk, Response res)
    throws IOException {

    int result = chunk.getLength();

    if (result <= 0) {
        return 0;
    }

    // Calculate chunk header
    int pos = 7;
    int current = result;
    while (current > 0) {
        int digit = current % 16;
        current = current / 16;
        chunkLength[pos--] = HexUtils.getHex(digit);
    }
    chunkHeader.setBytes(chunkLength, pos + 1, 9 - pos);
    buffer.doWrite(chunkHeader, res);

    buffer.doWrite(chunk, res);

    chunkHeader.setBytes(chunkLength, 8, 2);
    buffer.doWrite(chunkHeader, res);

    return result;

}
 
Example #12
Source File: RealmBase.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Digest the password using the specified algorithm and
 * convert the result to a corresponding hexadecimal string.
 * If exception, the plain credentials string is returned.
 *
 * @param credentials Password or other credentials to use in
 *  authenticating this username
 */
protected String digest(String credentials)  {

    // If no MessageDigest instance is specified, return unchanged
    if (hasMessageDigest() == false)
        return (credentials);

    // Digest the user credentials and return as hexadecimal
    synchronized (this) {
        try {
            md.reset();

            byte[] bytes = null;
            try {
                bytes = credentials.getBytes(getDigestCharset());
            } catch (UnsupportedEncodingException uee) {
                log.error("Illegal digestEncoding: " + getDigestEncoding(), uee);
                throw new IllegalArgumentException(uee.getMessage());
            }
            md.update(bytes);

            return (HexUtils.toHexString(md.digest()));
        } catch (Exception e) {
            log.error(sm.getString("realmBase.digest"), e);
            return (credentials);
        }
    }

}
 
Example #13
Source File: DesEncryptProvider.java    From mPass with Apache License 2.0 5 votes vote down vote up
/**
 * 解密
 *
 * @param decryptStr
 * @return
 */
@Override
public String decrypt(String decryptStr) {
    synchronized (this.decryptor) {
        try {
            decryptor.init(Cipher.DECRYPT_MODE, secretKey);
            return new String(decryptor.doFinal(Base64.getDecoder().decode(HexUtils.fromHexString(decryptStr))), CHARSET_DEFAULT);
        } catch (Exception e) {
            log.error(ENCRYPT_DES + "解密出错", e);
        }
    }
    return null;
}
 
Example #14
Source File: AesEncryptProvider.java    From mPass with Apache License 2.0 5 votes vote down vote up
/**
 * 解密
 *
 * @param decryptStr
 * @return
 */
@Override
public String decrypt(String decryptStr) {
    synchronized (this.decryptor) {
        try {
            decryptor.init(Cipher.DECRYPT_MODE, secretKey, ivParam);
            return new String(decryptor.doFinal(Base64.getDecoder().decode(HexUtils.fromHexString(decryptStr))), CHARSET_DEFAULT);
        } catch (Exception e) {
            log.error(ENCRYPT_AES + "解密出错", e);
        }
    }
    return null;
}
 
Example #15
Source File: AesEncryptProvider.java    From mPass with Apache License 2.0 5 votes vote down vote up
/**
 * 加密
 *
 * @param encryptStr
 * @return
 */
@Override
public String encrypt(String encryptStr) {
    synchronized (this.encryptor) {
        try {
            encryptor.init(Cipher.ENCRYPT_MODE, secretKey, ivParam);
            byte[] encodes = Base64.getEncoder().encode(encryptor.doFinal(encryptStr.getBytes(CHARSET_DEFAULT)));
            return HexUtils.toHexString(encodes);
        } catch (Exception e) {
            log.error(ENCRYPT_AES + "加密出错", e);
        }
    }
    return null;
}
 
Example #16
Source File: Md5EncryptProvider.java    From mPass with Apache License 2.0 5 votes vote down vote up
@Override
public String encrypt(String encryptStr) {
    try {
        MessageDigest messageDigest = MessageDigest.getInstance(ENCRYPT_MD5);
        if (!StringUtils.isEmpty(this.password)) {
            messageDigest.update((encryptStr + this.password).getBytes(CHARSET_DEFAULT));
        } else {
            messageDigest.update(encryptStr.getBytes(CHARSET_DEFAULT));
        }
        return String.valueOf(HexUtils.toHexString(messageDigest.digest()));
    } catch (NoSuchAlgorithmException e) {
        log.error("Not a valid encryption algorithm", e);
        throw new IllegalArgumentException("Not a valid encryption algorithm", e);
    }
}
 
Example #17
Source File: MDCFilter.java    From tensorboot with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    MDC.put(CONTEXT, HexUtils.toHexString(BigInteger.valueOf(random.nextInt()).toByteArray()));
    try {
        chain.doFilter(request, response);
    } finally {
        MDC.clear();
    }
}
 
Example #18
Source File: AjpMessage.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void dump(String prefix) {
    if (log.isDebugEnabled()) {
        log.debug(prefix + ": " + HexUtils.toHexString(buf) + " " + pos +"/" + (len + 4));
    }
    int max = pos;
    if (len + 4 > pos)
        max = len+4;
    if (max > 1000)
        max = 1000;
    if (log.isDebugEnabled()) {
        for (int j = 0; j < max; j += 16) {
            log.debug(hexLine(buf, j, len));
        }
    }
}
 
Example #19
Source File: ApplicationPushBuilder.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private static String decodePercentSequence(String sequence, Charset charset) {
    byte[] bytes = new byte[sequence.length()/3];
    for (int i = 0; i < bytes.length; i += 3) {
        bytes[i] = (byte) ((HexUtils.getDec(sequence.charAt(1 + 3 * i)) << 4) +
                HexUtils.getDec(sequence.charAt(2 + 3 * i)));
    }

    return new String(bytes, charset);
}
 
Example #20
Source File: ChunkedOutputFilter.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private int calculateChunkHeader(int len) {
    // Calculate chunk header
    int pos = 8;
    int current = len;
    while (current > 0) {
        int digit = current % 16;
        current = current / 16;
        chunkHeader.put(--pos, HexUtils.getHex(digit));
    }
    return pos;
}
 
Example #21
Source File: BaseNCodec.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Returns a String useful for debugging (especially within a debugger.)
 *
 * @return a String useful for debugging.
 */
@SuppressWarnings("boxing") // OK to ignore boxing here
@Override
public String toString() {
    return String.format("%s[buffer=%s, currentLinePos=%s, eof=%s, " +
            "ibitWorkArea=%s, modulus=%s, pos=%s, " +
            "readPos=%s]", this.getClass().getSimpleName(),
            HexUtils.toHexString(buffer), currentLinePos, eof,
            ibitWorkArea, modulus, pos, readPos);
}
 
Example #22
Source File: TestStreamQueryString.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Parameters
public static Collection<Object[]> inputs() {
    List<Object[]> result = new ArrayList<>();
    // Test ASCII characters from 32 to 126 inclusive
    for (int i = 32; i < 128; i++) {
        result.add(new String[] { "%" + HexUtils.toHexString(new byte[] { (byte) i})});
    }
    return result;
}
 
Example #23
Source File: SecretKeyCredentialHandler.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected String mutate(String inputCredentials, byte[] salt, int iterations, int keyLength) {
    try {
        KeySpec spec = new PBEKeySpec(inputCredentials.toCharArray(), salt, iterations, keyLength);
        return HexUtils.toHexString(secretKeyFactory.generateSecret(spec).getEncoded());
    } catch (InvalidKeySpecException | IllegalArgumentException e) {
        log.warn(sm.getString("pbeCredentialHandler.invalidKeySpec"), e);
        return null;
    }
}
 
Example #24
Source File: Md5EncryptProvider.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
@Override
public String encrypt(String encryptStr) {
    try {
        MessageDigest messageDigest = MessageDigest.getInstance(ENCRYPT_MD5);
        if (!StringUtils.isEmpty(this.password)) {
            messageDigest.update((encryptStr + this.password).getBytes(CHARSET_DEFAULT));
        } else {
            messageDigest.update(encryptStr.getBytes(CHARSET_DEFAULT));
        }
        return String.valueOf(HexUtils.toHexString(messageDigest.digest()));
    } catch (NoSuchAlgorithmException e) {
        log.error("Not a valid encryption algorithm", e);
        throw new IllegalArgumentException("Not a valid encryption algorithm", e);
    }
}
 
Example #25
Source File: DesEncryptProvider.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
/**
 * 解密
 *
 * @param decryptStr
 * @return
 */
@Override
public String decrypt(String decryptStr) {
    synchronized (this.decryptor) {
        try {
            decryptor.init(Cipher.DECRYPT_MODE, secretKey);
            return new String(decryptor.doFinal(Base64.getDecoder().decode(HexUtils.fromHexString(decryptStr))), CHARSET_DEFAULT);
        } catch (Exception e) {
            log.error(ENCRYPT_DES + "解密出错", e);
        }
    }
    return null;
}
 
Example #26
Source File: AesEncryptProvider.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
/**
 * 加密
 *
 * @param encryptStr
 * @return
 */
@Override
public String encrypt(String encryptStr) {
    synchronized (this.encryptor) {
        try {
            encryptor.init(Cipher.ENCRYPT_MODE, secretKey, ivParam);
            byte[] encodes = Base64.getEncoder().encode(encryptor.doFinal(encryptStr.getBytes(CHARSET_DEFAULT)));
            return HexUtils.toHexString(encodes);
        } catch (Exception e) {
            log.error(ENCRYPT_AES + "加密出错", e);
        }
    }
    return null;
}
 
Example #27
Source File: AesEncryptProvider.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
/**
 * 解密
 *
 * @param decryptStr
 * @return
 */
@Override
public String decrypt(String decryptStr) {
    synchronized (this.decryptor) {
        try {
            decryptor.init(Cipher.DECRYPT_MODE, secretKey, ivParam);
            return new String(decryptor.doFinal(Base64.getDecoder().decode(HexUtils.fromHexString(decryptStr))), CHARSET_DEFAULT);
        } catch (Exception e) {
            log.error(ENCRYPT_AES + "解密出错", e);
        }
    }
    return null;
}
 
Example #28
Source File: DesEncryptProvider.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
/**
 * 加密
 *
 * @param encryptStr
 * @return
 */
@Override
public String encrypt(String encryptStr) {
    synchronized (this.encryptor) {
        try {
            encryptor.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encodes = Base64.getEncoder().encode(encryptor.doFinal(encryptStr.getBytes(CHARSET_DEFAULT)));
            return HexUtils.toHexString(encodes);
        } catch (Exception e) {
            log.error(ENCRYPT_DES + "加密出错", e);
        }
    }
    return null;
}
 
Example #29
Source File: DigestCredentialHandlerBase.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Checks whether the provided credential matches the stored credential when
 * the stored credential is in the form salt$iteration-count$credential
 *
 * @param inputCredentials  The input credential
 * @param storedCredentials The stored credential
 *
 * @return <code>true</code> if they match, otherwise <code>false</code>
 */
protected boolean matchesSaltIterationsEncoded(String inputCredentials,
        String storedCredentials) {

    if (storedCredentials == null) {
        // Stored credentials are invalid
        // This may be expected if nested credential handlers are being used
        logInvalidStoredCredentials(null);
        return false;
    }

    int sep1 = storedCredentials.indexOf('$');
    int sep2 = storedCredentials.indexOf('$', sep1 + 1);

    if (sep1 < 0 || sep2 < 0) {
        // Stored credentials are invalid
        // This may be expected if nested credential handlers are being used
        logInvalidStoredCredentials(storedCredentials);
        return false;
    }

    String hexSalt = storedCredentials.substring(0,  sep1);

    int iterations = Integer.parseInt(storedCredentials.substring(sep1 + 1, sep2));

    String storedHexEncoded = storedCredentials.substring(sep2 + 1);
    byte[] salt;
    try {
        salt = HexUtils.fromHexString(hexSalt);
    } catch (IllegalArgumentException iae) {
        logInvalidStoredCredentials(storedCredentials);
        return false;
    }

    String inputHexEncoded = mutate(inputCredentials, salt, iterations,
            HexUtils.fromHexString(storedHexEncoded).length * Byte.SIZE);
    if (inputHexEncoded == null) {
        // Failed to mutate user credentials. Automatic fail.
        // Root cause should be logged by mutate()
        return false;
    }

    return storedHexEncoded.equalsIgnoreCase(inputHexEncoded);
}
 
Example #30
Source File: BaseOpenIDConnectAuthenticator.java    From tomcat-oidcauth with Apache License 2.0 4 votes vote down vote up
/**
 * Add request attributes for the login or the login error page.
 *
 * @param request The request.
 *
 * @throws IOException If an I/O error happens.
 */
protected void addLoginConfiguration(final Request request)
	throws IOException {

	// generate state value and save it in the session
	final byte[] stateBytes = new byte[16];
	this.rand.nextBytes(stateBytes);
	final String state = HexUtils.toHexString(stateBytes);
	request.getSessionInternal(true).setNote(SESS_STATE_NOTE, state);

	// add OP authorization endpoints to the request for the login page
	final List<AuthEndpointDesc> authEndpoints = new ArrayList<>();
	final StringBuilder buf = new StringBuilder(128);
	for (int i = 0; i < this.opDescs.size(); i++) {
		final OPDescriptor opDesc = this.opDescs.get(i);

		// get the OP configuration
		final String issuer = opDesc.getIssuer();
		final OPConfiguration opConfig =
			this.ops.getOPConfiguration(issuer);

		// construct the authorization endpoint URL
		buf.setLength(0);
		buf.append(opConfig.getAuthorizationEndpoint());
		buf.append("?scope=openid");
		final String extraScopes = opDesc.getAdditionalScopes();
		if (extraScopes != null)
			buf.append(URLEncoder.encode(" " + extraScopes, UTF8.name()));
		buf.append("&response_type=code");
		buf.append("&client_id=").append(URLEncoder.encode(
				opDesc.getClientId(), UTF8.name()));
		buf.append("&redirect_uri=").append(URLEncoder.encode(
				this.getBaseURL(request) + Constants.FORM_ACTION,
				UTF8.name()));
		buf.append("&state=").append(i).append('Z').append(state);
		final String addlParams = opDesc.getExtraAuthEndpointParams();
		if (addlParams != null)
			buf.append('&').append(addlParams);

		// add the URL to the map
		authEndpoints.add(new AuthEndpointDesc(
				opDesc.getName(), issuer, buf.toString()));
	}
	request.setAttribute(AUTHEPS_ATT, authEndpoints);

	// add no form flag to the request
	request.setAttribute(NOFORM_ATT, Boolean.valueOf(this.noForm));
}