Example usage for java.nio.charset StandardCharsets US_ASCII

List of usage examples for java.nio.charset StandardCharsets US_ASCII

Introduction

In this page you can find the example usage for java.nio.charset StandardCharsets US_ASCII.

Prototype

Charset US_ASCII

To view the source code for java.nio.charset StandardCharsets US_ASCII.

Click Source Link

Document

Seven-bit ASCII, also known as ISO646-US, also known as the Basic Latin block of the Unicode character set.

Usage

From source file:org.apache.hc.client5.http.impl.auth.NTLMEngineImpl.java

/**
 * Creates the LM Hash of the user's password.
 *
 * @param password//  w  w w . j  a va 2s  . c o m
 *            The password.
 *
 * @return The LM Hash of the given password, used in the calculation of the
 *         LM Response.
 */
private static byte[] lmHash(final char[] password) throws NTLMEngineException {
    try {
        final char[] tmp = new char[password.length];
        for (int i = 0; i < password.length; i++) {
            tmp[i] = Character.toUpperCase(password[i]);
        }
        final byte[] oemPassword = new ByteArrayBuilder().append(tmp).toByteArray();
        final int length = Math.min(oemPassword.length, 14);
        final byte[] keyBytes = new byte[14];
        System.arraycopy(oemPassword, 0, keyBytes, 0, length);
        final Key lowKey = createDESKey(keyBytes, 0);
        final Key highKey = createDESKey(keyBytes, 7);
        final byte[] magicConstant = "KGS!@#$%".getBytes(StandardCharsets.US_ASCII);
        final Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
        des.init(Cipher.ENCRYPT_MODE, lowKey);
        final byte[] lowHash = des.doFinal(magicConstant);
        des.init(Cipher.ENCRYPT_MODE, highKey);
        final byte[] highHash = des.doFinal(magicConstant);
        final byte[] lmHash = new byte[16];
        System.arraycopy(lowHash, 0, lmHash, 0, 8);
        System.arraycopy(highHash, 0, lmHash, 8, 8);
        return lmHash;
    } catch (final Exception e) {
        throw new NTLMEngineException(e.getMessage(), e);
    }
}

From source file:adalid.commons.util.StrUtils.java

public static String getStringAscii(String string) {
    if (string == null) {
        return null;
    }//from w w  w.j  a  v  a  2  s .  c o m
    String dless = diacriticlessAscii(string);
    byte[] bytes = dless.getBytes();
    String ascii = new String(bytes, StandardCharsets.US_ASCII);
    return ascii;
}

From source file:com.ehsy.solr.util.SimplePostTool.java

/**
 * Performs a simple get on the given URL
 *///  w  ww .  ja  va2s .c om
public static void doGet(URL url) {
    try {
        if (mockMode)
            return;
        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        if (url.getUserInfo() != null) {
            String encoding = DatatypeConverter
                    .printBase64Binary(url.getUserInfo().getBytes(StandardCharsets.US_ASCII));
            urlc.setRequestProperty("Authorization", "Basic " + encoding);
        }
        urlc.connect();
        checkResponseCode(urlc);
    } catch (IOException e) {
        warn("An error occurred posting data to " + url + ". Please check that Solr is running.");
    }
}

From source file:com.ehsy.solr.util.SimplePostTool.java

/**
 * Reads data from the data stream and posts it to solr,
 * writes to the response to output//  w  w w.  j  a  v a 2  s .  c  o  m
 * @return true if success
 */
public boolean postData(InputStream data, Integer length, OutputStream output, String type, URL url) {
    if (mockMode)
        return true;
    boolean success = true;
    if (type == null)
        type = DEFAULT_CONTENT_TYPE;
    HttpURLConnection urlc = null;
    try {
        try {
            urlc = (HttpURLConnection) url.openConnection();
            try {
                urlc.setRequestMethod("POST");
            } catch (ProtocolException e) {
                fatal("Shouldn't happen: HttpURLConnection doesn't support POST??" + e);
            }
            urlc.setDoOutput(true);
            urlc.setDoInput(true);
            urlc.setUseCaches(false);
            urlc.setAllowUserInteraction(false);
            urlc.setRequestProperty("Content-type", type);
            if (url.getUserInfo() != null) {
                String encoding = DatatypeConverter
                        .printBase64Binary(url.getUserInfo().getBytes(StandardCharsets.US_ASCII));
                urlc.setRequestProperty("Authorization", "Basic " + encoding);
            }
            if (null != length)
                urlc.setFixedLengthStreamingMode(length);
            urlc.connect();
        } catch (IOException e) {
            fatal("Connection error (is Solr running at " + solrUrl + " ?): " + e);
            success = false;
        }

        try (final OutputStream out = urlc.getOutputStream()) {
            pipe(data, out);
        } catch (IOException e) {
            fatal("IOException while posting data: " + e);
            success = false;
        }

        try {
            success &= checkResponseCode(urlc);
            try (final InputStream in = urlc.getInputStream()) {
                pipe(in, output);
            }
        } catch (IOException e) {
            warn("IOException while reading response: " + e);
            success = false;
        }
    } finally {
        if (urlc != null)
            urlc.disconnect();
    }
    return success;
}

From source file:net.yacy.kelondro.util.FileUtils.java

/**
 * auto-detect the charset of a file/*from   www.ja  v  a2  s  .  c om*/
 * used code from http://jchardet.sourceforge.net/;
 * see also: http://www-archive.mozilla.org/projects/intl/chardet.html
 * @param file
 * @return a list of probable charsets
 * @throws IOException
 */
