Search in sources :

Example 11 with CoderResult

use of java.nio.charset.CoderResult in project hudson-2.x by hudson.

the class WriterOutputStream method decode.

/**
     * Decodes the contents of {@link #buf} as much as possible to {@link #out}.
     * If necessary {@link #out} is further sent to {@link #writer}.
     *
     * <p>
     * When this method returns, the {@link #buf} is back to the 'accumulation'
     * mode.
     *
     * @param last
     *      if true, tell the decoder that all the input bytes are ready.
     */
private void decode(boolean last) throws IOException {
    buf.flip();
    while (true) {
        CoderResult r = decoder.decode(buf, out, last);
        if (r == CoderResult.OVERFLOW) {
            flushOutput();
            continue;
        }
        if (r == CoderResult.UNDERFLOW) {
            buf.compact();
            return;
        }
        // otherwise treat it as an error
        r.throwException();
    }
}
Also used : CoderResult(java.nio.charset.CoderResult)

Example 12 with CoderResult

use of java.nio.charset.CoderResult in project Android-Terminal-Emulator by jackpal.

the class ShortcutEncryption method decrypt.

/**
     * Decrypts a string encrypted using this algorithm and verifies that the
     * contents have not been tampered with.
     *
     * @param encrypted The string to decrypt, in the format described above.
     * @param keys The keys to verify and decrypt with.
     * @return The decrypted data.
     *
     * @throws GeneralSecurityException if the data is invalid, verification fails, or an error occurs during decryption.
     */
public static String decrypt(String encrypted, Keys keys) throws GeneralSecurityException {
    Cipher cipher = Cipher.getInstance(ENC_SYSTEM);
    String[] data = COLON.split(encrypted);
    if (data.length != 3) {
        throw new GeneralSecurityException("Invalid encrypted data!");
    }
    String mac = data[0];
    String iv = data[1];
    String cipherText = data[2];
    // Verify that the ciphertext and IV haven't been tampered with first
    String dataToAuth = iv + ":" + cipherText;
    if (!computeMac(dataToAuth, keys.getMacKey()).equals(mac)) {
        throw new GeneralSecurityException("Incorrect MAC!");
    }
    // Decrypt the ciphertext
    byte[] ivBytes = decodeBase64(iv);
    cipher.init(Cipher.DECRYPT_MODE, keys.getEncKey(), new IvParameterSpec(ivBytes));
    byte[] bytes = cipher.doFinal(decodeBase64(cipherText));
    // Decode the plaintext bytes into a String
    CharsetDecoder decoder = Charset.defaultCharset().newDecoder();
    decoder.onMalformedInput(CodingErrorAction.REPORT);
    decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
    /*
         * We are coding UTF-8 (guaranteed to be the default charset on
         * Android) to Java chars (UTF-16, 2 bytes per char).  For valid UTF-8
         * sequences, then:
         *     1 byte in UTF-8 (US-ASCII) -> 1 char in UTF-16
         *     2-3 bytes in UTF-8 (BMP)   -> 1 char in UTF-16
         *     4 bytes in UTF-8 (non-BMP) -> 2 chars in UTF-16 (surrogate pair)
         * The decoded output is therefore guaranteed to fit into a char
         * array the same length as the input byte array.
         */
    CharBuffer out = CharBuffer.allocate(bytes.length);
    CoderResult result = decoder.decode(ByteBuffer.wrap(bytes), out, true);
    if (result.isError()) {
        /* The input was supposed to be the result of encrypting a String,
             * so something is very wrong if it cannot be decoded into one! */
        throw new GeneralSecurityException("Corrupt decrypted data!");
    }
    decoder.flush(out);
    return out.flip().toString();
}
Also used : CharsetDecoder(java.nio.charset.CharsetDecoder) GeneralSecurityException(java.security.GeneralSecurityException) CharBuffer(java.nio.CharBuffer) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) CoderResult(java.nio.charset.CoderResult)

Example 13 with CoderResult

use of java.nio.charset.CoderResult in project jmonkeyengine by jMonkeyEngine.

the class HttpZipLocator method getUTF8String.

private static String getUTF8String(byte[] b, int off, int len) throws CharacterCodingException {
    StringBuilder sb = new StringBuilder();
    int read = 0;
    while (read < len) {
        // Either read n remaining bytes in b or 250 if n is higher.
        int toRead = Math.min(len - read, byteBuf.capacity());
        boolean endOfInput = toRead < byteBuf.capacity();
        // read 'toRead' bytes into byteBuf
        byteBuf.put(b, off + read, toRead);
        // set limit to position and set position to 0
        // so data can be decoded
        byteBuf.flip();
        // decode data in byteBuf
        CoderResult result = utf8Decoder.decode(byteBuf, charBuf, endOfInput);
        // then the decoder expects more bytes but there are no more => error
        if (!result.isUnderflow() || !endOfInput) {
            result.throwException();
        }
        // flip the char buf to get the string just decoded
        charBuf.flip();
        // append the decoded data into the StringBuilder
        sb.append(charBuf.toString());
        // clear buffers for next use
        byteBuf.clear();
        charBuf.clear();
        read += toRead;
    }
    return sb.toString();
}
Also used : CoderResult(java.nio.charset.CoderResult)

Example 14 with CoderResult

use of java.nio.charset.CoderResult in project hs4j by killme2008.

