Java Code Examples for org.apache.poi.util.LittleEndian

The following examples show how to use org.apache.poi.util.LittleEndian. These examples are extracted from open source projects. 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 Project: lams   Source File: PropertySet.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Checks whether a byte array is in the Horrible Property Set Format.
 *
 * @param src The byte array to check.
 * @param offset The offset in the byte array.
 * @param length The significant number of bytes in the byte
 * array. Only this number of bytes will be checked.
 * @return {@code true} if the byte array is a property set
 * stream, {@code false} if not.
 */
public static boolean isPropertySetStream(final byte[] src, final int offset, final int length) {
    /* FIXME (3): Ensure that at most "length" bytes are read. */

    /*
     * Read the header fields of the stream. They must always be
     * there.
     */
    int o = offset;
    final int byteOrder = LittleEndian.getUShort(src, o);
    o += LittleEndianConsts.SHORT_SIZE;
    if (byteOrder != BYTE_ORDER_ASSERTION) {
        return false;
    }
    final int format = LittleEndian.getUShort(src, o);
    o += LittleEndianConsts.SHORT_SIZE;
    if (format != FORMAT_ASSERTION) {
        return false;
    }
    // final long osVersion = LittleEndian.getUInt(src, offset);
    o += LittleEndianConsts.INT_SIZE;
    // final ClassID classID = new ClassID(src, offset);
    o += ClassID.LENGTH;
    final long sectionCount = LittleEndian.getUInt(src, o);
    return (sectionCount >= 0);
}
 
Example 2
Source Project: lams   Source File: Property.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a {@link Property} instance by reading its bytes
 * from the property set stream.
 *
 * @param id The property's ID.
 * @param src The bytes the property set stream consists of.
 * @param offset The property's type/value pair's offset in the
 * section.
 * @param length The property's type/value pair's length in bytes.
 * @param codepage The section's and thus the property's
 * codepage. It is needed only when reading string values.
 * @exception UnsupportedEncodingException if the specified codepage is not
 * supported.
 */
public Property(final long id, final byte[] src, final long offset, final int length, final int codepage)
throws UnsupportedEncodingException {
    this.id = id;

    /*
     * ID 0 is a special case since it specifies a dictionary of
     * property IDs and property names.
     */
    if (id == 0) {
        throw new UnsupportedEncodingException("Dictionary not allowed here");
    }

    int o = (int) offset;
    type = LittleEndian.getUInt(src, o);
    o += LittleEndianConsts.INT_SIZE;

    try {
        value = VariantSupport.read(src, o, length, (int) type, codepage);
    } catch (UnsupportedVariantTypeException ex) {
        VariantSupport.writeUnsupportedTypeMessage(ex);
        value = ex.getValue();
    }
}
 
Example 3
Source Project: lams   Source File: Property.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
     * Writes the property to an output stream.
     *
     * @param out The output stream to write to.
     * @param codepage The codepage to use for writing non-wide strings
     * @return the number of bytes written to the stream
     *
     * @exception IOException if an I/O error occurs
     * @exception WritingNotSupportedException if a variant type is to be
     * written that is not yet supported
     */
    public int write(final OutputStream out, final int codepage)
    throws IOException, WritingNotSupportedException {
        int length = 0;
        long variantType = getType();

        /* Ensure that wide strings are written if the codepage is Unicode. */
//        if (codepage == CodePageUtil.CP_UNICODE && variantType == Variant.VT_LPSTR) {
//            variantType = Variant.VT_LPWSTR;
//        }

        if (variantType == Variant.VT_LPSTR && codepage != CodePageUtil.CP_UTF16) {
            String csStr = CodePageUtil.codepageToEncoding(codepage > 0 ? codepage : Property.DEFAULT_CODEPAGE);
            if (!Charset.forName(csStr).newEncoder().canEncode((String)value)) {
                variantType = Variant.VT_LPWSTR;
            }
        }

        LittleEndian.putUInt(variantType, out);
        length += LittleEndianConsts.INT_SIZE;
        length += VariantSupport.write(out, variantType, getValue(), codepage);
        return length;
    }
 