public static List<String> detectCharset(File file) throws IOException {
    // auto-detect charset, used code from http://jchardet.sourceforge.net/; see also: http://www-archive.mozilla.org/projects/intl/chardet.html
    List<String> result;
    try (BufferedInputStream imp = new BufferedInputStream(new FileInputStream(file))) { // try-with-resource to close inputstream
        nsDetector det = new nsDetector(nsPSMDetector.ALL);
        byte[] buf = new byte[1024];
        int len;
        boolean done = false;
        boolean isAscii = true;
        while ((len = imp.read(buf, 0, buf.length)) != -1) {
            if (isAscii)
                isAscii = det.isAscii(buf, len);
            if (!isAscii && !done)
                done = det.DoIt(buf, len, false);
        }
        det.DataEnd();
        result = new ArrayList<>();
        if (isAscii) {
            result.add(StandardCharsets.US_ASCII.name());
        } else {
            for (String c : det.getProbableCharsets())
                result.add(c); // worst case this returns "nomatch"
        }
    }
    return result;
}

From source file:com.joyent.manta.http.EncryptionHttpHelper.java

/**
 * Encrypts a plaintext object metadata string.
 *
 * @param metadataPlaintext string to encrypt
 * @param cipher cipher to use for encryption
 * @return byte array of ciphertext/*  w  w w .  java2  s .co m*/
 */
private byte[] encryptMetadata(final String metadataPlaintext, final Cipher cipher) {
    byte[] rawBytes = metadataPlaintext.getBytes(StandardCharsets.US_ASCII);

    try {
        return cipher.doFinal(rawBytes);
    } catch (IllegalBlockSizeException | BadPaddingException e) {
        MantaClientEncryptionException mcee = new MantaClientEncryptionException(
                "There was a problem encrypting the object's metadata", e);
        String details = String.format("key=%s, algorithm=%s", secretKey.getAlgorithm(), secretKey.getFormat());
        mcee.setContextValue("key_details", details);
        throw mcee;
    }
}

From source file:org.wso2.carbon.identity.oauth2.util.OAuth2Util.java

public static boolean doPKCEValidation(String referenceCodeChallenge, String codeVerifier,
        String challenge_method, OAuthAppDO oAuthAppDO) throws IdentityOAuth2Exception {
    //ByPass PKCE validation if PKCE Support is disabled
    if (!isPKCESupportEnabled()) {
        return true;
    }/* w w w  . jav  a 2s  .  co m*/
    if (oAuthAppDO != null && oAuthAppDO.isPkceMandatory() || referenceCodeChallenge != null) {

        //As per RFC 7636 Fallback to 'plain' if no code_challenge_method parameter is sent
        if (challenge_method == null || challenge_method.trim().length() == 0) {
            challenge_method = "plain";
        }

        //if app with no PKCE code verifier arrives
        if ((codeVerifier == null || codeVerifier.trim().length() == 0)) {
            //if pkce is mandatory, throw error
            if (oAuthAppDO.isPkceMandatory()) {
                throw new IdentityOAuth2Exception(
                        "No PKCE code verifier found.PKCE is mandatory for this " + "oAuth 2.0 application.");
            } else {
                //PKCE is optional, see if the authz code was requested with a PKCE challenge
                if (referenceCodeChallenge == null || referenceCodeChallenge.trim().length() == 0) {
                    //since no PKCE challenge was provided
                    return true;
                } else {
                    throw new IdentityOAuth2Exception("Empty PKCE code_verifier sent. This authorization code "
                            + "requires a PKCE verification to obtain an access token.");
                }
            }
        }
        //verify that the code verifier is upto spec as per RFC 7636
        if (!validatePKCECodeVerifier(codeVerifier)) {
            throw new IdentityOAuth2Exception("Code verifier used is not up to RFC 7636 specifications.");
        }
        if (OAuthConstants.OAUTH_PKCE_PLAIN_CHALLENGE.equals(challenge_method)) {
            //if the current application explicitly doesn't support plain, throw exception
            if (!oAuthAppDO.isPkceSupportPlain()) {
                throw new IdentityOAuth2Exception(
                        "This application does not allow 'plain' transformation algorithm.");
            }
            if (!referenceCodeChallenge.equals(codeVerifier)) {
                return false;
            }
        } else if (OAuthConstants.OAUTH_PKCE_S256_CHALLENGE.equals(challenge_method)) {

            try {
                MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");

                byte[] hash = messageDigest.digest(codeVerifier.getBytes(StandardCharsets.US_ASCII));
                //Trim the base64 string to remove trailing CR LF characters.
                String referencePKCECodeChallenge = new String(Base64.encodeBase64URLSafe(hash),
                        StandardCharsets.UTF_8).trim();
                if (!referencePKCECodeChallenge.equals(referenceCodeChallenge)) {
                    return false;
                }
            } catch (NoSuchAlgorithmException e) {
                if (log.isDebugEnabled()) {
                    log.debug("Failed to create SHA256 Message Digest.");
                }
                return false;
            }
        } else {
            //Invalid OAuth2 token response
            throw new IdentityOAuth2Exception(
                    "Invalid OAuth2 Token Response. Invalid PKCE Code Challenge Method '" + challenge_method
                            + "'");
        }
    }
    //pkce validation successful
    return true;
}