the class AbstractIoBuffer method getString.

/**
     * {@inheritDoc}
     */
@Override
public String getString(int fieldSize, CharsetDecoder decoder) throws CharacterCodingException {
    checkFieldSize(fieldSize);
    if (fieldSize == 0) {
        return "";
    }
    if (!hasRemaining()) {
        return "";
    }
    boolean utf16 = decoder.charset().name().startsWith("UTF-16");
    if (utf16 && (fieldSize & 1) != 0) {
        throw new IllegalArgumentException("fieldSize is not even.");
    }
    int oldPos = position();
    int oldLimit = limit();
    int end = oldPos + fieldSize;
    if (oldLimit < end) {
        throw new BufferUnderflowException();
    }
    int i;
    if (!utf16) {
        for (i = oldPos; i < end; i++) {
            if (get(i) == 0) {
                break;
            }
        }
        if (i == end) {
            limit(end);
        } else {
            limit(i);
        }
    } else {
        for (i = oldPos; i < end; i += 2) {
            if (get(i) == 0 && get(i + 1) == 0) {
                break;
            }
        }
        if (i == end) {
            limit(end);
        } else {
            limit(i);
        }
    }
    if (!hasRemaining()) {
        limit(oldLimit);
        position(end);
        return "";
    }
    decoder.reset();
    int expectedLength = (int) (remaining() * decoder.averageCharsPerByte()) + 1;
    CharBuffer out = CharBuffer.allocate(expectedLength);
    for (; ; ) {
        CoderResult cr;
        if (hasRemaining()) {
            cr = decoder.decode(buf(), out, true);
        } else {
            cr = decoder.flush(out);
        }
        if (cr.isUnderflow()) {
            break;
        }
        if (cr.isOverflow()) {
            CharBuffer o = CharBuffer.allocate(out.capacity() + expectedLength);
            out.flip();
            o.put(out);
            out = o;
            continue;
        }
        if (cr.isError()) {
            // Revert the buffer back to the previous state.
            limit(oldLimit);
            position(oldPos);
            cr.throwException();
        }
    }
    limit(oldLimit);
    position(end);
    return out.flip().toString();
}
Also used : CharBuffer(java.nio.CharBuffer) BufferUnderflowException(java.nio.BufferUnderflowException) CoderResult(java.nio.charset.CoderResult)

Example 15 with CoderResult

use of java.nio.charset.CoderResult in project hs4j by killme2008.

the class AbstractIoBuffer method putString.

/**
     * {@inheritDoc}
     */
@Override
public IoBuffer putString(CharSequence val, int fieldSize, CharsetEncoder encoder) throws CharacterCodingException {
    checkFieldSize(fieldSize);
    if (fieldSize == 0) {
        return this;
    }
    autoExpand(fieldSize);
    boolean utf16 = encoder.charset().name().startsWith("UTF-16");
    if (utf16 && (fieldSize & 1) != 0) {
        throw new IllegalArgumentException("fieldSize is not even.");
    }
    int oldLimit = limit();
    int end = position() + fieldSize;
    if (oldLimit < end) {
        throw new BufferOverflowException();
    }
    if (val.length() == 0) {
        if (!utf16) {
            put((byte) 0x00);
        } else {
            put((byte) 0x00);
            put((byte) 0x00);
        }
        position(end);
        return this;
    }
    CharBuffer in = CharBuffer.wrap(val);
    limit(end);
    encoder.reset();
    for (; ; ) {
        CoderResult cr;
        if (in.hasRemaining()) {
            cr = encoder.encode(in, buf(), true);
        } else {
            cr = encoder.flush(buf());
        }
        if (cr.isUnderflow() || cr.isOverflow()) {
            break;
        }
        cr.throwException();
    }
    limit(oldLimit);
    if (position() < end) {
        if (!utf16) {
            put((byte) 0x00);
        } else {
            put((byte) 0x00);
            put((byte) 0x00);
        }
    }
    position(end);
    return this;
}
Also used : CharBuffer(java.nio.CharBuffer) BufferOverflowException(java.nio.BufferOverflowException) CoderResult(java.nio.charset.CoderResult)

Aggregations

CoderResult (java.nio.charset.CoderResult)123 CharBuffer (java.nio.CharBuffer)81 ByteBuffer (java.nio.ByteBuffer)35 IOException (java.io.IOException)25 CharsetDecoder (java.nio.charset.CharsetDecoder)25 Charset (java.nio.charset.Charset)15 CharacterCodingException (java.nio.charset.CharacterCodingException)13 CharsetEncoder (java.nio.charset.CharsetEncoder)13 BufferUnderflowException (java.nio.BufferUnderflowException)3 BufferOverflowException (java.nio.BufferOverflowException)2 CloseReason (javax.websocket.CloseReason)2 ArrayDecoder (sun.nio.cs.ArrayDecoder)2 ArrayEncoder (sun.nio.cs.ArrayEncoder)2 JSONException (com.alibaba.fastjson.JSONException)1 SimpleDiagnosticPosition (com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition)1 ParseException (io.druid.java.util.common.parsers.ParseException)1 IllegalCharsetNameException (java.nio.charset.IllegalCharsetNameException)1 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)1 GeneralSecurityException (java.security.GeneralSecurityException)1 Cipher (javax.crypto.Cipher)1