Example 4
Source Project: lams   Source File: ImageHeaderWMF.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void write(OutputStream out) throws IOException {
    byte[] header = new byte[22];
    int pos = 0;
    LittleEndian.putInt(header, pos, APMHEADER_KEY); pos += LittleEndian.INT_SIZE; //header key
    LittleEndian.putUShort(header, pos, 0); pos += LittleEndian.SHORT_SIZE; //hmf
    LittleEndian.putUShort(header, pos, left); pos += LittleEndian.SHORT_SIZE; //left
    LittleEndian.putUShort(header, pos, top); pos += LittleEndian.SHORT_SIZE; //top
    LittleEndian.putUShort(header, pos, right); pos += LittleEndian.SHORT_SIZE; //right
    LittleEndian.putUShort(header, pos, bottom); pos += LittleEndian.SHORT_SIZE; //bottom
    LittleEndian.putUShort(header, pos, inch); pos += LittleEndian.SHORT_SIZE; //inch
    LittleEndian.putInt(header, pos, 0); pos += LittleEndian.INT_SIZE;  //reserved

    checksum = getChecksum();
    LittleEndian.putUShort(header, pos, checksum);

    out.write(header);
}
 
Example 5
Source Project: lams   Source File: BinaryRC4Decryptor.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected static Cipher initCipherForBlock(Cipher cipher, int block,
    EncryptionInfo encryptionInfo, SecretKey skey, int encryptMode)
throws GeneralSecurityException {
    EncryptionVerifier ver = encryptionInfo.getVerifier();
    HashAlgorithm hashAlgo = ver.getHashAlgorithm();
    byte blockKey[] = new byte[4];
    LittleEndian.putUInt(blockKey, 0, block);
    byte encKey[] = CryptoFunctions.generateKey(skey.getEncoded(), hashAlgo, blockKey, 16);
    SecretKey key = new SecretKeySpec(encKey, skey.getAlgorithm());
    if (cipher == null) {
        EncryptionHeader em = encryptionInfo.getHeader();
        cipher = CryptoFunctions.getCipher(key, em.getCipherAlgorithm(), null, null, encryptMode);
    } else {
        cipher.init(encryptMode, key);
    }
    return cipher;
}
 
Example 6
Source Project: lams   Source File: EscherChildAnchorRecord.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public int fillFields(byte[] data, int offset, EscherRecordFactory recordFactory) {
    int bytesRemaining = readHeader( data, offset );
    int pos            = offset + 8;
    int size           = 0;
    switch (bytesRemaining) {
    case 16: // RectStruct
        field_1_dx1 =  LittleEndian.getInt( data, pos + size );size+=4;
        field_2_dy1 =  LittleEndian.getInt( data, pos + size );size+=4;
        field_3_dx2 =  LittleEndian.getInt( data, pos + size );size+=4;
        field_4_dy2 =  LittleEndian.getInt( data, pos + size );size+=4;
        break;
    case 8: // SmallRectStruct
        field_1_dx1 =  LittleEndian.getShort( data, pos + size );size+=2;
        field_2_dy1 =  LittleEndian.getShort( data, pos + size );size+=2;
        field_3_dx2 =  LittleEndian.getShort( data, pos + size );size+=2;
        field_4_dy2 =  LittleEndian.getShort( data, pos + size );size+=2;
        break;
    default:
        throw new RuntimeException("Invalid EscherChildAnchorRecord - neither 8 nor 16 bytes.");
    }
        
    return 8 + size;
}
 
Example 7
Source Project: lams   Source File: StandardDecryptor.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected static SecretKey generateSecretKey(String password, EncryptionVerifier ver, int keySize) {
    HashAlgorithm hashAlgo = ver.getHashAlgorithm();

    byte pwHash[] = hashPassword(password, hashAlgo, ver.getSalt(), ver.getSpinCount());

    byte[] blockKey = new byte[4];
    LittleEndian.putInt(blockKey, 0, 0);

    byte[] finalHash = CryptoFunctions.generateKey(pwHash, hashAlgo, blockKey, hashAlgo.hashSize);
    byte x1[] = fillAndXor(finalHash, (byte) 0x36);
    byte x2[] = fillAndXor(finalHash, (byte) 0x5c);

    byte[] x3 = new byte[x1.length + x2.length];
    System.arraycopy(x1, 0, x3, 0, x1.length);
    System.arraycopy(x2, 0, x3, x1.length, x2.length);
    
    byte[] key = Arrays.copyOf(x3, keySize);

    SecretKey skey = new SecretKeySpec(key, ver.getCipherAlgorithm().jceId);
    return skey;
}
 
