Java ByteBuffer Decode decodeLength(ByteBuffer buf)

Here you can find the source of decodeLength(ByteBuffer buf)

Description

Decode octets and extract the length information from a DER-encoded message.

License

Open Source License

Parameter

Parameter Description
buf the DER-encoded data buffer with position immediately after the DER-identifier octets

Return

the length of the DER-encoded contents

Declaration

public static int decodeLength(ByteBuffer buf) 

Method Source Code

//package com.java2s;
/**/*from w  w  w.  j a  v  a2s  . co m*/
 * Copyright 2007-2016, Kaazing Corporation. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.nio.ByteBuffer;

public class Main {
    /**
     * Decode octets and extract the length information from a DER-encoded message.
     *
     * @param buf
     *            the DER-encoded data buffer with position immediately after the DER-identifier octets
     * @return the length of the DER-encoded contents
     */
    public static int decodeLength(ByteBuffer buf) {
        if (buf == null || buf.remaining() == 0) {
            throw new IllegalArgumentException("Null or empty buffer");
        }

        int len = 0;

        byte first = buf.get();
        if (first >> 7 == 0) {
            // Bit 8 is zero: Short form
            len = first & 0x7f;
        } else {
            // Bit 8 is one: Long form
            // Bit 7-1 represents number of subsequent octets
            int numOctets = first & 0x7f;
            if (buf.remaining() < numOctets) {
                throw new IllegalArgumentException(
                        "Insufficient data to decode long-form DER length");
            }

            // Combine subsequent octets to compute length
            for (int i = 0; i < numOctets; i++) {
                len = (len << 8) + (0xff & buf.get());
            }
        }

        return len;
    }
}

Related

  1. decodeASCII(ByteBuffer buffer, int length, int offset)
  2. decodeBuffer(ByteBuffer buffer, String charsetName)
  3. decodeDouble(ByteBuffer bb)
  4. decodeInt(ByteBuffer buffer, int start)
  5. decodeIO(String encoding, ByteBuffer bbuf)
  6. decodeLong(ByteBuffer buffer, int start)
  7. decodeNIO(String encoding, ByteBuffer bbuf)
  8. decodeNumber(byte firstByte, ByteBuffer buffer)
  9. decodeStoredBits(ByteBuffer bb)