Example 8
Source Project: lams   Source File: EscherTextboxRecord.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public int serialize( int offset, byte[] data, EscherSerializationListener listener )
{
    listener.beforeRecordSerialize( offset, getRecordId(), this );

    LittleEndian.putShort(data, offset, getOptions());
    LittleEndian.putShort(data, offset+2, getRecordId());
    int remainingBytes = thedata.length;
    LittleEndian.putInt(data, offset+4, remainingBytes);
    System.arraycopy(thedata, 0, data, offset+8, thedata.length);
    int pos = offset+8+thedata.length;

    listener.afterRecordSerialize( pos, getRecordId(), pos - offset, this );
    int size = pos - offset;
    if (size != getRecordSize()) {
        throw new RecordFormatException(size + " bytes written but getRecordSize() reports " + getRecordSize());
    }
    return size;
}
 
Example 9
Source Project: lams   Source File: EscherSpRecord.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
     * This method serializes this escher record into a byte array.
     *
     * @param offset   The offset into <code>data</code> to start writing the record data to.
     * @param data     The byte array to serialize to.
     * @param listener A listener to retrieve start and end callbacks.  Use a <code>NullEscherSerailizationListener</code> to ignore these events.
     * @return The number of bytes written.
     *
     * @see NullEscherSerializationListener
     */
    @Override
    public int serialize( int offset, byte[] data, EscherSerializationListener listener )
    {
        listener.beforeRecordSerialize( offset, getRecordId(), this );
        LittleEndian.putShort( data, offset, getOptions() );
        LittleEndian.putShort( data, offset + 2, getRecordId() );
        int remainingBytes = 8;
        LittleEndian.putInt( data, offset + 4, remainingBytes );
        LittleEndian.putInt( data, offset + 8, field_1_shapeId );
        LittleEndian.putInt( data, offset + 12, field_2_flags );
//        System.arraycopy( remainingData, 0, data, offset + 26, remainingData.length );
//        int pos = offset + 8 + 18 + remainingData.length;
        listener.afterRecordSerialize( offset + getRecordSize(), getRecordId(), getRecordSize(), this );
        return 8 + 8;
    }
 
Example 10
Source Project: lams   Source File: Formula.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets the locator for the corresponding {@link org.apache.poi.hssf.record.SharedFormulaRecord},
    * {@link org.apache.poi.hssf.record.ArrayRecord} or {@link org.apache.poi.hssf.record.TableRecord}
    * if this formula belongs to such a grouping.  The {@link CellReference}
 * returned by this method will  match the top left corner of the range of that grouping.
 * The return value is usually not the same as the location of the cell containing this formula.
 *
 * @return the firstRow &amp; firstColumn of an array formula or shared formula that this formula
 * belongs to.  <code>null</code> if this formula is not part of an array or shared formula.
 */
public CellReference getExpReference() {
	byte[] data = _byteEncoding;
	if (data.length != 5) {
		// tExp and tTbl are always 5 bytes long, and the only ptg in the formula
		return null;
	}
	switch (data[0]) {
		case ExpPtg.sid:
			break;
		case TblPtg.sid:
			break;
		default:
			return null;
	}
	int firstRow = LittleEndian.getUShort(data, 1);
	int firstColumn = LittleEndian.getUShort(data, 3);
	return new CellReference(firstRow, firstColumn);
}
 
Example 11
Source Project: lams   Source File: BiffViewer.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void fillNextBuffer() throws IOException {
	if (_innerHasReachedEOF) {
		return;
	}
	int b0 = _is.read();
	if (b0 == -1) {
		_innerHasReachedEOF = true;
		return;
	}
	_data[0] = (byte) b0;
	_is.readFully(_data, 1, 3);
	int len = LittleEndian.getShort(_data, 2);
	_is.readFully(_data, 4, len);
	_currentPos = 0;
	_currentSize = len + 4;
	_recordCounter++;
}
 
Example 12
@Override
public int serialize(int offset, byte[] data)
{
    LittleEndian.putShort( data, 0 + offset, getSid() );
    LittleEndian.putShort( data, 2 + offset, (short) ( getRecordSize() - 4 ) );
    byte[] rawData = getRawData();
    if ( escherRecords.size() == 0 && rawData != null )
    {
        LittleEndian.putShort(data, 0 + offset, getSid());
        LittleEndian.putShort(data, 2 + offset, (short)(getRecordSize() - 4));
        System.arraycopy( rawData, 0, data, 4 + offset, rawData.length);
        return rawData.length + 4;
    }
    LittleEndian.putShort(data, 0 + offset, getSid());
    LittleEndian.putShort(data, 2 + offset, (short)(getRecordSize() - 4));

    int pos = offset + 4;
    for (EscherRecord r : escherRecords) {
        pos += r.serialize( pos, data, new NullEscherSerializationListener() );
    }
    return getRecordSize();
}
 
Example 13
Source Project: lams   Source File: EscherSpgrRecord.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
    public int serialize( int offset, byte[] data, EscherSerializationListener listener )
    {
        listener.beforeRecordSerialize( offset, getRecordId(), this );
        LittleEndian.putShort( data, offset, getOptions() );
        LittleEndian.putShort( data, offset + 2, getRecordId() );
        int remainingBytes = 16;
        LittleEndian.putInt( data, offset + 4, remainingBytes );
        LittleEndian.putInt( data, offset + 8, field_1_rectX1 );
        LittleEndian.putInt( data, offset + 12, field_2_rectY1 );
        LittleEndian.putInt( data, offset + 16, field_3_rectX2 );
        LittleEndian.putInt( data, offset + 20, field_4_rectY2 );
//        System.arraycopy( remainingData, 0, data, offset + 26, remainingData.length );
//        int pos = offset + 8 + 18 + remainingData.length;
        listener.afterRecordSerialize( offset + getRecordSize(), getRecordId(), offset + getRecordSize(), this );
        return 8 + 16;
    }
 
Example 14
Source Project: lams   Source File: EscherBitmapBlip.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public int serialize( int offset, byte[] data, EscherSerializationListener listener ) {
    listener.beforeRecordSerialize(offset, getRecordId(), this);

    LittleEndian.putShort( data, offset, getOptions() );
    LittleEndian.putShort( data, offset + 2, getRecordId() );
    LittleEndian.putInt( data, offset + 4, getRecordSize() - HEADER_SIZE );
    int pos = offset + HEADER_SIZE;

    System.arraycopy( field_1_UID, 0, data, pos, 16 );
    data[pos + 16] = field_2_marker;
    byte pd[] = getPicturedata();
    System.arraycopy( pd, 0, data, pos + 17, pd.length );

    listener.afterRecordSerialize(offset + getRecordSize(), getRecordId(), getRecordSize(), this);
    return HEADER_SIZE + 16 + 1 + pd.length;
}
 
Example 15
Source Project: lams   Source File: EscherPictBlip.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public int serialize(int offset, byte[] data, EscherSerializationListener listener) {
    listener.beforeRecordSerialize(offset, getRecordId(), this);

    int pos = offset;
    LittleEndian.putShort( data, pos, getOptions() ); pos += 2;
    LittleEndian.putShort( data, pos, getRecordId() ); pos += 2;
    LittleEndian.putInt( data, 0, getRecordSize() - HEADER_SIZE ); pos += 4;

    System.arraycopy( field_1_UID, 0, data, pos, 16 ); pos += 16;
    LittleEndian.putInt( data, pos, field_2_cb ); pos += 4;
    LittleEndian.putInt( data, pos, field_3_rcBounds_x1 ); pos += 4;
    LittleEndian.putInt( data, pos, field_3_rcBounds_y1 ); pos += 4;
    LittleEndian.putInt( data, pos, field_3_rcBounds_x2 ); pos += 4;
    LittleEndian.putInt( data, pos, field_3_rcBounds_y2 ); pos += 4;
    LittleEndian.putInt( data, pos, field_4_ptSize_w ); pos += 4;
    LittleEndian.putInt( data, pos, field_4_ptSize_h ); pos += 4;
    LittleEndian.putInt( data, pos, field_5_cbSave ); pos += 4;
    data[pos] = field_6_fCompression; pos++;
    data[pos] = field_7_fFilter; pos++;

    System.arraycopy( raw_pictureData, 0, data, pos, raw_pictureData.length );

    listener.afterRecordSerialize(offset + getRecordSize(), getRecordId(), getRecordSize(), this);
    return HEADER_SIZE + 16 + 1 + raw_pictureData.length;
}
 
Example 16
Source Project: lams   Source File: EscherSpgrRecord.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
    public int fillFields(byte[] data, int offset, EscherRecordFactory recordFactory) {
        int bytesRemaining = readHeader( data, offset );
        int pos            = offset + 8;
        int size           = 0;
        field_1_rectX1 =  LittleEndian.getInt( data, pos + size );size+=4;
        field_2_rectY1 =  LittleEndian.getInt( data, pos + size );size+=4;
        field_3_rectX2 =  LittleEndian.getInt( data, pos + size );size+=4;
        field_4_rectY2 =  LittleEndian.getInt( data, pos + size );size+=4;
        bytesRemaining -= size;
        if (bytesRemaining != 0) {
            throw new RecordFormatException("Expected no remaining bytes but got " + bytesRemaining);
        }
//        remainingData  =  new byte[bytesRemaining];
//        System.arraycopy( data, pos + size, remainingData, 0, bytesRemaining );
        return 8 + size + bytesRemaining;
    }
 
Example 17
Source Project: lams   Source File: EscherDump.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Dumps out a hex value by reading from a input stream.
 *
 * @param bytes     How many bytes this hex value consists of.
 * @param in        The stream to read the hex value from.
 * @param out       The stream to write the nicely formatted hex value to.
 */
private void outHex( int bytes, InputStream in, PrintStream out ) throws IOException, LittleEndian.BufferUnderrunException
{
    switch ( bytes )
    {
        case 1:
            out.print( HexDump.toHex( (byte) in.read() ) );
            break;
        case 2:
            out.print( HexDump.toHex( LittleEndian.readShort( in ) ) );
            break;
        case 4:
            out.print( HexDump.toHex( LittleEndian.readInt( in ) ) );
            break;
        default:
            throw new IOException( "Unable to output variable of that width" );
    }
}
 
Example 18
Source Project: lams   Source File: PropertySet.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the string representation of a property value
 * 
 * @param propertyValue the property value
 *  
 * @return The property value as a String, or null if unavailable
 */
public static String getPropertyStringValue(final Object propertyValue) {
    // Normal cases
    if (propertyValue == null) {
        return null;
    }
    if (propertyValue instanceof String) {
        return (String)propertyValue;
    }
    
    // Do our best with some edge cases
    if (propertyValue instanceof byte[]) {
        byte[] b = (byte[])propertyValue;
        switch (b.length) {
            case 0:
                return "";
            case 1:
                return Byte.toString(b[0]);
            case 2:
                return Integer.toString( LittleEndian.getUShort(b) );
            case 4:
                return Long.toString( LittleEndian.getUInt(b) );
            default:
                // Maybe it's a string? who knows!
                try {
                    return CodePageUtil.getStringFromCodePage(b, Property.DEFAULT_CODEPAGE);
                } catch (UnsupportedEncodingException e) {
                    // doesn't happen ...
                    return "";
                }
        }
    }
    return propertyValue.toString();
}
 
Example 19
Source Project: lams   Source File: EscherArrayProperty.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Serializes the simple part of this property.  ie the first 6 bytes.
 *
 * Needs special code to handle the case when the size doesn't
 *  include the size of the header block
 */
@Override
public int serializeSimplePart(byte[] data, int pos) {
    LittleEndian.putShort(data, pos, getId());
    int recordSize = getComplexData().length;
    if(!sizeIncludesHeaderSize) {
        recordSize -= 6;
    }
    LittleEndian.putInt(data, pos + 2, recordSize);
    return 6;
}
 
Example 20
Source Project: lams   Source File: TypeWriter.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Writes an unsigned two-byte value to an output stream.</p>
 *
 * @param out The stream to write to
 * @param n The value to write
 * @exception IOException if an I/O error occurs
 */
public static void writeUShortToStream( final OutputStream out, final int n )
        throws IOException
{
    int high = n & 0xFFFF0000;
    if ( high != 0 ) {
        throw new IllegalPropertySetDataException( "Value " + n
                + " cannot be represented by 2 bytes." );
    }
    LittleEndian.putUShort( n, out );
}
 
Example 21
Source Project: lams   Source File: TypeWriter.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Writes an unsigned four-byte value to an output stream.</p>
 *
 * @param out The stream to write to.
 * @param n The value to write.
 * @return The number of bytes that have been written to the output stream.
 * @exception IOException if an I/O error occurs
 */
public static int writeUIntToStream( final OutputStream out, final long n )
        throws IOException
{
    long high = n & 0xFFFFFFFF00000000L;
    if ( high != 0 && high != 0xFFFFFFFF00000000L ) {
        throw new IllegalPropertySetDataException( "Value " + n
                + " cannot be represented by 4 bytes." );
    }
    LittleEndian.putUInt( n, out );
    return LittleEndianConsts.INT_SIZE;
}
 
Example 22
Source Project: lams   Source File: ImageHeaderWMF.java    License: GNU General Public License v2.0 5 votes vote down vote up
public ImageHeaderWMF(byte[] data, final int off) {
    int offset = off;
    int key = LittleEndian.getInt(data, offset); offset += LittleEndian.INT_SIZE; //header key
    if (key != APMHEADER_KEY) {
        LOG.log(POILogger.WARN, "WMF file doesn't contain a placeable header - ignore parsing");
        handle = 0;
        left = 0;
        top = 0;
        right = 200;
        bottom = 200;
        inch = Units.POINT_DPI; //default resolution is 72 dpi
        reserved = 0;
        return;
    }

    handle = LittleEndian.getUShort(data, offset); offset += LittleEndian.SHORT_SIZE;
    left = LittleEndian.getShort(data, offset); offset += LittleEndian.SHORT_SIZE;
    top = LittleEndian.getShort(data, offset); offset += LittleEndian.SHORT_SIZE;
    right = LittleEndian.getShort(data, offset); offset += LittleEndian.SHORT_SIZE;
    bottom = LittleEndian.getShort(data, offset); offset += LittleEndian.SHORT_SIZE;

    inch = LittleEndian.getUShort(data, offset); offset += LittleEndian.SHORT_SIZE;
    reserved = LittleEndian.getInt(data, offset); offset += LittleEndian.INT_SIZE;

    checksum = LittleEndian.getShort(data, offset); offset += LittleEndian.SHORT_SIZE;
    if (checksum != getChecksum()){
        LOG.log(POILogger.WARN, "WMF checksum does not match the header data");
    }
}
 
Example 23
Source Project: lams   Source File: EscherDgRecord.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
    public int fillFields(byte[] data, int offset, EscherRecordFactory recordFactory) {
        /*int bytesRemaining =*/ readHeader( data, offset );
        int pos            = offset + 8;
        int size           = 0;
        field_1_numShapes   =  LittleEndian.getInt( data, pos + size );     size += 4;
        field_2_lastMSOSPID =  LittleEndian.getInt( data, pos + size );     size += 4;
//        bytesRemaining -= size;
//        remainingData  =  new byte[bytesRemaining];
//        System.arraycopy( data, pos + size, remainingData, 0, bytesRemaining );
        return getRecordSize();
    }
 
Example 24
Source Project: lams   Source File: NDocumentInputStream.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public long readLong() {
	checkAvaliable(SIZE_LONG);
	byte[] data = new byte[SIZE_LONG];
	readFully(data, 0, SIZE_LONG);
	return LittleEndian.getLong(data, 0);
}
 
Example 25
Source Project: lams   Source File: NDocumentInputStream.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public short readShort() {
   checkAvaliable(SIZE_SHORT);
   byte[] data = new byte[SIZE_SHORT];
   readFully(data, 0, SIZE_SHORT);
   return LittleEndian.getShort(data);
}
 
Example 26
Source Project: lams   Source File: EscherArrayProperty.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void setNumberOfElementsInArray(int numberOfElements) {
    int expectedArraySize = numberOfElements * getActualSizeOfElements(getSizeOfElements()) + FIXED_SIZE;
    if (expectedArraySize != getComplexData().length) {
        byte[] newArray = new byte[expectedArraySize];
        System.arraycopy(getComplexData(), 0, newArray, 0, getComplexData().length);
        setComplexData(newArray);
    }
    LittleEndian.putShort(getComplexData(), 0, (short) numberOfElements);
}
 
Example 27
Source Project: lams   Source File: EscherBlipRecord.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public int serialize(int offset, byte[] data, EscherSerializationListener listener) {
    listener.beforeRecordSerialize(offset, getRecordId(), this);

    LittleEndian.putShort( data, offset, getOptions() );
    LittleEndian.putShort( data, offset + 2, getRecordId() );

    System.arraycopy( field_pictureData, 0, data, offset + 4, field_pictureData.length );

    listener.afterRecordSerialize(offset + 4 + field_pictureData.length, getRecordId(), field_pictureData.length + 4, this);
    return field_pictureData.length + 4;
}
 
Example 28
Source Project: lams   Source File: XORDecryptor.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean verifyPassword(String password) {
    XOREncryptionVerifier ver = (XOREncryptionVerifier)getEncryptionInfo().getVerifier();
    int keyVer = LittleEndian.getUShort(ver.getEncryptedKey());
    int verifierVer = LittleEndian.getUShort(ver.getEncryptedVerifier());
    int keyComp      = CryptoFunctions.createXorKey1(password);
    int verifierComp = CryptoFunctions.createXorVerifier1(password);
    if (keyVer == keyComp && verifierVer == verifierComp) {
        byte xorArray[] = CryptoFunctions.createXorArray1(password);
        setSecretKey(new SecretKeySpec(xorArray, "XOR"));
        return true;
    } else {
        return false;
    }
}
 
Example 29
@Override
public void processPOIFSWriterEvent(POIFSWriterEvent event) {
    try {
        OutputStream os = event.getStream();

        // StreamSize (8 bytes): An unsigned integer that specifies the number of bytes used by data
        // encrypted within the EncryptedData field, not including the size of the StreamSize field.
        // Note that the actual size of the \EncryptedPackage stream (1) can be larger than this
        // value, depending on the block size of the chosen encryption algorithm
        byte buf[] = new byte[LittleEndianConsts.LONG_SIZE];
        LittleEndian.putLong(buf, 0, pos);
        os.write(buf);

        FileInputStream fis = new FileInputStream(fileOut);
        try {
            IOUtils.copy(fis, os);
        } finally {
            fis.close();
        }

        os.close();

        if (!fileOut.delete()) {
            LOG.log(POILogger.ERROR, "Can't delete temporary encryption file: "+fileOut);
        }
    } catch (IOException e) {
        throw new EncryptedDocumentException(e);
    }
}
 
Example 30
Source Project: lams   Source File: CryptoFunctions.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Generalized method for read and write protection hash generation.
 * The difference is, read protection uses the order iterator then hash in the hash loop, whereas write protection
 * uses first the last hash value and then the current iterator value
 *
 * @param password
 * @param hashAlgorithm
 * @param salt
 * @param spinCount
 * @param iteratorFirst if true, the iterator is hashed before the n-1 hash value,
 *        if false the n-1 hash value is applied first
 * @return the hashed password
 */
public static byte[] hashPassword(String password, HashAlgorithm hashAlgorithm, byte salt[], int spinCount, boolean iteratorFirst) {
    // If no password was given, use the default
    if (password == null) {
        password = Decryptor.DEFAULT_PASSWORD;
    }
    
    MessageDigest hashAlg = getMessageDigest(hashAlgorithm);
    
    hashAlg.update(salt);
    byte[] hash = hashAlg.digest(StringUtil.getToUnicodeLE(password));
    byte[] iterator = new byte[LittleEndianConsts.INT_SIZE];

    byte[] first = (iteratorFirst ? iterator : hash);
    byte[] second = (iteratorFirst ? hash : iterator);
    
    try {
        for (int i = 0; i < spinCount; i++) {
            LittleEndian.putInt(iterator, 0, i);
            hashAlg.reset();
            hashAlg.update(first);
            hashAlg.update(second);
            hashAlg.digest(hash, 0, hash.length); // don't create hash buffer everytime new
        }
    } catch (DigestException e) {
        throw new EncryptedDocumentException("error in password hashing");
    }
    
    return hash;
}